1/**
2@description for module commonjs
3*/
4
5// JWT MIDDLEWARE
6const jwt = require('jsonwebtoken')
7const { message } = require('../utils/util.message')
8
9module.exports = (req, res, next) => {
10 try {
11 const tokenHeader = req.headers.authorization.split('Bearer ')[1]
12 const decoded = jwt.verify(tokenHeader, process.env.ACCESS_TOKEN_SECRET)
13 req.user = decoded
14 next()
15 } catch (err) {
16 next(httpError(401))
17 }
18}
19
20// ROUTE LOGIN
21app.get('/protect', authJwt, (req, res) => {
22 console.log(req.user)
23 res.send('aim in proteced route')
24})
25
26app.post('/login', (req, res) => {
27 const bodyPayload = {
28 id: Date.now(),
29 username: req.body.username
30 }
31 const token = signAccessToken(res, bodyPayload)
32 return res.status(200).json(token)
33})
34
35app.post('/refresh-token', (req, res) => {
36 const refreshToken = signRefreshToken(req)
37 return res.status(200).json(refreshToken)
38})
39
40// JWT HELPER
41const jwt = require('jsonwebtoken')
42const { message } = require('../utils/util.message')
43
44exports.signAccessToken = (res, payload) => {
45 try {
46 if (payload) {
47 const accessToken = jwt.sign({ ...payload }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
48 const refreshToken = jwt.sign({ ...payload }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
49 res.cookie('refreshToken', `${refreshToken}`, { maxAge: 86400 * 90, httpOnly: true })
50 return { accessToken, refreshToken }
51 }
52 } catch (err) {
53 message({
54 response: res,
55 statusCode: 401,
56 method: req.method,
57 message: 'Unautorization'
58 })
59 }
60}
61
62exports.signRefreshToken = (req) => {
63 try {
64 const getToken = req.cookies.refreshToken
65 if (getToken) {
66 const { id, username } = jwt.verify(getToken, process.env.REFRESH_TOKEN_SECRET)
67 const accesssToken = jwt.sign({ id, username }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '90d' })
68 return { accesssToken }
69 }
70 } catch (err) {
71 message({
72 response: res,
73 statusCode: 401,
74 method: req.method,
75 message: 'Unautorization'
76 })
77 }
78}
79
1/**
2@description for module esm, change userDTO with your DTO
3*/
4
5import { Request, Response } from 'express'
6import jwt, { Secret } from 'jsonwebtoken'
7import { Base64 } from 'js-base64'
8import { UsersDTO } from './../dto/users'
9import { message } from '../utils/util.message'
10
11const ACCESS_TOKEN_SECRET: Secret = process.env.ACCESS_TOKEN_SECRET
12const REFRESH_TOKEN_SECRET: Secret = process.env.REFRESH_TOKEN_SECRET
13
14export const signAccessToken = (res: Response, payload: UsersDTO): string | any => {
15 try {
16 if (payload) {
17 const accessToken: string = jwt.sign({ ...payload }, ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
18 const refreshToken: string = jwt.sign({ ...payload }, REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
19
20 const encodedAccessToken: string = Base64.encode(accessToken)
21 const encodedRefreshToken: string = Base64.encode(refreshToken)
22
23 res.cookie('refreshToken', `${encodedRefreshToken}`, { maxAge: 86400 * 90, httpOnly: true })
24
25 return { accessToken: encodedAccessToken, refreshToken: encodedRefreshToken }
26 }
27 } catch (err) {
28 return message({
29 response: res,
30 statusCode: 401,
31 method: req.method,
32 message: 'Unautorization'
33 })
34 }
35}
36
37export const signRefreshToken = () => (req: Request): string | any => {
38 try {
39 const getToken: string = req.cookies['refreshToken']
40
41 if (Base64.isValid(getToken) && getToken) {
42 const decodedToken: string = Base64.decode(getToken)
43
44 const { user_id, email }: string | any = jwt.verify(decodedToken, REFRESH_TOKEN_SECRET)
45 const accessToken: string = jwt.sign({ user_id: user_id, email: email }, ACCESS_TOKEN_SECRET, {
46 expiresIn: '90d'
47 })
48
49 const encodedAccessToken: string = Base64.encode(accessToken)
50 return encodedAccessToken
51 }
52 } catch (err) {
53 message({
54 response: res,
55 statusCode: 401,
56 method: req.method,
57 message: 'Unautorization'
58 })
59 }
60}
61
1import { Request, Response } from 'express'
2import jwt, { Secret, SignOptions } from 'jsonwebtoken'
3import { Base64 } from 'js-base64'
4import { UsersDTO } from '../dto/dto.users'
5
6const ACCESS_TOKEN_SECRET: Secret = process.env.ACCESS_TOKEN_SECRET
7const REFRESH_TOKEN_SECRET: Secret = process.env.REFRESH_TOKEN_SECRET
8
9export const signAccessToken = () => (res: Response, payload: UsersDTO, options: SignOptions): string | any => {
10 if (!payload) {
11 return null
12 } else {
13 const accessToken: string = jwt.sign({ ...payload }, ACCESS_TOKEN_SECRET, { ...options })
14 const refreshToken: string = jwt.sign({ ...payload }, REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
15
16 const encodedAccessToken: string = Base64.encode(accessToken)
17 const encodedRefreshToken: string = Base64.encode(refreshToken)
18
19 res.cookie('refreshToken', `${encodedRefreshToken}`, { maxAge: 86400 * 90, httpOnly: true })
20
21 return { accessToken: encodedAccessToken, refreshToken: encodedRefreshToken }
22 }
23}
24
25export const verifySignAccessToken = () => (token: string): string | any => {
26 if (!Base64.isValid(token)) {
27 return null
28 } else {
29 const decodedToken: string = Base64.decode(token)
30 const decoded: string | any = jwt.verify(decodedToken, ACCESS_TOKEN_SECRET)
31 return decoded
32 }
33}
34
35export const signRefreshToken = () => (req: Request): string | any => {
36 const getToken: string = req.cookies.refreshToken
37
38 if (!Base64.isValid(getToken) && !getToken) {
39 return null
40 } else {
41 const decodedToken: string = Base64.decode(getToken)
42
43 const { user_id, email }: string | any = jwt.verify(decodedToken, REFRESH_TOKEN_SECRET)
44 const accessToken: string = jwt.sign({ user_id: user_id, email: email }, ACCESS_TOKEN_SECRET, {
45 expiresIn: '90d'
46 })
47
48 const encodedAccessToken: string = Base64.encode(accessToken)
49 return encodedAccessToken
50 }
51}