Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Backend authenticate:
- const express = require('express');
- const router = express.Router();
- const jwt = require('jsonwebtoken');
- const moment = require('moment');
- const Users = require('../helpers/userLookup');
- const userService = new Users();
- module.exports = {
- authenticate
- };
- /**
- * decodes a basic auth string to authenticate a user
- * @param {object} req the recieved request body
- * @param {object} res response body to send back
- */
- function authenticate(req, res) {
- let creds = decode(req.headers.authorization);
- if (!creds.password) {
- res.status(401).json({
- error: 'Could not log in. One or more fields were missing.'
- });
- } else {
- validateUser(creds).then((result) => {
- let token = jwt.sign(result, 'defInItelyNotaSecReT', { expiresIn: '8h' });
- res.status(200).json({
- message: 'Login successful!',
- user: result,
- expires: moment().add(8, 'h').utc(),
- token: token
- });
- }).catch((error) => {
- if (error.serviceFailed) {
- res.status(500).json(error);
- } else {
- res.status(401).json(error);
- }
- });
- }
- }
- /**
- * validates that a user with the given information exists in the database
- * @param {object} creds user information decoded from the basic auth string
- */
- function validateUser(creds) {
- return new Promise((resolve, reject) => {
- userService.retrieveByQuery({
- email: creds.email
- }).then((users) => {
- if (!users[0]) {
- reject({
- message: 'Could not log in. The email address you entered is not a valid user account. Please try again.'
- });
- } else if (users[0].password == creds.password) {
- resolve(users[0]);
- } else {
- reject({
- message: 'Could not log in. The password you entered is incorrect.'
- });
- }
- }).catch((error) => {
- reject({
- serviceFailed: true,
- message: error
- });
- });
- });
- }
- /**
- * decodes a given basic auth string
- * @param {object} header the header field from post endpoint's request body
- */
- function decode(header) {
- let auth = header.split(' ');
- let buffer = Buffer.from(auth[1], 'base64').toString();
- let creds = buffer.split(':');
- if (!creds[1]) {
- creds[1] = false;
- }
- //The following allows passwords (but not email addresses!) to contain the ":" character.
- for (let i = 2; i < creds.length; ++i) {
- creds[1] += ':' + creds[i];
- }
- return {
- email: creds[0],
- password: creds[1]
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement