2024-10-03 21:15:48 +03:00
|
|
|
const authRouter = require('express').Router();
|
|
|
|
|
|
|
|
// For creating tokens
|
|
|
|
const jwt = require('jsonwebtoken');
|
|
|
|
|
2024-10-03 22:35:39 +03:00
|
|
|
require('dotenv').config();
|
|
|
|
const TOKEN_KEY = process.env.TOKEN_KEY;
|
2024-10-03 21:15:48 +03:00
|
|
|
|
|
|
|
|
2024-10-03 22:35:39 +03:00
|
|
|
module.exports = authRouter;
|
2024-10-03 21:15:48 +03:00
|
|
|
|
2024-10-04 11:21:21 +03:00
|
|
|
const { addUserToDB, getUserFromDB } = require('../db');
|
2024-10-03 21:15:48 +03:00
|
|
|
|
|
|
|
|
|
|
|
// Get a user by its id
|
|
|
|
authRouter.get('/:id', (req, res) => {
|
|
|
|
const user = getUserFromDB(req.params.id);
|
|
|
|
console.log("Request get in /auth:", req.params.id);
|
|
|
|
|
|
|
|
if (user) {
|
|
|
|
res.status(200).send({user});
|
|
|
|
} else {
|
|
|
|
res.status(404).send({message: 'User was not found'});
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
// For login (authorization)
|
|
|
|
authRouter.post('/login', (req, res) => {
|
|
|
|
const { name, password } = req.body;
|
|
|
|
console.log("Request login in /auth:", name);
|
|
|
|
|
|
|
|
const user = getUserFromDB(name);
|
|
|
|
|
|
|
|
// Invalid identification
|
|
|
|
if (!user) {
|
|
|
|
res.status(401).send({message: 'Invalid credentials (id)'});
|
2024-10-04 15:53:50 +03:00
|
|
|
return;
|
2024-10-03 21:15:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Invalid authentication
|
|
|
|
if (!password || password !== user.password) {
|
|
|
|
res.status(401).send({message: 'Invalid credentials (password)'});
|
2024-10-04 15:53:50 +03:00
|
|
|
return;
|
2024-10-03 21:15:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Now, authorization
|
|
|
|
const token = jwt.sign({id: name}, TOKEN_KEY, {
|
|
|
|
expiresIn: '1h'
|
|
|
|
})
|
|
|
|
|
|
|
|
res.status(200).send({token});
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
|
authRouter.post('/reg', (req, res) => {
|
|
|
|
const { name, password, nickname } = req.body;
|
|
|
|
console.log("Request reg in /auth:", name);
|
|
|
|
|
|
|
|
const user = getUserFromDB(name);
|
|
|
|
|
|
|
|
// Invalid identification
|
|
|
|
if (user) {
|
|
|
|
res.status(409).send({message: 'Such id already exists'});
|
2024-10-04 15:53:50 +03:00
|
|
|
return;
|
2024-10-03 21:15:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!name || !password || !nickname) {
|
|
|
|
res.status(401).send({message: 'Empty or invalid fields'});
|
2024-10-04 15:53:50 +03:00
|
|
|
return;
|
2024-10-03 21:15:48 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Add to 'DB'
|
|
|
|
const newUser = {id: name, password: password, nickname: nickname};
|
2024-10-04 11:21:21 +03:00
|
|
|
addUserToDB(newUser)
|
2024-10-03 21:15:48 +03:00
|
|
|
|
|
|
|
res.status(200).send({user: newUser});
|
|
|
|
})
|