front/stubs/api/auth/index.js
Nikolai Petukhov a9b683797b auth with api
2024-10-03 21:15:48 +03:00

88 lines
2.0 KiB
JavaScript

const authRouter = require('express').Router();
// For cryptography
// const bcrypt = require('bcrypt');
// For creating tokens
const jwt = require('jsonwebtoken');
const TOKEN_KEY = "5frv12e4few3r"
module.exports = authRouter;
// Read already defined users (pseudo-DB)
const users = require('./users.json');
const getUserFromDB = (userID) => {
if (!userID) {return false;}
// Accessing 'DB'
const user = users.find((user) => user.id === userID);
if (user) {
return user;
} else {
return false;
}
}
// 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)'});
}
// Invalid authentication
if (!password || password !== user.password) {
res.status(401).send({message: 'Invalid credentials (password)'});
}
// 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'});
}
if (!name || !password || !nickname) {
res.status(401).send({message: 'Empty or invalid fields'});
}
// Add to 'DB'
const newUser = {id: name, password: password, nickname: nickname};
users.push(newUser);
res.status(200).send({user: newUser});
})