55import io .jsonwebtoken .Jws ;
66import io .jsonwebtoken .JwtException ;
77import io .jsonwebtoken .Jwts ;
8+ import org .slf4j .Logger ;
9+ import org .slf4j .LoggerFactory ;
810
911import java .nio .charset .StandardCharsets ;
1012import java .util .Arrays ;
1315import static spark .Spark .*;
1416
1517public class App {
18+ private static final Logger log = LoggerFactory .getLogger (App .class );
1619
1720 public static void main (String [] args ) {
1821 Gson gson = new Gson ();
@@ -21,7 +24,7 @@ public static void main(String[] args) {
2124 Config dotenv = new Config ();
2225 String secretOri = dotenv .getValue ("JWT_SECRET" );
2326 byte [] bytesToEncode = secretOri .getBytes (StandardCharsets .UTF_8 );
24-
27+
2528 // Encode the bytes using Base64
2629 String secret = Base64 .getEncoder ().encodeToString (bytesToEncode );
2730
@@ -36,20 +39,20 @@ public static void main(String[] args) {
3639 before ("/api/sync" , (request , response ) -> {
3740 String authHeader = request .headers ("Authorization" );
3841 try {
39- if (authHeader == null || !authHeader .startsWith ("Bearer " )) {
40- throw new JwtException ("Missing or invalid token" );
41- } else {
42- String token = authHeader .substring (7 );
43- Jws <Claims > claimsJws = Jwts .parserBuilder ().setSigningKey (secret ).build ().parseClaimsJws (token );
44- String id = claimsJws .getBody ().get ("id" ).toString ();
45- boolean found = Arrays .stream (idArrStrings ).anyMatch (element -> element .equals (id ));
46- if (!found ) {
47- throw new JwtException ("Unauthorized access" );
48- }
49- request .attribute ("jwtId" , id );
50- }
42+ if (authHeader == null || !authHeader .startsWith ("Bearer " )) {
43+ throw new JwtException ("Missing or invalid token" );
44+ } else {
45+ String token = authHeader .substring (7 );
46+ Jws <Claims > claimsJws = Jwts .parserBuilder ().setSigningKey (secret ).build ().parseClaimsJws (token );
47+ String id = claimsJws .getBody ().get ("id" ).toString ();
48+ boolean found = Arrays .stream (idArrStrings ).anyMatch (element -> element .equals (id ));
49+ if (!found ) {
50+ throw new JwtException ("Unauthorized access" );
51+ }
52+ request .attribute ("jwtId" , id );
53+ }
5154 } catch (JwtException ex ) {
52- halt (401 , "Unauthorized: " + ex .getMessage ());
55+ halt (401 , "Unauthorized: " + ex .getMessage ());
5356 }
5457 });
5558
@@ -70,10 +73,11 @@ public static void main(String[] args) {
7073 response .status (r .statusCode );
7174 return r .message ;
7275 });
73-
76+
7477 after ((request , response ) -> {
7578 response .type ("application/json" );
7679 response .header ("Content-Encoding" , "gzip" );
80+ log .info (String .format ("%s[%s] - [%s]" , request .requestMethod (), request .url (), response .status ()));
7781 });
7882 }
7983}
0 commit comments