Skip to content

Instantly share code, notes, and snippets.

@BrenoOPrado
Last active November 5, 2022 19:32
Show Gist options
  • Save BrenoOPrado/a44155925983330999aba9b5b775df4c to your computer and use it in GitHub Desktop.
Save BrenoOPrado/a44155925983330999aba9b5b775df4c to your computer and use it in GitHub Desktop.
Guia de uso do JWT

CASO USE DOCKER:

  • Checar chave ‘environment’ dentro do arquivo .YAML (usado para criar o Docker) se existe o campo JWT_SECRET ou similar onde estará a chave secreta.

  • criar diretório 'Util' em 'src'
  • criar arquivo 'jwt.js' em 'Util'
conteúdo: (função de criação do token)
import dotenv from 'dotenv';
const jwt = require('jsonwebtoken');

const TOKEN_SECRET_KEY = process.env.JWT_SECRET;

const generateToken = (data) => {
 const payload = {
   ...data,
 };

 const jwtConfig = {
   expiresIn: '50m', // tempo até expirar o token (ex 15d – 15 dias)
   algorithm: 'HS256',
 };

 const token = jwt.sign(payload, TOKEN_SECRET_KEY, jwtConfig);

 return token;
};

const authenticateToken = async (token) => {
 if (!token) {
   const status = 401;
   const message = 'Token not found';
   return { status, message };
 }

 try {
   const validateToken = jwt.verify(token, TOKEN_SECRET_KEY);
   console.log(validateToken);
   return validateToken;
 } catch (error) {
   const status = 401;
   const message = 'Expired or invalid token';
   return { status, message };
 }
};

module.exports = {
 generateToken,
 authenticateToken,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment