Advertisement
Guest User

auth.js

a guest
Nov 14th, 2019
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * module auth
  3. * register and login user
  4. */
  5. "use strict";
  6.  
  7.  
  8. //Database
  9. // const sqlite3 = require('sqlite3').verbose();
  10. // const db = new sqlite3.Database('./db/texts.sqlite');
  11. const db = require("../db/database");
  12.  
  13.  
  14. // Handle hashing password
  15. const bcrypt = require('bcryptjs');
  16. const saltRounds = 10;
  17.  
  18. //JWT
  19. const jwt = require('jsonwebtoken');
  20. require('dotenv').config();
  21.  
  22. function authError(status, message) {
  23.     const error = new Error(message);
  24.     error.status = status;
  25.  
  26.     return error;
  27. }
  28.  
  29. const auth = {
  30.     signToken(payload) {
  31.         const secret = process.env.JWT_SECRET;
  32.  
  33.         return jwt.sign(payload, secret, { expiresIn: '1h' });
  34.     },
  35.  
  36.     async register(data) {
  37.         const { name, email, birthday, password } = data;
  38.         const sql = "INSERT INTO users (name, email, birthday, password) VALUES(?, ?, ?, ?);";
  39.  
  40.         if (!name || !email || !birthday || !password) {
  41.             throw authError(401, "Value (name, email, birthday or password) missing");
  42.         }
  43.  
  44.         const hash = await bcrypt.hash(password, saltRounds);
  45.  
  46.         return db.run(sql, [name, email, birthday, hash]);
  47.     },
  48.  
  49.     async login(email, password) {
  50.         const { email, password } = data;
  51.         const sql = "SELECT * FROM 'users' WHERE email = ?;";
  52.  
  53.         if (!userEmail || !userPassword) {
  54.             throw authError(401, "Email or password missing");
  55.         }
  56.  
  57.         const user = await db.get(sql, [ email ]);
  58.  
  59.         if (!user) {
  60.             throw authError(401, "User not found");
  61.         }
  62.  
  63.         const result = await bcrypt.compare(password, user.password);
  64.  
  65.         if (!result) {
  66.             throw authError(401, "Wrong password");
  67.         }
  68.  
  69.         return auth.createToken({ email, name: user.name });
  70.     },
  71.  
  72.     async getUsers() {
  73.         return db.all("SELECT * FROM 'users'");
  74.     },
  75. }
  76.  
  77.  
  78. module.exports = auth;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement