-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi-helpers.js
84 lines (75 loc) · 2.3 KB
/
api-helpers.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
import { getServerSession } from "next-auth";
import { authOptions } from "../pages/api/auth/[...nextauth]";
/**
* helper methods for common HTTP request checks.
*
* example usage:
*
* import { withAuthCheck, withMethodCheck } from './helper';
*
* async function handle(req, res) {
* // Do something
* }
*
* export default withAuthCheck(withMethodCheck(handle));
*/
/**
* higher-order function to check if a user is authenticated before
* handling an HTTP request.
*
* @param {Function} handler - the function to handle the HTTP request
* @returns {Function} the new handler function with the added authentication check
*/
export const withAuthCheck = (handler) => {
return async (req, res) => {
const session = await getServerSession(req, res, authOptions);
if (!session) {
res.status(401).json({
message: "Unauthorized. Please sign in before accessing this resource.",
});
return;
}
// If the check passed, call the actual handler
return handler(req, res);
};
};
/**
* higher-order function to check if a user is an admin before
* handling an HTTP request.
*
* @param {Function} handler - the function to handle the HTTP request
* @returns {Function} the new handler function with the added authentication check
*/
export const withAdminCheck = (handler) => {
return async (req, res) => {
const session = await getServerSession(req, res, authOptions);
if (!session?.user.admin) {
res.status(401).json({
message:
"Unauthorized. Please contact an admin to complete this action.",
});
return;
}
// If the check passed, call the actual handler
return handler(req, res);
};
};
/**
* higher-order function to check the method of an HTTP request before
* handling it.
*
* @param {Function} handler - the function to handle the HTTP request
* @param {string} method - the HTTP method that the request should be
* @returns {Function} the new handler function with the added method check
*/
export const withMethodCheck = (handler, method = "POST") => {
return (req, res) => {
if (req.method !== method) {
console.error(`Only ${method} requests permitted`);
res.status(405).send();
return;
}
// If the check passed, call the actual handler
return handler(req, res);
};
};