1 module hunt.framework.middleware.AuthMiddleware; 2 3 import hunt.framework.middleware.MiddlewareInterface; 4 5 import hunt.framework.application.Application; 6 import hunt.framework.auth.Auth; 7 import hunt.framework.auth.AuthOptions; 8 import hunt.framework.auth.Claim; 9 import hunt.framework.auth.ClaimTypes; 10 import hunt.framework.auth.Identity; 11 import hunt.framework.auth.UserService; 12 import hunt.framework.config.ApplicationConfig; 13 import hunt.framework.http.RedirectResponse; 14 import hunt.framework.http.Request; 15 import hunt.framework.http.Response; 16 import hunt.framework.http.UnauthorizedResponse; 17 import hunt.framework.Init; 18 import hunt.framework.provider.ServiceProvider; 19 20 21 import hunt.http.HttpHeader; 22 import hunt.http.AuthenticationScheme; 23 import hunt.logging; 24 25 import std.base64; 26 import std.range; 27 import std.string; 28 29 /** 30 * 31 */ 32 class AuthMiddleware : AbstractMiddleware { 33 shared static this() { 34 MiddlewareInterface.register!(typeof(this)); 35 } 36 37 protected bool onAccessable(Request request) { 38 return true; 39 } 40 41 protected Response onRejected(Request request) { 42 if(request.isRestful()) { 43 return new UnauthorizedResponse("", true); 44 } else { 45 ApplicationConfig.AuthConf appConfig = app().config().auth; 46 string unauthorizedUrl = appConfig.unauthorizedUrl; 47 if(unauthorizedUrl.empty ) { 48 return new UnauthorizedResponse("", false, request.auth().scheme()); 49 } else { 50 return new RedirectResponse(request, unauthorizedUrl); 51 } 52 } 53 } 54 55 Response onProcess(Request request, Response response = null) { 56 version(HUNT_AUTH_DEBUG) { 57 infof("path: %s, method: %s", request.path(), request.method ); 58 } 59 60 61 Auth auth = request.auth(); 62 if(!auth.isEnabled()) { 63 warning("The auth is disabled. Are you sure that the guard is defined?"); 64 return onRejected(request); 65 } 66 67 // FIXME: Needing refactor or cleanup -@zhangxueping at 2020-08-04T18:03:55+08:00 68 // More tests are needed 69 // Identity user = auth.user(); 70 // try { 71 // if(user.isAuthenticated()) { 72 // version(HUNT_DEBUG) { 73 // string fullName = user.fullName(); 74 // infof("User [%s / %s] has already logged in.", user.name(), fullName); 75 // } 76 // return null; 77 // } 78 // } catch(Exception ex) { 79 // warning(ex.msg); 80 // version(HUNT_DEBUG) warning(ex); 81 // } 82 83 Identity user = auth.signIn(); 84 if(user.isAuthenticated()) { 85 version(HUNT_DEBUG) { 86 string fullName = user.fullName(); 87 infof("User [%s / %s] logged in.", user.name(), fullName); 88 } 89 90 if(onAccessable(request)) return null; 91 } 92 93 return onRejected(request); 94 } 95 }