-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathrequireAuth.ts
53 lines (47 loc) · 1.48 KB
/
requireAuth.ts
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
import type { RequestHandler } from 'express';
import { authenticateAndDecorateRequest } from './authenticateRequest';
import type { ClerkMiddlewareOptions, ExpressRequestWithAuth } from './types';
/**
* Middleware to require authentication for user requests.
* Redirects unauthenticated requests to the sign-in url.
*
* @example
* // Basic usage
* import { requireAuth } from '@clerk/express'
*
* router.use(requireAuth())
* //or
* router.get('/path', requireAuth(), getHandler)
*
* @example
* // Customizing the sign-in path
* router.use(requireAuth({ signInUrl: '/sign-in' }))
*
* @example
* // Combining with permission check
* import { getAuth, requireAuth } from '@clerk/express'
*
* const hasPermission = (req, res, next) => {
* const auth = getAuth(req)
* if (!auth.has({ permission: 'permission' })) {
* return res.status(403).send('Forbidden')
* }
* return next()
* }
* router.get('/path', requireAuth(), hasPermission, getHandler)
*/
export const requireAuth = (options: ClerkMiddlewareOptions = {}): RequestHandler => {
const authMiddleware = authenticateAndDecorateRequest(options);
return (request, response, next) => {
authMiddleware(request, response, err => {
if (err) {
return next(err);
}
const signInUrl = options.signInUrl || process.env.CLERK_SIGN_IN_URL || '/';
if (!(request as ExpressRequestWithAuth).auth?.userId) {
return response.redirect(signInUrl);
}
next();
});
};
};