From 9a37ebf284d3d2e20fe990084750b222100ae1c9 Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Fri, 9 Aug 2024 08:22:14 +0700 Subject: [PATCH] Create auth.ts --- projects/pi-nexus-iam/routes/auth.ts | 67 ++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 projects/pi-nexus-iam/routes/auth.ts diff --git a/projects/pi-nexus-iam/routes/auth.ts b/projects/pi-nexus-iam/routes/auth.ts new file mode 100644 index 000000000..4d0fb86bd --- /dev/null +++ b/projects/pi-nexus-iam/routes/auth.ts @@ -0,0 +1,67 @@ +import express, { Request, Response, NextFunction } from 'express'; +import bcrypt from 'bcrypt'; +import jwt from 'jsonwebtoken'; +import { User } from '../models/user'; +import { Role } from '../enums/role.enum'; + +const router = express.Router(); + +router.post('/register', async (req: Request, res: Response, next: NextFunction) => { + try { + const { username, email, password } = req.body; + const user = new User({ username, email, password, roles: [Role.USER] }); + await user.save(); + res.json({ message: 'User created successfully' }); + } catch (error) { + next(error); + } +}); + +router.post('/login', async (req: Request, res: Response, next: NextFunction) => { + try { + const { email, password } = req.body; + const user = await User.findOne({ email }); + if (!user) { + return res.status(401).json({ error: 'Invalid email or password' }); + } + const isValid = await user.comparePassword(password); + if (!isValid) { + return res.status(401).json({ error: 'Invalid email or password' }); + } + const token = user.generateToken(); + res.json({ token }); + } catch (error) { + next(error); + } +}); + +router.post('/forgot-password', async (req: Request, res: Response, next: NextFunction) => { + try { + const { email } = req.body; + const user = await User.findOne({ email }); + if (!user) { + return res.status(404).json({ error: 'User not found' }); + } + const token = await user.generatePasswordResetToken(); + res.json({ token }); + } catch (error) { + next(error); + } +}); + +router.post('/reset-password', async (req: Request, res: Response, next: NextFunction) => { + try { + const { token, password } = req.body; + const user = await User.findOne({ passwordResetToken: token }); + if (!user) { + return res.status(404).json({ error: 'Invalid token' }); + } + user.password = password; + await user.save(); + res.json({ message: 'Password reset successfully' }); + } catch (error) { + next(error); + } +}); + +export default router;