middlewares.js 903 Bytes
Newer Older
CHAERIN KIM's avatar
CHAERIN KIM committed
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
const jwt = require('jsonwebtoken');

exports.isLoggedIn = (req, res, next) => {
  if (req.isAuthenticated()) {
    next();
  } else {
    res.status(403).send('로그인 필요');
  }
};

exports.isNotLoggedIn = (req, res, next) => {
  if (!req.isAuthenticated()) {
    next();
  } else {
    res.redirect('/');
  }
};

exports.verifyToken = (req, res, next) => {
  try {
    req.decoded = jwt.verify(req.headers.authorization, process.env.JWT_SECRET);
    console.log('decode', req.decoded)
    return next();
  } catch (error) {
    if (error.name === 'TokenExpiredError') { // 유효기간 초과
      return res.status(419).json({
        code: 419,
        error: '토큰이 만료되었습니다. 다시 로그인 해주세요.',
      });
    }
    return res.status(401).json({
      code: 401,
      error: '유효하지 않은 토큰입니다. 다시 로그인 해주세요.',
    });
  }
Kim, Subin's avatar
Kim, Subin committed
36
};