-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
27 lines (25 loc) · 943 Bytes
/
auth.js
File metadata and controls
27 lines (25 loc) · 943 Bytes
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
// making a function to enable the app to protect
// a particular endpoint from unauthenticated users.
const jwt = require("jsonwebtoken");
module.exports = async (request, response, next) => {
try {
// get the token from the authorization header
const token = await request.headers.authorization.split(" ")[1];
// Check if the token that was generated matches the token
// string (RANDOM-TOKEN) matches the suppossed origin
const decodedToken = await jwt.verify(
token,
"RANDOM_TOKEN"
)
// retrieve the user details of the logged in users
const user = await decodedToken;
// pass the user down to the endpoints here
request.user = user;
// pass down functionality to the endpoint
next();
} catch (error) {
response.status(401).json({
error: new Error("Invalid request!"),
});
}
}