diff --git a/32-platform/platform/authorization/auth_middleware.go b/32-platform/platform/authorization/auth_middleware.go new file mode 100644 index 0000000..d2acbdf --- /dev/null +++ b/32-platform/platform/authorization/auth_middleware.go @@ -0,0 +1,77 @@ +package authorization + +import ( + "net/http" + "platform/authorization/identity" + "platform/config" + "platform/http/handing" + "platform/pipeline" + "regexp" + "strings" +) + +func NewAuthComponent(prefix string, condition identity.AuthorizationCondition, requestHandlers ...interface{}) *AuthMiddlewareComponent { + var entries []handing.HandlerEntry + for _, handler := range requestHandlers { + entries = append(entries, handing.HandlerEntry{Prefix: prefix, Handler: handler}) + } + router := handing.NewRouter(entries...) + + return &AuthMiddlewareComponent{ + prefix: "/" + prefix, + condition: condition, + RequestPipeline: pipeline.CreatePipeline(router), + fallbacks: map[*regexp.Regexp]string{}, + } +} + +type AuthMiddlewareComponent struct { + prefix string + condition identity.AuthorizationCondition + pipeline.RequestPipeline + config.Configuration + authFailUrl string + fallbacks map[*regexp.Regexp]string +} + +func (c *AuthMiddlewareComponent) Init() { + c.authFailUrl, _ = c.Configuration.GetString("authorization:failUrl") +} + +func (c *AuthMiddlewareComponent) ImplementsProcessRequestWithServices() {} + +func (c *AuthMiddlewareComponent) ProcessRequestWithService(context *pipeline.ComponentContext, next func(*pipeline.ComponentContext), user identity.User) { + // 匹配前缀 + if strings.HasPrefix(context.Request.URL.Path, c.prefix) { + for expr, target := range c.fallbacks { + // 正则表达式匹配,则跳转URL + if expr.MatchString(context.Request.URL.Path) { + http.Redirect(context.ResponseWriter, context.Request, target, http.StatusSeeOther) + return + } + } + if c.condition.Validate(user) { + // 验证通过,则继续处理 + err := c.RequestPipeline.ProcessRequest(context.Request, context.ResponseWriter) + if err != nil { + context.Error(err) + return + } + } else if c.authFailUrl != "" { + http.Redirect(context.ResponseWriter, context.Request, c.authFailUrl, http.StatusSeeOther) + } else if user.IsAuthenticated() { + context.ResponseWriter.WriteHeader(http.StatusForbidden) + } else { + context.ResponseWriter.WriteHeader(http.StatusUnauthorized) + } + } else { + next(context) + } +} + +func (c *AuthMiddlewareComponent) AddFallback(target string, patterns ...string) *AuthMiddlewareComponent { + for _, p := range patterns { + c.fallbacks[regexp.MustCompile(p)] = target + } + return c +} diff --git a/32-platform/platform/authorization/role_condition.go b/32-platform/platform/authorization/role_condition.go new file mode 100644 index 0000000..e91795f --- /dev/null +++ b/32-platform/platform/authorization/role_condition.go @@ -0,0 +1,20 @@ +package authorization + +import "platform/authorization/identity" + +func NewRoleCondition(roles ...string) identity.AuthorizationCondition { + return &roleCondition{allowedRoles: roles} +} + +type roleCondition struct { + allowedRoles []string +} + +func (c *roleCondition) Validate(user identity.User) bool { + for _, role := range c.allowedRoles { + if user.InRole(role) { + return true + } + } + return false +} diff --git a/32-platform/platform/authorization/user_service.go b/32-platform/platform/authorization/user_service.go new file mode 100644 index 0000000..1ef6da6 --- /dev/null +++ b/32-platform/platform/authorization/user_service.go @@ -0,0 +1,23 @@ +package authorization + +import ( + "platform/authorization/identity" + "platform/services" + "platform/sessions" +) + +func RegisterDefaultUserService() { + err := services.AddScoped(func(session sessions.Session, store identity.UserStore) identity.User { + userId, found := session.GetValue(UserSessionKey).(int) + if found { + user, userFound := store.GetUserById(userId) + if userFound { + return user + } + } + return identity.UnauthenticatedUser + }) + if err != nil { + panic(err) + } +}