-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthentication.js
65 lines (61 loc) · 2.17 KB
/
authentication.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const JWTstrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
const { User } = require('../models/');
//This verifies that the token sent by the user is valid
passport.use(new JWTstrategy({
//secret we used to sign our JWT
secretOrKey: process.env.JWT_SECRET,
//we expect the user to send the token as a query parameter with the name 'secret_token'
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
}, async (token, done) => {
try {
//Pass the user details to the next middleware
const user = await User.findOne({ where: { email: token.user.email }})
return done(null, user);
} catch (error) {
done(error);
}
}));
//Create a passport middleware to handle user registration
passport.use('signup', new localStrategy({
usernameField: 'email',
passwordField: 'password'
}, async (email, password, done) => {
try {
//Save the information provided by the user to the the database
const user = await User.create({
email,
password
});
//Send the user information to the next middleware
return done(null, user);
} catch (error) {
done(error);
}
}));
//Create a passport middleware to handle User login
passport.use('login', new localStrategy({
usernameField: 'email',
passwordField: 'password'
}, async (email, password, done) => {
try {
//Find the user associated with the email provided by the user
const user = await User.findOne({ where: { email } });
if (!user) {
//If the user isn't found in the database, return a message
return done(null, false, { message: 'User not found' });
}
//Validate password and make sure it matches with the corresponding hash stored in the database
//If the passwords match, it returns a value of true.
const validate = await user.isValidPassword(password);
if (!validate) {
return done(null, false, { message: 'Wrong Password' });
}
//Send the user information to the next middleware
return done(null, user, { message: 'Logged in Successfully' });
} catch (error) {
return done(error);
}
}));