-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticate.ts
66 lines (55 loc) · 1.84 KB
/
authenticate.ts
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
66
import * as passport from 'passport';
import * as passportlocal from 'passport-local';
import * as passportjwt from 'passport-jwt';
import {default as User} from './model/user';
import * as jwt from 'jsonwebtoken';
require('dotenv').config();
const JwtStrategy = passportjwt.Strategy;
const ExtractJwt = passportjwt.ExtractJwt;
const LocalStrategy = passportlocal.Strategy;
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser);
export const getToken = function(user) {
return jwt.sign(user,process.env.SECRET_KEY,
{expiresIn: 3600});
}
var opts = {
jwtFromRequest : ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey : process.env.SECRET_KEY
}
export const jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload,done) => {
console.log('JWT Payload',jwt_payload);
User.findOne({_id: jwt_payload._id},(err,user) => {
if(err){
return done(err,false);
}else if(user){
return done(null,user);
}
else{
return done(null,false);
}
});
}));
interface ErrorWithStatus{
status?: number;
}
export const verifyUser = passport.authenticate('jwt',{session:false});
export const verifyAdmin = ((req,res,next) => {
if (req.user.admin === true){
return next();
}else{
var err = new Error('You are not authorized') as ErrorWithStatus;
err.status = 401;
return next(err);
}
});
export const verifyLogin = passport.authenticate('jwt',{session:false,failureRedirect:'http://localhost:4200/'});
export const verifyLoginAdmin = ((req,res,next) => {
if(req.user.admin === true)
return next();
else{
res.redirect('http://localhost:4200/');
}
})