github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-supply-chain-master/server/api/auth.js (about) 1 /** 2 * Copyright 2017 Intel Corporation 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * ---------------------------------------------------------------------------- 16 */ 17 'use strict' 18 19 const bcrypt = require('bcrypt') 20 const jwt = require('jsonwebtoken') 21 22 const users = require('../db/users') 23 const { BadRequest, Unauthorized } = require('./errors') 24 const config = require('../system/config') 25 26 const SALT_ROUNDS = 10 27 const SECRET = config.JWT_SECRET 28 29 // Hashes a password as promised 30 const hashPassword = pass => bcrypt.hash(pass, SALT_ROUNDS) 31 32 // Creates a new JWT token as promised 33 const createToken = payload => { 34 return new Promise((resolve, reject) => { 35 jwt.sign(payload, SECRET, (err, token) => { 36 if (err) reject(err) 37 else resolve(token) 38 }) 39 }) 40 } 41 42 // Verifies a token is valid as promised. 43 // Sends back the decoded payload, or throws an error if invalid. 44 const verifyToken = token => { 45 return new Promise((resolve, reject) => { 46 jwt.verify(token, SECRET, (err, payload) => { 47 if (err) reject(err) 48 else resolve(payload) 49 }) 50 }) 51 } 52 53 // Checks an object with username and password keys. 54 // Returns an auth token and the user's private key if it passes. 55 const authorize = ({ username, password }) => { 56 if (!username || !password) { 57 const message = 'Authorization requires username and password' 58 return Promise.reject(new BadRequest(message)) 59 } 60 61 return users.query(users => users.filter({ username })) 62 .then(matches => { 63 if (matches.length === 0) throw new Error() 64 const user = matches[0] 65 66 return bcrypt.compare(password, user.password) 67 .then(passValid => { 68 if (!passValid) throw new Error() 69 return createToken(user.publicKey) 70 }) 71 .then(token => ({ 72 authorization: token, 73 encryptedKey: user.encryptedKey 74 })) 75 }) 76 .catch(() => { throw new Unauthorized('Authorization Failed') }) 77 } 78 79 module.exports = { 80 hashPassword, 81 createToken, 82 verifyToken, 83 authorize 84 }