Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const jwt = require("jsonwebtoken");
- const express = require("express");
- const crypto = require("crypto");
- const Router = express.Router();
- const config = require("../../config");
- const UserException = require("../../exceptions").UserException;
- const User = require("../middleware/sequelize").user;
- Router.get("/", (req,res,next) => {
- if(!req.body.login)
- return next(new UserException("Login nie może być pusty!"));
- else if(!req.body.password)
- return next(new UserException("Hasło nie może być puste!"));
- User.findOne({
- where: { login: req.body.login }
- }).then(function(user) {
- if(user) {
- if(user.password == crypto.createHash("sha256").update(req.body.password).digest("hex")) {
- userId = user.id
- jwt.sign({userId}, config.jwtsign, (err, token) => {
- res.json(token).status(200);
- });
- } else
- return next(new UserException("Podano zły login lub hasło"));
- } else
- return next(new UserException("Podano zły login lub hasło"));
- });
- });
- Router.get("/check", (req,res,next) => {
- const bearerHeader = req.headers['authorization'];
- if(typeof bearerHeader !== 'undefined') {
- const bearer = bearerHeader.split(' ');
- const bearerToken = bearer[1];
- jwt.verify(bearerToken, config.jwtsign, (err, authData) => {
- if(err) {
- res.sendStatus(401);
- } else {
- User.findOne({
- attributes: [ `id`, `login`, `email` ],
- where: { id: authData.userId }
- }).then(user => {
- res.json({
- id: user.id,
- login: user.login,
- email: user.email,
- });
- });
- }
- });
- } else {
- res.sendStatus(401);
- }
- });
- module.exports = Router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement