@payez/next-mvp 3.4.0 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Server-Side Auth Wrapper for API Routes & Server Actions
3
+ *
4
+ * Wraps route handlers with session validation. Uses direct Redis reads.
5
+ * Zero HTTP self-fetches.
6
+ *
7
+ * Usage:
8
+ * export const GET = withAuth(async (req, auth) => {
9
+ * return NextResponse.json({ userId: auth.userId });
10
+ * });
11
+ *
12
+ * // With role requirement:
13
+ * export const POST = withAuth(async (req, auth) => { ... }, { requiredRoles: ['admin'] });
14
+ */
15
+
16
+ import 'server-only';
17
+ import { NextRequest, NextResponse } from 'next/server';
18
+ import { decodeSession } from './decode-session';
19
+ import type { SessionData } from '../lib/session-store';
20
+
21
+ // =============================================================================
22
+ // TYPES
23
+ // =============================================================================
24
+
25
+ export interface ApiAuthResult {
26
+ userId: string;
27
+ email: string;
28
+ roles: string[];
29
+ sessionData: SessionData;
30
+ accessToken?: string;
31
+ }
32
+
33
+ export interface WithAuthOptions {
34
+ /** Roles required to access the route (any match = allowed) */
35
+ requiredRoles?: string[];
36
+ }
37
+
38
+ // =============================================================================
39
+ // MAIN
40
+ // =============================================================================
41
+
42
+ /**
43
+ * Wrap an API route handler with auth validation.
44
+ * Returns 401 if not authenticated, 403 if missing required roles.
45
+ */
46
+ export function withAuth(
47
+ handler: (req: NextRequest, auth: ApiAuthResult) => Promise<NextResponse>,
48
+ options?: WithAuthOptions
49
+ ): (req: NextRequest) => Promise<NextResponse> {
50
+ return async (req: NextRequest): Promise<NextResponse> => {
51
+ try {
52
+ // Decode session from request cookies (direct Redis, no self-fetch)
53
+ const decoded = await decodeSession(req.cookies);
54
+
55
+ if (!decoded) {
56
+ return NextResponse.json(
57
+ { error: 'Unauthorized', message: 'No valid session' },
58
+ { status: 401 }
59
+ );
60
+ }
61
+
62
+ const { sessionData } = decoded;
63
+
64
+ // Check required roles
65
+ if (options?.requiredRoles && options.requiredRoles.length > 0) {
66
+ const userRoles = sessionData.roles || [];
67
+ const hasRole = options.requiredRoles.some(r => userRoles.includes(r));
68
+ if (!hasRole) {
69
+ return NextResponse.json(
70
+ { error: 'Forbidden', message: 'Insufficient permissions' },
71
+ { status: 403 }
72
+ );
73
+ }
74
+ }
75
+
76
+ const auth: ApiAuthResult = {
77
+ userId: sessionData.userId,
78
+ email: sessionData.email,
79
+ roles: sessionData.roles || [],
80
+ sessionData,
81
+ accessToken: sessionData.idpAccessToken,
82
+ };
83
+
84
+ return handler(req, auth);
85
+ } catch (error) {
86
+ console.error('[WITH-AUTH] Error:', error instanceof Error ? error.message : String(error));
87
+ return NextResponse.json(
88
+ { error: 'Internal Server Error', message: 'Auth check failed' },
89
+ { status: 500 }
90
+ );
91
+ }
92
+ };
93
+ }