1 module hunt.framework.auth.JwtUtil;
2 
3 import hunt.framework.auth.AuthOptions;
4 import hunt.jwt;
5 import hunt.logging;
6 import hunt.util.DateTime;
7 
8 import core.time;
9 import std.json;
10 
11 
12 /**
13  * 
14  */
15 class JwtUtil {
16 
17     __gshared Duration EXPIRE_TIME = days(DEFAULT_TOKEN_EXPIRATION);
18 
19     static bool verify(string token, string username, string secret) {
20         try {
21             return JwtToken.verify(token, secret);
22         } catch (Exception e) {
23             warning(e.msg);
24             version(HUNT_AUTH_DEBUG) warning(e);
25             return false;
26         }
27     }
28     
29     static string getUsername(string token) {
30         try {
31             JwtToken tk = JwtToken.decode(token);
32             return tk.claims().sub();
33         } catch (Exception e) {
34             warning(e);
35             return null;
36         }
37     }
38 
39     static string sign(string username, string secret, JwtAlgorithm algo = JwtAlgorithm.HS512) {
40         return sign(username, secret, EXPIRE_TIME, null, algo);
41     }
42     
43     static string sign(string username, string secret, string[string] claims, JwtAlgorithm algo = JwtAlgorithm.HS512) {
44         return sign(username, secret, EXPIRE_TIME, claims, algo);
45     }
46 
47     static string sign(string username, string secret, Duration expireTime, 
48             string[string] claims = null, JwtAlgorithm algo = JwtAlgorithm.HS512) {
49         JSONValue claimsInJson = JSONValue(claims);
50         return sign(username, secret, expireTime, claimsInJson, algo);
51     }
52 
53     static string sign(string username, string secret, Duration expireTime, 
54             JSONValue claims, JwtAlgorithm algo = JwtAlgorithm.HS512) {
55         version(HUNT_AUTH_DEBUG) {
56             infof("username: %s, secret: %s", username, secret);
57         }
58 
59         JwtToken token = new JwtToken(algo);
60         token.claims.sub = username;
61         token.claims.exp = cast(int) DateTime.currentUnixTime() + expireTime.total!(TimeUnit.Second)();
62         // token.claims.set("username", username);
63 
64         foreach(string key, JSONValue value; claims) {
65             token.claims.set(key, value);
66         }
67 
68         return token.encode(secret);        
69     }
70 }