1 module hunt.framework.auth.guard.Guard; 2 3 import hunt.framework.auth.AuthOptions; 4 import hunt.framework.auth.AuthRealm; 5 import hunt.framework.auth.HuntShiroCache; 6 import hunt.framework.auth.ShiroCacheManager; 7 import hunt.framework.auth.UserService; 8 import hunt.framework.config.ApplicationConfig; 9 import hunt.framework.http.Request; 10 import hunt.framework.provider.ServiceProvider; 11 import hunt.http.AuthenticationScheme; 12 import hunt.shiro; 13 import hunt.shiro.session.mgt.SessionManager; 14 import hunt.shiro.session.mgt.DefaultSessionManager; 15 16 import hunt.logging; 17 18 19 20 /** 21 * 22 */ 23 abstract class Guard { 24 private DefaultSecurityManager _securityManager; 25 private Realm[] _realms; 26 private UserService _userService; 27 private int _tokenExpiration = DEFAULT_TOKEN_EXPIRATION*24*60*60; 28 private AuthenticationScheme _authScheme = AuthenticationScheme.Bearer; 29 private string _tokenCookieName = JWT_COOKIE_NAME; 30 31 private string _name; 32 33 this(UserService userService, string name = DEFAULT_GURAD_NAME) { 34 _userService = userService; 35 _name = name; 36 37 ApplicationConfig appConfig = serviceContainer().resolve!ApplicationConfig(); 38 _tokenExpiration = appConfig.auth.tokenExpiration; 39 } 40 41 string name() { 42 return _name; 43 } 44 45 UserService userService() { 46 return _userService; 47 } 48 49 Guard tokenExpiration(int value) { 50 _tokenExpiration = value; 51 return this; 52 } 53 54 int tokenExpiration() { 55 return _tokenExpiration; 56 } 57 58 Guard tokenCookieName(string value) { 59 _tokenCookieName = value; 60 return this; 61 } 62 63 string tokenCookieName() { 64 return _tokenCookieName; 65 } 66 67 AuthenticationScheme authScheme() { 68 return _authScheme; 69 } 70 71 Guard authScheme(AuthenticationScheme value) { 72 _authScheme = value; 73 return this; 74 } 75 76 Guard addRealms(AuthRealm realm) { 77 _realms ~= cast(Realm)realm; 78 return this; 79 } 80 81 AuthenticationToken getToken(Request request); 82 83 void boot() { 84 try { 85 HuntCache cache = serviceContainer().resolve!HuntCache(); 86 CacheManager cacheManager = new ShiroCacheManager(cache); 87 _securityManager = new DefaultSecurityManager(); 88 DefaultSessionManager sm = cast(DefaultSessionManager)_securityManager.getSessionManager(); 89 90 if(sm !is null) { 91 sm.setGlobalSessionTimeout(_tokenExpiration*1000); 92 } 93 94 SecurityUtils.setSecurityManager(_name, _securityManager); 95 _securityManager.setRealms(_realms); 96 _securityManager.setCacheManager(cacheManager); 97 } catch(Exception ex) { 98 warning(ex.msg); 99 version(HUNT_DEBUG) warning(ex); 100 } 101 } 102 103 }