Files
yourpart3/backend/controllers/authController.js
2024-10-27 14:15:44 +01:00

64 lines
2.0 KiB
JavaScript

import * as userService from '../services/authService.js';
class AuthController {
constructor() {
this.register = this.register.bind(this);
this.login = this.login.bind(this);
this.forgotPassword = this.forgotPassword.bind(this);
this.activateAccount = this.activateAccount.bind(this);
this.logout = this.logout.bind(this);
}
async register(req, res) {
const { email, username, password, language } = req.body;
try {
const result = await userService.registerUser({ email, username, password, language });
res.status(201).json(result);
} catch (error) {
console.log(error);
res.status(500).json({ error: error.message });
}
}
async login(req, res) {
const { username, password } = req.body;
try {
const result = await userService.loginUser({ username, password });
res.status(200).json(result);
} catch (error) {
if (error.message === 'credentialsinvalid') {
res.status(404).json({ error: error.message });
} else {
res.status(500).json({ error: error.message });
}
}
}
async logout(req, res) {
const { userid: hashedUserId } = req.headers;
await userService.logoutUser(hashedUserId);
}
async forgotPassword(req, res) {
const { email } = req.body;
try {
const result = await userService.handleForgotPassword({ email });
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
async activateAccount(req, res) {
const { token } = req.body;
try {
const result = await userService.activateUserAccount({ token });
res.status(200).json(result);
} catch (error) {
res.status(500).json({ error: error.message });
}
}
}
export default AuthController;