Showing
1 changed file
with
37 additions
and
0 deletions
back/src/passport.js
0 → 100644
1 | +import passport from "passport"; | ||
2 | +import { Strategy, ExtractJwt } from "passport-jwt"; | ||
3 | +import { prisma } from "./utils"; | ||
4 | + | ||
5 | +const JWTOptions = { | ||
6 | + jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
7 | + secretOrKey: process.env.JWT_SECRET, | ||
8 | +}; | ||
9 | + | ||
10 | +const verifyUser = async (payload, done) => { | ||
11 | + try { | ||
12 | + const user = await prisma.user.findOne({ | ||
13 | + where: { | ||
14 | + id: payload.id, | ||
15 | + }, | ||
16 | + }); | ||
17 | + if (user !== null) { | ||
18 | + return done(null, user); | ||
19 | + } else { | ||
20 | + return done(null, false); | ||
21 | + } | ||
22 | + } catch (error) { | ||
23 | + return done(null, false); | ||
24 | + } | ||
25 | +}; | ||
26 | + | ||
27 | +export const authenticateJWT = (req, res, next) => { | ||
28 | + passport.authenticate("jwt", { session: false }, (error, user) => { | ||
29 | + if (user) { | ||
30 | + req.user = user; | ||
31 | + } | ||
32 | + next(); | ||
33 | + })(req, res, next); | ||
34 | +}; | ||
35 | + | ||
36 | +passport.use(new Strategy(JWTOptions, verifyUser)); | ||
37 | +passport.initialize(); |
-
Please register or login to post a comment