-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
88 lines (78 loc) · 2.16 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"use strict";
const fs = require("fs");
const path = require("path");
const uuid = require("uuid/v4");
const jwt = require("jsonwebtoken");
var PrettyError = require("pretty-error");
var pe = new PrettyError();
/** Suppress tracing for things like unit testing */
const DEBUG = process.env.DEBUG === true;
/** Private certificate used for signing JSON WebTokens */
const privateKey = fs.readFileSync(
path.join(__dirname, "certs/privatekey.pem")
);
/** Public certificate used for verification. Note: you could also use the private key */
const publicKey = fs.readFileSync(
path.join(__dirname, "certs/certificate.pem")
);
/**
* Creates a signed JSON WebToken and returns it. Utilizes the private certificate to create
* the signed JWT. For more options and other things you can change this to, please see:
* https://github.com/auth0/node-jsonwebtoken
*
* @param {Number} exp - The number of seconds for this token to expire. By default it will be 60
* minutes (3600 seconds) if nothing is passed in.
* @param {String} sub - The subject or identity of the token.
* @return {String} The JWT Token
*/
const createToken = ({
exp = 3600,
sub = "",
aud = "",
scope = "read",
role = "",
targetLanguages = ""
} = {}) => {
const token = jwt.sign(
{
jti: uuid(),
iss: "auth.arasaac.org",
sub,
aud,
role,
exp: Math.floor(Date.now() / 1000) + exp,
scope,
targetLanguages
},
privateKey,
{
algorithm: "RS256"
}
);
console.log(token)
return token;
};
/**
* Verifies the token through the jwt library using the public certificate.
* @param {String} token - The token to verify
* @throws {Error} Error if the token could not be verified
* @returns {Object} The token decoded and verified
*/
const verifyToken = token => jwt.verify(token, publicKey);
const logAndThrow = msg => {
// if (DEBUG) console.trace(msg)
throw new Error(msg);
};
class CustomError extends Error {
constructor(message, code) {
super(message);
this.httpCode = code;
this.name = "Custom error";
}
}
module.exports = {
createToken,
verifyToken,
logAndThrow,
CustomError
};