|
| 1 | +import { Request, Response } from 'express'; |
| 2 | +import { LoginCredentials } from './types/auth-types'; |
| 3 | +import { db, users } from '../../lib/db'; |
| 4 | +import { eq } from 'drizzle-orm'; |
| 5 | +import bcrypt from 'bcrypt'; |
| 6 | +import jwt from 'jsonwebtoken'; |
| 7 | + |
| 8 | +export async function login(req: Request, res: Response) { |
| 9 | + const { username, password }: LoginCredentials = req.body; |
| 10 | + const userArray = await db.select().from(users).where(eq(users.username, username)); |
| 11 | + if (userArray.length === 0) { |
| 12 | + return res.status(404).json('Account does not exist'); |
| 13 | + } |
| 14 | + |
| 15 | + const user = userArray[0]; |
| 16 | + const checkPassword = bcrypt.compareSync(password, user.password); |
| 17 | + if (!checkPassword) { |
| 18 | + return res.status(401).json('Incorrect Password'); |
| 19 | + } |
| 20 | + |
| 21 | + const { password: _userPassword, ...userDetails } = user; |
| 22 | + const jwtToken = jwt.sign({ id: user.id }, 'key'); |
| 23 | + return res.cookie('jwtToken', jwtToken, { httpOnly: true }).status(200).json(userDetails); |
| 24 | +} |
| 25 | + |
| 26 | +export async function logout(_req: Request, res: Response) { |
| 27 | + return res |
| 28 | + .clearCookie('jwtToken', { |
| 29 | + secure: true, |
| 30 | + sameSite: 'none', |
| 31 | + }) |
| 32 | + .status(200) |
| 33 | + .json('User has been logged out.'); |
| 34 | +} |
0 commit comments