Advertisement
Guest User

Untitled

a guest
Dec 6th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. const jwt = require("jsonwebtoken");
  2. const express = require("express");
  3. const crypto = require("crypto");
  4. const Router = express.Router();
  5. const config = require("../../config");
  6. const UserException = require("../../exceptions").UserException;
  7. const User = require("../middleware/sequelize").user;
  8.  
  9. Router.get("/", (req,res,next) => {
  10. if(!req.body.login)
  11. return next(new UserException("Login nie może być pusty!"));
  12. else if(!req.body.password)
  13. return next(new UserException("Hasło nie może być puste!"));
  14. User.findOne({
  15. where: { login: req.body.login }
  16. }).then(function(user) {
  17. if(user) {
  18. if(user.password == crypto.createHash("sha256").update(req.body.password).digest("hex")) {
  19. userId = user.id
  20. jwt.sign({userId}, config.jwtsign, (err, token) => {
  21. res.json(token).status(200);
  22. });
  23. } else
  24. return next(new UserException("Podano zły login lub hasło"));
  25. } else
  26. return next(new UserException("Podano zły login lub hasło"));
  27. });
  28. });
  29.  
  30. Router.get("/check", (req,res,next) => {
  31. const bearerHeader = req.headers['authorization'];
  32. if(typeof bearerHeader !== 'undefined') {
  33. const bearer = bearerHeader.split(' ');
  34. const bearerToken = bearer[1];
  35. jwt.verify(bearerToken, config.jwtsign, (err, authData) => {
  36. if(err) {
  37. res.sendStatus(401);
  38. } else {
  39. User.findOne({
  40. attributes: [ `id`, `login`, `email` ],
  41. where: { id: authData.userId }
  42. }).then(user => {
  43. res.json({
  44. id: user.id,
  45. login: user.login,
  46. email: user.email,
  47. });
  48. });
  49. }
  50. });
  51. } else {
  52. res.sendStatus(401);
  53. }
  54. });
  55.  
  56. module.exports = Router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement