red-coder-bh/dist/routes/auth.js

69 lines
2.9 KiB
JavaScript

"use strict";
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.authRouter = void 0;
const express_1 = require("express");
const pbkdf2_password_1 = __importDefault(require("pbkdf2-password"));
const uuid_1 = require("uuid");
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const express_jwt_1 = __importDefault(require("express-jwt"));
const makeHash = (0, pbkdf2_password_1.default)();
exports.authRouter = (0, express_1.Router)();
const requiredFields = (fields) => (req, res, next) => {
for (const fieldName of fields) {
if (!req.body[fieldName]) {
throw new Error(`Field ${fieldName} does\'t set`);
}
}
next();
};
const users = [];
exports.authRouter.get('/users', (0, express_jwt_1.default)({ secret: process.env.JWT_SECRET_STRING, algorithms: ['HS256'] }), (req, res) => {
res.send(users);
});
exports.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 } = user, cleanUser = __rest(user, ["hash", "salt"]);
req.session.user = cleanUser;
const token = jsonwebtoken_1.default.sign(cleanUser, process.env.JWT_SECRET_STRING, {});
return res.send({ token, user: cleanUser });
}
res.status(400).send({ error: 'Login or password does\'t match' });
});
});
exports.authRouter.post('/sign-up', requiredFields(['password', 'login', 'email']), (req, res, next) => {
const _a = req.body, { password, login } = _a, rest = __rest(_a, ["password", "login"]);
makeHash({ password }, function (err, pass, salt, hash) {
if (err)
throw err;
const newUser = Object.assign(Object.assign({ id: (0, uuid_1.v4)() }, rest), { login,
salt,
hash });
users.push(newUser);
const { hash: _hash, salt: _salt } = newUser, cleanUser = __rest(newUser, ["hash", "salt"]);
res.send(cleanUser);
});
});