|
| 1 | +import superagent from "superagent"; |
| 2 | +import HTTPError from "./http-error"; |
| 3 | +import jwt from 'jsonwebtoken'; |
| 4 | +import crypto from 'crypto'; |
| 5 | + |
| 6 | +async function defaultRefreshRoles({name,roles,token}, {baseUrl}) { |
| 7 | + try { |
| 8 | + let {body} = await superagent.get(`${baseUrl}/_users/org.couchdb.user:${name}`) |
| 9 | + .set("Authorization", "Bearer " + token) |
| 10 | + .accept("application/json"); |
| 11 | + |
| 12 | + return body.roles; |
| 13 | + } catch(e) { |
| 14 | + return roles; |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +export default function(couchOpts={}, opts={}) { |
| 19 | + const api = {}; |
| 20 | + const {baseUrl} = couchOpts; |
| 21 | + const { |
| 22 | + algorithms, expiresIn, secret, |
| 23 | + refreshRoles=defaultRefreshRoles |
| 24 | + } = opts; |
| 25 | + const algorithm = Array.isArray(algorithms) ? algorithms[0] : "HS256"; |
| 26 | + |
| 27 | + api.authenticate = async function authenticate(username, password) { |
| 28 | + try { |
| 29 | + let {body} = await superagent.get(`${baseUrl}/_session`) |
| 30 | + .accept("application/json") |
| 31 | + .auth(username, password); |
| 32 | + |
| 33 | + return body; |
| 34 | + } catch(e) { |
| 35 | + let resp = e.response; |
| 36 | + if (!resp) throw e; |
| 37 | + |
| 38 | + if (resp.statusCode === 401) { |
| 39 | + throw new HTTPError(401, resp.body.reason, "EBADAUTH"); |
| 40 | + } else { |
| 41 | + throw new HTTPError(resp.statusCode, resp.body.reason, "ECOUCH"); |
| 42 | + } |
| 43 | + } |
| 44 | + }; |
| 45 | + |
| 46 | + api.generateToken = function generateToken({name, roles}, session) { |
| 47 | + const token = jwt.sign({name, roles, session}, secret, {algorithm, expiresIn}); |
| 48 | + const data = jwt.decode(token); |
| 49 | + data.token = token; |
| 50 | + return data; |
| 51 | + }; |
| 52 | + |
| 53 | + api.generateSession = async function generateSession() { |
| 54 | + const sid = crypto.randomBytes(16).toString('hex'); |
| 55 | + await this.sessionStore.add(sid); |
| 56 | + return sid; |
| 57 | + }; |
| 58 | + |
| 59 | + api.validateToken = async function validateToken(token, ignoreExpiration=false) { |
| 60 | + // decode data without verifying to check the session first |
| 61 | + const data = jwt.decode(token); |
| 62 | + if (!data) { |
| 63 | + throw new HTTPError(401, "Missing or invalid token.", "EBADTOKEN"); |
| 64 | + } |
| 65 | + |
| 66 | + // ensure session id exists |
| 67 | + const exists = await this.sessionStore.exists(data.session); |
| 68 | + if (!exists) { |
| 69 | + throw new HTTPError(401, "Invalid session.", "EBADSESSION"); |
| 70 | + } |
| 71 | + |
| 72 | + // verify the token |
| 73 | + try { |
| 74 | + jwt.verify(token, secret, {algorithms, ignoreExpiration}); |
| 75 | + } catch(e) { |
| 76 | + if (e.name === "TokenExpiredError") { |
| 77 | + throw new HTTPError(401, "Expired token.", "EEXPTOKEN"); |
| 78 | + } else if (e.name === "JsonWebTokenError") { |
| 79 | + throw new HTTPError(401, "Missing or invalid token.", "EBADTOKEN"); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + // return the payload |
| 84 | + data.token = token; |
| 85 | + return data; |
| 86 | + }; |
| 87 | + |
| 88 | + api.refreshRoles = async function(data) { |
| 89 | + if (typeof refreshRoles === "function") { |
| 90 | + return await refreshRoles.call(this, data, couchOpts); |
| 91 | + } |
| 92 | + |
| 93 | + return data.roles; |
| 94 | + }; |
| 95 | + |
| 96 | + api.login = async function login(username, password) { |
| 97 | + const response = await this.authenticate(username, password); |
| 98 | + const session = await this.generateSession(); |
| 99 | + return this.generateToken(response.userCtx, session); |
| 100 | + }; |
| 101 | + |
| 102 | + api.logout = async function logout(token) { |
| 103 | + const data = await this.validateToken(token, true); |
| 104 | + await this.sessionStore.remove(data.session); |
| 105 | + return data; |
| 106 | + }; |
| 107 | + |
| 108 | + api.renew = async function renew(token) { |
| 109 | + const data = await this.validateToken(token, true); |
| 110 | + data.roles = await this.refreshRoles(data); |
| 111 | + return this.generateToken(data, data.session); |
| 112 | + }; |
| 113 | + |
| 114 | + return api; |
| 115 | +} |
0 commit comments