github.com/ngocphuongnb/tetua@v0.0.7-alpha/app/auth/middlewares.go (about) 1 package auth 2 3 import ( 4 "net/http" 5 "net/url" 6 "time" 7 8 "github.com/golang-jwt/jwt/v4" 9 "github.com/ngocphuongnb/tetua/app/config" 10 "github.com/ngocphuongnb/tetua/app/entities" 11 "github.com/ngocphuongnb/tetua/app/server" 12 "github.com/ngocphuongnb/tetua/app/utils" 13 ) 14 15 func Check(c server.Context) error { 16 var routeName = c.RouteName() 17 var userRoles = []*entities.Role{ROLE_GUEST} 18 var user = c.User() 19 var authConfig = GetAuthConfig(routeName) 20 21 // If there is no auth config for this route, then allow all 22 if authConfig == nil { 23 return c.Next() 24 } 25 26 if authConfig.Prepare != nil { 27 if err := authConfig.Prepare(c); err != nil { 28 if entities.IsNotFound(err) { 29 return c.Status(http.StatusNotFound).SendString("Not found") 30 } 31 return err 32 } 33 } 34 35 if user != nil && user.IsRoot() { 36 return c.Next() 37 } 38 39 if user != nil { 40 userRoles = user.Roles 41 } 42 43 if user.ID > 0 && !user.Active { 44 c.Cookie(&server.Cookie{ 45 Name: config.APP_TOKEN_KEY, 46 Value: "", 47 Expires: time.Now().Add(time.Hour * 100 * 365 * 24), 48 }) 49 50 return c.Redirect(utils.Url("/inactive")) 51 } 52 53 // Check all user roles for this action 54 for _, role := range userRoles { 55 permission := GetRolePermission(role.ID, routeName) 56 57 if permission.Value == entities.PERM_ALL { 58 return c.Next() 59 } 60 61 if permission.Value == entities.PERM_OWN && authConfig.OwnCheckFN != nil && authConfig.OwnCheckFN(c) { 62 return c.Next() 63 } 64 } 65 66 if user == nil || user.ID == 0 { 67 return c.Redirect("/login?back=" + url.QueryEscape(c.OriginalURL())) 68 } 69 70 return c.Status(http.StatusForbidden).SendString("Insufficient permission") 71 } 72 73 func AssignUserInfo(c server.Context) error { 74 c.Locals("user", GUEST_USER) 75 tokenString := c.Cookies(config.APP_TOKEN_KEY) 76 77 if tokenString == "" { 78 return c.Next() 79 } 80 81 token, err := jwt.ParseWithClaims( 82 tokenString, 83 &entities.UserJwtClaims{}, 84 func(token *jwt.Token) (interface{}, error) { 85 return []byte(config.APP_KEY), nil 86 }, 87 ) 88 89 if err == nil { 90 if claims, ok := token.Claims.(*entities.UserJwtClaims); ok && token.Valid { 91 user := &claims.User 92 user.Roles = GetRolesFromIDs(user.RoleIDs) 93 c.Locals("user", user) 94 } 95 } else { 96 c.Logger().Error(err) 97 } 98 99 return c.Next() 100 }