@@ -2,23 +2,60 @@ const express = require("express");
22const router = express . Router ( ) ;
33const crowdhandler = require ( "crowdhandler-sdk" ) ;
44
5- router . get ( "*" , async ( req , res ) => {
5+ // Middleware to handle CrowdHandler logic for all GET requests
6+ const crowdHandlerMiddleware = async ( req , res , next ) => {
67 const publicKey = "YOUR_PUBLIC_KEY" ;
7- const public_client = new crowdhandler . PublicClient ( publicKey ) ;
8- const ch_context = new crowdhandler . RequestContext ( req , res ) ;
9- const ch_gatekeeper = new crowdhandler . Gatekeeper ( public_client , ch_context , publicKey ) ;
10- const ch_status = await ch_gatekeeper . validateRequest ( ) ;
11-
12- ch_status . setCookie && ch_gatekeeper . setCookie ( ch_status . cookieValue ) ;
13- ch_status . stripParams && ch_gatekeeper . redirectToCleanUrl ( ch_status . targetURL ) ;
14-
15- if ( ! ch_status . promoted ) {
16- ch_gatekeeper . redirectIfNotPromoted ( ) ;
17- } else {
18- //YOUR CODE HERE
19- res . render ( "index" , { title : "hello" } ) ;
20- ch_gatekeeper . recordPerformance ( ) ;
8+ const publicClient = new crowdhandler . PublicClient ( publicKey ) ;
9+ const chContext = new crowdhandler . RequestContext ( req , res ) ;
10+ const chGatekeeper = new crowdhandler . Gatekeeper ( publicClient , chContext ) ;
11+
12+ try {
13+ const chStatus = await chGatekeeper . validateRequest ( ) ;
14+
15+ if ( chStatus . setCookie ) {
16+ chGatekeeper . setCookie ( chStatus . cookieValue ) ;
17+ }
18+
19+ if ( chStatus . stripParams ) {
20+ chGatekeeper . redirectToCleanUrl ( chStatus . targetURL ) ;
21+ }
22+
23+ if ( ! chStatus . promoted ) {
24+ return chGatekeeper . redirectIfNotPromoted ( ) ;
25+ }
26+
27+ // If the request is promoted, save the chGatekeeper instance in res.locals for later use
28+ res . locals . chGatekeeper = chGatekeeper ;
29+
30+ // Continue to the next middleware or route handler
31+ next ( ) ;
32+ } catch ( err ) {
33+ // Error handling middleware
34+ next ( err ) ;
2135 }
36+ } ;
37+
38+ // Add the CrowdHandler middleware to the router
39+ router . use ( crowdHandlerMiddleware ) ;
40+
41+ // Route handler for all paths
42+ router . get ( "*" , ( req , res , next ) => {
43+ // Render the view and send the HTML
44+ res . render ( "index" , { title : "hello" } , ( err , html ) => {
45+ // Handle any errors during rendering
46+ if ( err ) {
47+ return next ( err ) ;
48+ }
49+
50+ // Send the rendered HTML to the client
51+ res . send ( html ) ;
52+
53+ // If the chGatekeeper instance exists in res.locals, record the performance
54+ if ( res . locals . chGatekeeper ) {
55+ res . locals . chGatekeeper . recordPerformance ( ) ;
56+ }
57+ } ) ;
2258} ) ;
2359
60+ // Export the router
2461module . exports = router ;
0 commit comments