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

65 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-10-16 11:06:23 +03:00
const changeRouter = require('express').Router()
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
module.exports = changeRouter
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
const { getUserFromDB, deleteUserFromDB, addUserToDB } = require('../db')
2024-10-10 12:02:52 +03:00
changeRouter.post('/nickname', (req, res) => {
2024-10-16 11:06:23 +03:00
const { id, newNickname } = req.body
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
const user = getUserFromDB(id)
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
}
const updatedUser = {
"nickname": newNickname,
"password": user.password,
"id": user.id
2024-10-16 11:06:23 +03:00
}
2024-10-10 12:02:52 +03:00
// Delete the old one
deleteUserFromDB(id)
// Insert updated
2024-10-16 11:06:23 +03:00
addUserToDB(updatedUser)
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
res.status(200).send({})
})
2024-10-10 12:02:52 +03:00
changeRouter.post('/password', (req, res) => {
2024-10-16 11:06:23 +03:00
const { id, newPassword } = req.body
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
const user = getUserFromDB(id)
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
}
// Delete the old one
deleteUserFromDB(id)
// Insert updated
const updatedUser = {
"nickname": user.nickname,
"password": newPassword,
"id": user.id
2024-10-16 11:06:23 +03:00
}
addUserToDB(updatedUser)
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
res.status(200).send({})
})
2024-10-10 12:02:52 +03:00
changeRouter.delete('/:id', (req, res) => {
2024-10-16 11:06:23 +03:00
const { id } = req.params
2024-10-10 12:02:52 +03:00
2024-10-16 11:06:23 +03:00
deleteUserFromDB(id)
})
2024-10-10 12:02:52 +03:00