97 lines
2.4 KiB
Go
97 lines
2.4 KiB
Go
|
package controller
|
||
|
|
||
|
import (
|
||
|
"log"
|
||
|
"time"
|
||
|
|
||
|
jwt "github.com/appleboy/gin-jwt/v2"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"github.com/naiba/nezha/model"
|
||
|
)
|
||
|
|
||
|
func initParams() *jwt.GinJWTMiddleware {
|
||
|
return &jwt.GinJWTMiddleware{
|
||
|
Realm: "test zone",
|
||
|
Key: []byte("secret key"),
|
||
|
Timeout: time.Hour,
|
||
|
MaxRefresh: time.Hour,
|
||
|
IdentityKey: model.CtxKeyAuthorizedUser,
|
||
|
PayloadFunc: payloadFunc(),
|
||
|
|
||
|
IdentityHandler: identityHandler(),
|
||
|
Authenticator: authenticator(),
|
||
|
Authorizator: authorizator(),
|
||
|
Unauthorized: unauthorized(),
|
||
|
TokenLookup: "header: Authorization, query: token, cookie: jwt",
|
||
|
TokenHeadName: "Bearer",
|
||
|
TimeFunc: time.Now,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func handlerMiddleWare(authMiddleware *jwt.GinJWTMiddleware) gin.HandlerFunc {
|
||
|
return func(context *gin.Context) {
|
||
|
errInit := authMiddleware.MiddlewareInit()
|
||
|
if errInit != nil {
|
||
|
log.Fatal("authMiddleware.MiddlewareInit() Error:" + errInit.Error())
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func payloadFunc() func(data interface{}) jwt.MapClaims {
|
||
|
return func(data interface{}) jwt.MapClaims {
|
||
|
if v, ok := data.(*model.User); ok {
|
||
|
return jwt.MapClaims{
|
||
|
model.CtxKeyAuthorizedUser: v.Username,
|
||
|
}
|
||
|
}
|
||
|
return jwt.MapClaims{}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func identityHandler() func(c *gin.Context) interface{} {
|
||
|
return func(c *gin.Context) interface{} {
|
||
|
claims := jwt.ExtractClaims(c)
|
||
|
return &model.User{
|
||
|
Username: claims[model.CtxKeyAuthorizedUser].(string),
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func authenticator() func(c *gin.Context) (interface{}, error) {
|
||
|
return func(c *gin.Context) (interface{}, error) {
|
||
|
var loginVals model.LoginRequest
|
||
|
if err := c.ShouldBind(&loginVals); err != nil {
|
||
|
return "", jwt.ErrMissingLoginValues
|
||
|
}
|
||
|
userID := loginVals.Username
|
||
|
password := loginVals.Password
|
||
|
|
||
|
if (userID == "admin" && password == "admin") || (userID == "test" && password == "test") {
|
||
|
return &model.User{
|
||
|
Username: userID,
|
||
|
}, nil
|
||
|
}
|
||
|
return nil, jwt.ErrFailedAuthentication
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func authorizator() func(data interface{}, c *gin.Context) bool {
|
||
|
return func(data interface{}, c *gin.Context) bool {
|
||
|
if v, ok := data.(*model.User); ok && v.Username == "admin" {
|
||
|
return true
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func unauthorized() func(c *gin.Context, code int, message string) {
|
||
|
return func(c *gin.Context, code int, message string) {
|
||
|
c.JSON(code, model.CommonResponse{
|
||
|
Success: false,
|
||
|
Error: model.CommonError{
|
||
|
Code: model.ApiErrorUnauthorized,
|
||
|
},
|
||
|
})
|
||
|
}
|
||
|
}
|