All files / src/routes auth.js

100% Statements 32/32
100% Branches 6/6
100% Functions 2/2
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 804x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x           4x               4x 60x     60x   57x 1x       56x     56x         56x   56x             4x 58x     58x       58x 2x       56x   56x 2x       54x   54x     4x  
const express = require("express");
const router = express.Router();
const prisma = require("../lib/prisma");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const { z } = require("zod");
const SECRET = process.env.JWT_SECRET;
const { ValidationError } = require("../lib/errors");
const { ConflictError } = require("../lib/errors");
const { UnauthorizedError } = require("../lib/errors");
 
const RegisterInput = z.object({
  email: z.string().min(1).max(255),
  password: z.string().min(1).max(72),
  name: z.string().min(1).max(100),
});
 
const LoginInput = z.object({
  email: z.string().min(1).max(255),
  password: z.string().min(1).max(72),
});
 
// Here we will add all routes related to authentication
 
// POST /api/auth/register
router.post("/register", async (req, res) => {
  const { email, password, name } = RegisterInput.parse(req.body);
 
  // Check if user already exists
  const existingUser = await prisma.user.findUnique({ where: { email },});
 
  if (existingUser) {
    throw new ConflictError("Email already registered");
  }
 
  // Hash the password
  const hashedPassword = await bcrypt.hash(password, 10);
 
  // Create the user
  const user = await prisma.user.create({
    data: { email, password: hashedPassword, name },
  });
 
  // Generate a token
  const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: "24h" });
 
  res.status(201).json({
    message: "User registered successfully",
    token,
  });
});
 
// POST /api/auth/login
router.post("/login", async (req, res) => {
  const { email, password } = LoginInput.parse(req.body);
 
  // Find the user
  const user = await prisma.user.findUnique({
    where: { email },
  });
 
  if (!user) {
    throw new UnauthorizedError("Invalid credentials");
  }
 
  // Verify the password
  const isValid = await bcrypt.compare(password, user.password);
 
  if (!isValid) {
    throw new UnauthorizedError("Invalid credentials");
  }
 
  // Generate a token
  const token = jwt.sign({ userId: user.id }, SECRET, { expiresIn: "1h" });
 
  res.json({ token });
});
 
module.exports = router; // This should be the last line