-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoken.js
More file actions
61 lines (48 loc) · 1.26 KB
/
token.js
File metadata and controls
61 lines (48 loc) · 1.26 KB
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
const jwt = require("jsonwebtoken")
const fs = require("fs")
const path = require("path")
const logger = require("./logger")
const { generateKeyPairSync } = require("crypto")
const keyPath = path.join(__dirname, "../secrets/private_key.pem")
let privateKey
function CheckForKey() {
if (fs.existsSync(keyPath)) {
privateKey = fs.readFileSync(keyPath, "utf8")
logger.log("Loaded existing RSA private key")
} else {
const { privateKey: genPrivKey, publicKey: genPubKey } =
generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
})
fs.mkdirSync(path.dirname(keyPath), { recursive: true })
fs.writeFileSync(keyPath, genPrivKey)
fs.writeFileSync(
path.join(__dirname, "../secrets/public_key.pem"),
genPubKey
)
privateKey = genPrivKey
logger.log("Generated new RSA key pair")
}
}
function SignToken(payload) {
const options = {
algorithm: "RS256",
keyid: "middleware-key-1",
}
return jwt.sign(payload, privateKey, options)
}
function DecodeToken(idToken) {
return jwt.decode(idToken)
}
CheckForKey()
exports.SignToken = SignToken
exports.DecodeToken = DecodeToken
exports.CheckForKey = CheckForKey