banner-data
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { Router } from 'express';
|
||||
import pbkdf2Password from 'pbkdf2-password';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import jwtMiddleware from 'express-jwt';
|
||||
|
||||
const makeHash = pbkdf2Password();
|
||||
|
||||
export const authRouter = Router();
|
||||
|
||||
const requiredFields = (fields: string[]) => (req, res, next) => {
|
||||
for (const fieldName of fields) {
|
||||
if (!req.body[fieldName]) {
|
||||
throw new Error(`Field ${fieldName} does\'t set`)
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
const users: any[] = [];
|
||||
|
||||
|
||||
authRouter.get('/users', jwtMiddleware({ secret: process.env.JWT_SECRET_STRING, algorithms: ['HS256'] }), (req, res) => {
|
||||
res.send(users);
|
||||
});
|
||||
|
||||
authRouter.post('/sign-in', requiredFields(['password', 'login']), (req, res) => {
|
||||
const { password, login } = req.body;
|
||||
|
||||
const user = users.find(u => u.login === login);
|
||||
|
||||
if (!user) {
|
||||
res.status(400).send({ error: 'Login or password does\'t match' });
|
||||
return;
|
||||
}
|
||||
|
||||
makeHash({ password, salt: user.salt }, (err, pass, salt, hash) => {
|
||||
if (err) throw err;
|
||||
|
||||
if (user.hash === hash) {
|
||||
const { hash: _hash, salt: _salt, ...cleanUser } = user
|
||||
|
||||
req.session.user = cleanUser;
|
||||
const token = jwt.sign(cleanUser, process.env.JWT_SECRET_STRING, {
|
||||
|
||||
});
|
||||
|
||||
return res.send({ token, user: cleanUser })
|
||||
}
|
||||
|
||||
res.status(400).send({ error: 'Login or password does\'t match' });
|
||||
});
|
||||
});
|
||||
|
||||
authRouter.post('/sign-up', requiredFields(['password', 'login', 'email']), (req, res, next) => {
|
||||
const { password, login, ...rest } = req.body;
|
||||
|
||||
makeHash({ password }, function (err, pass, salt, hash) {
|
||||
if (err) throw err;
|
||||
|
||||
const newUser = {
|
||||
id: uuid(),
|
||||
...rest,
|
||||
login,
|
||||
salt,
|
||||
hash
|
||||
}
|
||||
|
||||
users.push(newUser);
|
||||
|
||||
const { hash: _hash, salt: _salt, ...cleanUser } = newUser
|
||||
|
||||
res.send(cleanUser);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user