Description of key algorithms - nhash46/Tessagon-e-Portfolio GitHub Wiki
This page explains the mechanism of algorithms implemented in the final product.
Authentication - (Passport.js, Bcrypt.js)
Bcrypt.js is used to to hash user passwords before storing them in the database. It takes care of hashing the strings, comparing plain strings with hashes, and appending salt.
When a user attempts to login, their request will either be sent to LocalStrategy or GoogleStrategy depending on their selected login method. If bcryprt.compare() authorizes the request, the browser will be designated a session cookie, and the user's object will be returned and stored in the request object.
Authentication via Passport - LocalStrategy
Sourced from /config/passport.js (line 10 - 29)
passport.use(new LocalStrategy((username, password, done) => {
// Match username
let query = {username:username};
User.findOne(query, (err, user) => {
if(err) throw err;
if(!user){
return done(null, false, {message: 'No user found'})
}
// Match password
bcrypt.compare(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
return done(null, user, {message: 'Successful sign in'});
} else {
return done(null, false, {message: 'Wrong password'})
}
});
});
}));
Authentication via Passport - GoogleStrategy
Sourced from /config/passport.js (line 31 - 58)
passport.use(new GoogleStrategy({
clientID: google.GOOGLE.client_id,
clientSecret: google.GOOGLE.client_secret,
callbackURL: "http://localhost:3000/user/auth/google/callback"
},
(accessToken, refreshToken, profile, cb) => {
// check if user exists
User.findOne({googleId: profile.id}).then((currUser) => {
//console.log(profile);
if(currUser){
//console.log('user is' + currUser);
cb(null, currUser);
} else {
new User({
googleId: profile.id,
username: profile.displayName,
email: profile._json.email,
first_name: profile.name.givenName,
last_name: profile.name.familyName
}).save().then((newUser) => {
cb(null, newUser);
});
}
});
}
));
Hashing new password via Bcrypt.js
Sourced from /controllers/userController.js/addUser (line 74 - 91)
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err){
console.log(err);
}
newUser.password = hash;
// add user to database
newUser.save((err) => {
if (err) {
console.log(err);
} else {
next();
}
});
});
});