multy-stub/server/routers/epja-2024-1/enterfront/auth/index.js

74 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-10-16 11:06:23 +03:00
const authRouter = require('express').Router()
2024-10-10 12:02:52 +03:00
// For creating tokens
2024-10-16 11:06:23 +03:00
const jwt = require('jsonwebtoken')
2024-10-10 12:02:52 +03:00
2024-10-12 11:17:21 +03:00
const { TOKEN_KEY } = require('../key')
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
module.exports = authRouter
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
const { addUserToDB, getUserFromDB } = require('../db')
2024-10-10 12:02:52 +03:00
// Get a user by its id
authRouter.get('/:id', (req, res) => {
2024-10-16 11:06:23 +03:00
const user = getUserFromDB(req.params.id)
2024-10-10 12:02:52 +03:00
if (user) {
2024-10-16 11:06:23 +03:00
res.status(200).send({user})
2024-10-10 12:02:52 +03:00
} else {
2024-10-16 11:06:23 +03:00
res.status(404).send({message: 'User was not found'})
2024-10-10 12:02:52 +03:00
}
})
// For login (authorization)
authRouter.post('/login', (req, res) => {
2024-10-16 11:06:23 +03:00
const { name, password } = req.body
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
const user = getUserFromDB(name)
2024-10-10 12:02:52 +03:00
// Invalid identification
if (!user) {
2024-10-16 11:06:23 +03:00
res.status(401).send({message: 'Invalid credentials (id)'})
return
2024-10-10 12:02:52 +03:00
}
// Invalid authentication
if (!password || password !== user.password) {
2024-10-16 11:06:23 +03:00
res.status(401).send({message: 'Invalid credentials (password)'})
return
2024-10-10 12:02:52 +03:00
}
// Now, authorization
const token = jwt.sign({id: name}, TOKEN_KEY, {
expiresIn: '1h'
})
2024-10-16 11:06:23 +03:00
res.status(200).send({token})
2024-10-10 12:02:52 +03:00
})
authRouter.post('/reg', (req, res) => {
2024-10-16 11:06:23 +03:00
const { name, password, nickname } = req.body
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
const user = getUserFromDB(name)
2024-10-10 12:02:52 +03:00
// Invalid identification
if (user) {
2024-10-16 11:06:23 +03:00
res.status(409).send({message: 'Such id already exists'})
return
2024-10-10 12:02:52 +03:00
}
if (!name || !password || !nickname) {
2024-10-16 11:06:23 +03:00
res.status(401).send({message: 'Empty or invalid fields'})
return
2024-10-10 12:02:52 +03:00
}
// Add to 'DB'
2024-10-16 11:06:23 +03:00
const newUser = {id: name, password: password, nickname: nickname}
2024-10-10 12:02:52 +03:00
addUserToDB(newUser)
2024-10-16 11:06:23 +03:00
res.status(200).send({user: newUser})
2024-10-10 12:02:52 +03:00
})