«   2019/08   »
        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
Archives
Today
11
Total
1,222,663
안정적인 DNS서비스 DNSEver
관리 메뉴

Blue Breeze

jwtwebtoken 본문

Language/Node.js

jwtwebtoken

푸른바람 C/H 2019.04.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);
    }
  }
};

'Language > Node.js' 카테고리의 다른 글

jwtwebtoken  (0) 2019.04.12
Origin Policy Error on Sailsjs  (0) 2019.03.20
not support route and folder fot sails.js  (0) 2019.03.04
Sails Restful-api Tutorials  (0) 2019.02.22
Full Stack Framework Sails.js For Node.js  (0) 2019.02.14
node.js json-server  (0) 2018.06.13
0 Comments
댓글쓰기 폼