-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
74 lines (69 loc) · 2.11 KB
/
index.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
const jwt = require('jsonwebtoken');
const jwtPassword = 'secret';
const zod = require('zod');
/**
* Generates a JWT for a given username and password.
*
* @param {string} username - The username to be included in the JWT payload.
* Must be a valid email address.
* @param {string} password - The password to be included in the JWT payload.
* Should meet the defined length requirement (e.g., 6 characters).
* @returns {string|null} A JWT string if the username and password are valid.
* Returns null if the username is not a valid email or
* the password does not meet the length requirement.
*/
const userSchema = zod.object({
username: zod.string().email(),
password: zod.string().min(6),
});
function signJwt(username, password) {
// Your code here
try {
const validationResponse = userSchema.safeParse({ username, password });
if (!validationResponse.success) {
return null;
}
const token = jwt.sign({ username, password }, jwtPassword);
return token;
} catch (error) {
return error;
}
}
/**
* Verifies a JWT using a secret key.
*
* @param {string} token - The JWT string to verify.
* @returns {boolean} Returns true if the token is valid and verified using the secret key.
* Returns false if the token is invalid, expired, or not verified
* using the secret key.
*/
function verifyJwt(token) {
// Your code here
try {
jwt.verify(token, jwtPassword);
return true;
} catch (error) {
return false;
}
}
/**
* Decodes a JWT to reveal its payload without verifying its authenticity.
*
* @param {string} token - The JWT string to decode.
* @returns {object|false} The decoded payload of the JWT if the token is a valid JWT format.
* Returns false if the token is not a valid JWT format.
*/
function decodeJwt(token) {
// Your code here
const payload = jwt.decode(token);
if (!payload) {
return false;
}
return true;
}
module.exports = {
signJwt,
verifyJwt,
decodeJwt,
jwtPassword,
};