lang/node

jwtwebtoken

C/H 2019. 4. 12. 12:09

JWT for node.js

# https://www.npmjs.com/package/jsonwebtoken
npm i jsonwebtoken
npm i magic-globals
npm i lodash
// JWTService.js
const jwt = require('jsonwebtoken');
const SECRET='secretkey';
module.exports = {
  issuer(payload, expiresIn){
    try{
      return jwt.sign(payload, SECRET, {
        expiresIn
      });
    }catch(TokenExpiredError){
      throw {
        code: 'E_TOKEN',
        name: TokenExpiredError.name||null,
        message: TokenExpiredError.message||null,
        expiredAt: TokenExpiredError.expiredAt||null
      }
    }
  },
  verify(token){
    try{
      return jwt.verify(token, SECRET);
    }catch(TokenExpiredError){
      throw {
        code: 'E_TOKEN',
        name: TokenExpiredError.name||null,
        message: TokenExpiredError.message||null,
        expiredAt: TokenExpiredError.expiredAt||null
      }
    }
  }
}
# isLoggedIn.js
module.exports = async function(req, res, next) {
  try {
    // header Authorization value check
    if (!req.headers || !req.headers.authorization) {
      throw { message: "autorization header is missing" };
    }

    const access_token = req.headers.authorization||null;
    const access_verify = JWTService.verify(access_token);

    const user = await User.findOne({ where: { id: access_verify.id } }); // find user
    if (!user) throw { message: "invalid credentionals provided" };

    req.user = user;
  } catch (err) {
    console.error({file: __file+':'+__line, headers: req.headers, params: req.allParams()});
    return res.json(_.extend({ code: "E_TOKEN" }, err));
  }
  next();
};
# AuthController.js
module.exports = {
  async login(req, res) {
    try {
      const params = req.allParams();
      const user = await User.findOne({ where: { email: params.email } }); // get email user
      if (_.isUndefined(user) || CryptService.hashSHA1(params.pwd||'') != user.passwd) {
        console.error(__filename, { params: params, user: user });
        throw { code: "E_AUTH", msg: "Invalid Email and password" };
      }

      const access_token = JWTService.issuer(
        {
          id: user.id,
          ...
        },
        '1 Day'
      );
      return res.json({ ok: true, access_token: access_token });
    } catch (err) {
      return res.json(err);
    }
  }
};
반응형