박권수

feat. jwt Middleware

1 +const jwt = require("jsonwebtoken");
2 +const User = require('../models/user');
3 +
4 +const jwtMiddleware = async (ctx, next) => {
5 + const token = ctx.cookies.get("access_token");
6 + if(!token) {
7 + return next();
8 + }
9 +
10 + try {
11 + const decoded = jwt.verify(token, process.env.JWT_SECRET);
12 + ctx.state.user = {
13 + _id : decoded._id,
14 + userId : decoded.userId
15 + };
16 + const now = Math.floor(Date.now() / 1000);
17 + if (decoded.exp - now < 60 * 60 * 24 * 3.5) {
18 + const user = await User.findById(decoded._id);
19 + const token = user.generateToken();
20 +
21 + ctx.cookies.set('access_token', token, {
22 + httpOnly : true,
23 + maxAge : 1000 * 60 * 60 * 24 * 7
24 + })
25 + }
26 +
27 + } catch(e) {
28 + ctx.state.user = null;
29 + }
30 +
31 + return next();
32 +
33 +};
34 +
35 +module.exports = jwtMiddleware;
......