Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Development #4

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
0512295
fix: mongoose strict error
KOTTAGENVH Sep 25, 2024
68889dd
feat: Oauth adde to backend
KOTTAGENVH Sep 25, 2024
ad195a8
feat: update passport jwt code base
KOTTAGENVH Sep 25, 2024
d43a2c5
Merge pull request #2 from anjana-madushan/feature/OAuth
KOTTAGENVH Sep 25, 2024
96073b0
fix: count issue
KOTTAGENVH Sep 25, 2024
b7ef7cc
Merge pull request #3 from anjana-madushan/feature/OAuth
KOTTAGENVH Sep 25, 2024
3a96f1f
feat: Token update
KOTTAGENVH Sep 25, 2024
691e948
fix: redux issue
KOTTAGENVH Sep 25, 2024
38293c8
fix: properly format backend response for Redux handling
KOTTAGENVH Sep 25, 2024
30ee2a3
Merge pull request #5 from anjana-madushan/feature/OAuth
KOTTAGENVH Sep 25, 2024
079b33f
implement complete passport-jwt
Priyantha-IT21021534 Sep 25, 2024
0b6b98a
add isAdmin to accessToken
Priyantha-IT21021534 Sep 25, 2024
60eb929
feat: login backend
KOTTAGENVH Sep 26, 2024
79bd504
feat: OAuth Completed
KOTTAGENVH Sep 26, 2024
4dc3765
feat: recaptcha added to login screen
KOTTAGENVH Sep 26, 2024
a6f9ed4
Merge branch 'development' into feature/jwt
KOTTAGENVH Sep 26, 2024
a60042e
Merge pull request #6 from anjana-madushan/feature/jwt
KOTTAGENVH Sep 26, 2024
8425edc
Merge branch 'feature/OAuth' into development
KOTTAGENVH Sep 26, 2024
a33b468
Merge pull request #7 from anjana-madushan/development
KOTTAGENVH Sep 26, 2024
9a7e138
feat: reCaptcha and Oauth configuration completed
KOTTAGENVH Sep 26, 2024
e009f2e
Merge pull request #8 from anjana-madushan/feature/OAuth
KOTTAGENVH Sep 26, 2024
fc3c252
cleaned code
KOTTAGENVH Sep 26, 2024
aed66f8
Merge pull request #9 from anjana-madushan/feature/OAuth
KOTTAGENVH Sep 26, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 56 additions & 6 deletions backend/configs/passport.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,64 @@
const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('./models/User');
require('dotenv').config();
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const passport = require("passport");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const User = require("../models/User");
require("dotenv").config({ path: ".env.local" });


// JWT strategy
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
jwtFromRequest: ExtractJwt.fromExtractors([(req) => req.cookies.accessToken]),
secretOrKey: process.env.JWT_SECRET,
issuer: process.env.ISSUER,
};

passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:4000/auth/google/callback",
passReqToCallback: true,
},
async function (req, accessToken, refreshToken, profile, done) {
try {
// Check if user already exists
let user = await User.findOne({ email: profile.emails[0].value });

if (!user) {
// Create a new user if not found
user = new User({
name: profile.displayName,
email: profile.emails[0].value,
googleId: profile.id,
});
await user.save();
} else {
//Verify user
user = await User.findOne({ email: profile.emails[0].value });
user.googleId = profile.id;
}

done(null, user);
} catch (error) {
console.log(error);
done(error, false);
}
}
)
);

passport.serializeUser((user, done) => {
done(null, user);
});

passport.deserializeUser((user, done) => {
done(null, user);
});

//JWT strategy

passport.use(
new JwtStrategy(opts, async (jwt_payload, done) => {
try {
Expand Down
1 change: 1 addition & 0 deletions backend/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ require('dotenv').config({ path: '.env.local' });
const mongoose = require('mongoose');

const connectionStr = process.env.MONGO_URI;
mongoose.set("strictQuery", false);
mongoose.connect(connectionStr, {useNewUrlparser: true})
.then(() => console.log('connected to mongodb'))
.catch(err => console.log(err))
Expand Down
161 changes: 82 additions & 79 deletions backend/models/User.js
Original file line number Diff line number Diff line change
@@ -1,95 +1,100 @@
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const UserSchema = mongoose.Schema({

name: {
type: String,
required: [true, 'is required']
},

bdate: {
type: String,
required: [true, 'is required']
},

address: {
type: String,
required: [true, 'is required']
},

email: {
type: String,
required: [true, 'is required'],
unique: true,
index: true,
validate: {
validator: function (str) {
return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g.test(str);
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const UserSchema = mongoose.Schema(
{
name: {
type: String,
required: [true, "is required"],
},

bdate: {
type: String,
required: [false, "is required"],
},

address: {
type: String,
required: [false, "is required"],
},

email: {
type: String,
required: [true, "is required"],
unique: true,
index: true,
validate: {
validator: function (str) {
return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g.test(str);
},
message: (props) => `${props.value} is not a valid email`,
},
message: props => `${props.value} is not a valid email`
}
},

password: {
type: String,
required: [true, 'is required']
},
},

password: {
type: String,
required: [false, "is required"],
},

isAdmin: {
type: Boolean,
default: false,
},

cart: {
type: Object,
default: {
total: 0,
count: 0,
},
},

isAdmin: {
type: Boolean,
default: false
},
feedbacks: {
type: Array,
default: [],
},

cart: {
type: Object,
default: {
total: 0,
count: 0
}
},
notifications: {
type: Array,
default: [],
},

feedbacks: {
type: Array,
default: []
},
tokens: {
type: Array,
default: [],
},

notifications: {
type: Array,
default: []
},
googleId: {
type: String,
required: [false, "is required"],
},

tokens: {
type: Array,
default: []
orders: [{ type: mongoose.Schema.Types.ObjectId, ref: "Order" }],
},

orders: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Order' }]

}, { minimize: false });
{ minimize: false }
);

UserSchema.statics.findByCredentials = async function (email, password) {
const user = await User.findOne({ email });
if (!user) throw new Error('invalid credentials');
if (!user) throw new Error("invalid credentials");
const isSamePassword = bcrypt.compareSync(password, user.password);
if (isSamePassword) return user;
throw new Error('invalid credentials');
}
throw new Error("invalid credentials");
};

UserSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject();
delete userObject.password;
delete userObject.tokens;
return userObject;
}
};

//before saving => hash the password
UserSchema.pre('save', function (next) {

UserSchema.pre("save", function (next) {
const user = this;

if (!user.isModified('password')) return next();
if (!user.isModified("password")) return next();

bcrypt.genSalt(10, function (err, salt) {
if (err) return next(err);
Expand All @@ -99,18 +104,16 @@ UserSchema.pre('save', function (next) {

user.password = hash;
next();
})

})

})
});
});
});

//Remove user check

UserSchema.pre('remove', function (next) {
this.model('Order').remove({ owner: this._id }, next);
})
UserSchema.pre("remove", function (next) {
this.model("Order").remove({ owner: this._id }, next);
});

const User = mongoose.model('User', UserSchema);
const User = mongoose.model("User", UserSchema);

module.exports = User;
module.exports = User;
Loading