Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. const express = require("express");
  2. const bcrypt = require("bcrypt");
  3. const router = express.Router();
  4. const jwt = require("jsonwebtoken");
  5. const config = require("../config");
  6.  
  7. const User = require("../models/User");
  8.  
  9. router.get("/", (req, res) => {
  10. res.send("Auth page");
  11. });
  12.  
  13. router.post("/register", async (req, res) => {
  14. const { username, password } = req.body;
  15.  
  16. try {
  17. const existingUser = await User.findOne({ username: username });
  18.  
  19. if (existingUser) {
  20. throw new Error("User already exist!");
  21. }
  22.  
  23. const hashedPassword = await bcrypt.hash(password, 12).catch(() => {
  24. throw new Error("Something wrong");
  25. });
  26.  
  27. const user = new User({
  28. username: username,
  29. password: hashedPassword
  30. });
  31.  
  32. const result = await user.save();
  33.  
  34. if (result) {
  35. res.json({
  36. message: "User created",
  37. code: 1
  38. });
  39. }
  40. } catch (err) {
  41. res.json({
  42. message: err.message,
  43. code: 0
  44. });
  45. }
  46. });
  47.  
  48. router.post("/login", async (req, res) => {
  49. const { username, password } = req.body;
  50.  
  51. try {
  52. const user = await User.findOne({ username: username });
  53.  
  54. if (!user) {
  55. throw new Error("User does not found!");
  56. }
  57.  
  58. const isPasswordEqual = await bcrypt
  59. .compare(password, user.password)
  60. .catch(() => {
  61. throw new Error("Something wrong");
  62. });
  63.  
  64. if (!isPasswordEqual) {
  65. throw new Error("Password is incorrect!");
  66. }
  67.  
  68. const token = jwt.sign(
  69. { username: username, userId: user.id },
  70. config.SECRET_KEY
  71. );
  72.  
  73. res.json({
  74. code: 1,
  75. message: token
  76. });
  77. } catch (err) {
  78. res.json({
  79. message: err.message,
  80. code: 0
  81. });
  82. }
  83. });
  84.  
  85. module.exports = router;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement