1 module hunt.framework.auth.guard.BasicGuard;
2 
3 import hunt.framework.auth.guard.Guard;
4 import hunt.framework.auth.AuthOptions;
5 import hunt.framework.auth.BasicAuthRealm;
6 import hunt.framework.auth.JwtAuthRealm;
7 import hunt.framework.auth.SimpleUserService;
8 import hunt.framework.auth.UserService;
9 import hunt.framework.http.Request;
10 import hunt.http.AuthenticationScheme;
11 import hunt.shiro;
12 
13 import hunt.logging;
14 
15 import std.algorithm;
16 import std.base64;
17 import std.range;
18 import std.string;
19 
20 
21 class BasicGuard : Guard {
22 
23     this() {
24         this(new SimpleUserService(), DEFAULT_GURAD_NAME);
25     }
26 
27     this(UserService userService, string name) {
28         super(userService, name);
29         initialize();
30     }    
31 
32     override AuthenticationToken getToken(Request request) {
33         string tokenString = request.basicToken();
34         
35         if (tokenString.empty)
36             tokenString = request.cookie(tokenCookieName);
37 
38         if(tokenString.empty) {
39             return null;
40         }
41 
42         ubyte[] decoded = Base64.decode(tokenString);
43         string[] values = split(cast(string)decoded, ":");
44         if(values.length != 2) {
45             warningf("Wrong token: %s", values);
46             return null;
47         }
48 
49         string username = values[0];
50         string password = values[1];
51         
52         return new UsernamePasswordToken(username, password);
53     }
54 
55     protected void initialize() {
56         tokenCookieName = BASIC_COOKIE_NAME;
57         authScheme = AuthenticationScheme.Basic;
58 
59         addRealms(new BasicAuthRealm(userService()));
60         // addRealms(new JwtAuthRealm(userService()));
61     }
62 
63 }