-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.ts
48 lines (44 loc) · 1.35 KB
/
auth.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
import * as passportJWT from 'passport-jwt';
import * as jwt from 'jsonwebtoken';
import * as express from 'express';
export function initialize(passport: any, app: express.Express, jwtKey: string) {
passport.use(new passportJWT.Strategy(
{
secretOrKey: jwtKey,
jwtFromRequest: passportJWT.ExtractJwt.fromExtractors([
passportJWT.ExtractJwt.fromAuthHeaderWithScheme('jwt'),
passportJWT.ExtractJwt.fromUrlQueryParameter('token')
])
},
(jwt_payload, done) => {
done(null, jwt_payload);
}
));
// Inicializa passport
app.use(passport.initialize());
return passport;
}
function getToken(req: express.Request) {
if (req.headers && req.headers.authorization) {
return req.headers.authorization.substring(4);
} else if (req.query.token) {
return req.query.token;
}
return null;
}
export const optionalAuth = (jwtKey: string) => {
return (req: any, res: any, next: any) => {
try {
const token = getToken(req);
if (token) {
const tokenData = jwt.verify((token as string), jwtKey);
if (tokenData) {
req.user = tokenData;
}
}
next();
} catch (e) {
next();
}
};
};