Files
gg-backend/backend/src/controllers/auth.controller.js
T

77 lines
1.6 KiB
JavaScript
Raw Normal View History

2026-05-26 15:48:01 +05:30
import prisma from '../prisma/client.js';
import { generateToken } from '../utils/jwt.js';
import { hashPassword, comparePassword } from '../utils/password.js';
2026-03-12 14:15:44 +05:30
/**
* REGISTER
* POST /api/auth/register
*/
export async function register(req, res) {
2026-05-26 15:48:01 +05:30
const { username, password, role } = req.body;
2026-03-12 14:15:44 +05:30
if (!username || !password) {
2026-05-26 15:48:01 +05:30
return res.status(400).json({ error: 'Username and password required' });
2026-03-12 14:15:44 +05:30
}
const existingUser = await prisma.user.findUnique({
2026-05-26 15:48:01 +05:30
where: { username },
2026-03-12 14:15:44 +05:30
});
if (existingUser) {
2026-05-26 15:48:01 +05:30
return res.status(409).json({ error: 'Username already exists' });
2026-03-12 14:15:44 +05:30
}
const hashedPassword = await hashPassword(password);
const user = await prisma.user.create({
data: {
username,
password: hashedPassword,
2026-05-26 15:48:01 +05:30
role: role || 'admin',
2026-03-12 14:15:44 +05:30
},
});
res.status(201).json({
2026-05-26 15:48:01 +05:30
message: 'User registered successfully',
2026-03-12 14:15:44 +05:30
user: {
id: user.id,
username: user.username,
role: user.role,
},
});
}
/**
* LOGIN
* POST /api/auth/login
*/
export async function login(req, res) {
2026-05-26 15:48:01 +05:30
const { username, password } = req.body;
2026-03-12 14:15:44 +05:30
if (!username || !password) {
2026-05-26 15:48:01 +05:30
return res.status(400).json({ error: 'Username and password required' });
2026-03-12 14:15:44 +05:30
}
const user = await prisma.user.findUnique({
2026-05-26 15:48:01 +05:30
where: { username },
2026-03-12 14:15:44 +05:30
});
if (!user) {
2026-05-26 15:48:01 +05:30
return res.status(401).json({ error: 'Invalid credentials' });
2026-03-12 14:15:44 +05:30
}
const isValid = await comparePassword(password, user.password);
if (!isValid) {
2026-05-26 15:48:01 +05:30
return res.status(401).json({ error: 'Invalid credentials' });
2026-03-12 14:15:44 +05:30
}
const token = generateToken({
userId: user.id,
username: user.username,
role: user.role,
});
2026-05-26 15:48:01 +05:30
res.json({ token });
2026-03-12 14:15:44 +05:30
}