BETTERZON-79: Adding API endpoint for logging in (#36)

This commit is contained in:
Patrick
2021-05-03 15:14:22 +02:00
committed by GitHub
parent e9d03b9cbb
commit a42c7da9a5
2 changed files with 100 additions and 4 deletions
+30 -1
View File
@@ -26,7 +26,7 @@ usersRouter.post('/register', async (req: Request, res: Response) => {
const username: string = req.body.username;
const password: string = req.body.password;
const email: string = req.body.email;
const ip: string = req.connection.remoteAddress?? '';
const ip: string = req.connection.remoteAddress ?? '';
if (!username || !password || !email) {
// Missing
@@ -52,3 +52,32 @@ usersRouter.post('/register', async (req: Request, res: Response) => {
res.status(404).send(e.message);
}
});
// POST users/login
usersRouter.post('/login', async (req: Request, res: Response) => {
try {
const username: string = req.body.username;
const password: string = req.body.password;
const ip: string = req.connection.remoteAddress ?? '';
if (!username || !password) {
// Missing
res.status(400).send(JSON.stringify({message: 'Missing parameters'}));
return;
}
// Update the user entry and create a session
const session: Session = await UserService.login(username, password, ip);
if(!session.session_id) {
// Error logging in, probably wrong username / password
res.status(401).send(JSON.stringify({messages: ["Wrong username and / or password"], codes: [1, 4]}));
return;
}
// Send the session details back to the user
res.status(201).send(session);
} catch (e) {
res.status(404).send(e.message);
}
});