I'm new at Node.js and I need some help with my code. I'm developing an API-REST for diet control. My code is returning the JWT successfully when the person logs in, but now I don't know how to verify the JWT for when the user tries to access the registered meals.

Here's my sing-in route:

    app.post('/sign-in', async (request, reply) => {
    const getUserParamsSchema = z.object({
      email: z.string(),
      password: z.string(),
    })

    const { email, password } = getUserParamsSchema.parse(request.body)

    const user = await knex('users').where('email', email).first()

    if (!user) return new Error('Email ou senha incorretos')

    const passwordMatch = await PasswordCrypto.verifyPassword(
      password,
      user.password,
    )

    if (!passwordMatch) {
      return new Error('Email ou senha incorretos')
    } else {
      const accessToken = JWTService.sign({ uid: user.id })

      if (accessToken === 'JWT_SECRET_NOT_FOUND') {
        return reply.status(500).send('Erro interno do servidor')
      }
      return reply
        .status(200)
        .send({ message: 'Login efetuado com sucesso!', accessToken })
    }

My meals routes:

import { FastifyInstance } from 'fastify'
import { z } from 'zod'
import { knex } from '../database'
import { randomUUID } from 'crypto'

export async function mealsRoutes(app: FastifyInstance) {
  app.get('/', async () => {
    const meals = await knex('meals').select()

    return { meals }
  })

  app.get('/:id', async (request) => {
    const getMealParamsSchema = z.object({
      id: z.string().uuid(),
    })

    const { id } = getMealParamsSchema.parse(request.params)

    const meal = await knex('meals').where('id', id).first()

    return { meal }
  })

  app.post('/', async (request, reply) => {
    const createMealBodySchema = z.object({
      title: z.string(),
      description: z.string(),
      onDiet: z.enum(['Sim', 'Não']),
    })

    const { title, description, onDiet } = createMealBodySchema.parse(
      request.body,
    )

    await knex('meals').insert({
      id: randomUUID(),
      title,
      description,
      onDiet,
    })

    return reply.status(201).send()
  })
}

JWT:

import * as jwt from 'jsonwebtoken'

interface JwtData {
  uid: string
}

const sign = (data: JwtData) => {
  if (!process.env.JWT_SECRET) return 'JWT_SECRET_NOT_FOUND'

  return jwt.sign(data, process.env.JWT_SECRET, { expiresIn: '24h' })
}

const verify = (
  token: string,
): JwtData | 'JWT_SECRET_NOT_FOUND' | 'INVALID_TOKEN' => {
  if (!process.env.JWT_SECRET) return 'JWT_SECRET_NOT_FOUND'

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET)

    if (typeof decoded === 'string') {
      return 'INVALID_TOKEN'
    }

    return decoded as JwtData
  } catch (error) {
    return 'INVALID_TOKEN'
  }
}

export const JWTService = {
  sign,
  verify,
}
0

There are 0 best solutions below