github.com/germla/auth@v0.0.0-20230505173936-bc9a4159cf17/authority/authority_rule.go (about) 1 package authority 2 3 import ( 4 "net/http" 5 "time" 6 7 "github.com/qor/roles" 8 ) 9 10 // Rule authority rule's definition 11 type Rule struct { 12 TimeoutSinceLastLogin time.Duration 13 LongestDistractionSinceLastLogin time.Duration 14 } 15 16 // Handler generate roles checker 17 func (authority Authority) Handler(rule Rule) roles.Checker { 18 return func(req *http.Request, user interface{}) bool { 19 claims, _ := authority.Auth.Get(req) 20 21 // Check Last Auth 22 if rule.TimeoutSinceLastLogin > 0 { 23 if claims == nil || claims.LastLoginAt == nil || time.Now().Add(-rule.TimeoutSinceLastLogin).After(*claims.LastLoginAt) { 24 return false 25 } 26 } 27 28 // Check Distraction 29 if rule.LongestDistractionSinceLastLogin > 0 { 30 if claims == nil || claims.LongestDistractionSinceLastLogin == nil || *claims.LongestDistractionSinceLastLogin > rule.LongestDistractionSinceLastLogin { 31 return false 32 } 33 } 34 35 return true 36 } 37 } 38 39 // Register register authority rule into Role 40 func (authority *Authority) Register(name string, rule Rule) { 41 authority.Config.Role.Register(name, authority.Handler(rule)) 42 } 43 44 // Allow Check allow role or not 45 func (authority *Authority) Allow(role string, req *http.Request) bool { 46 currentUser := authority.Auth.GetCurrentUser(req) 47 return authority.Role.HasRole(req, currentUser, role) 48 }