82 lines
2.5 KiB
Go
82 lines
2.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
"git.inspur.com/sbg-jszt/cfn/cfn-schedule-agent/internal/pkg/authen"
|
|
"git.inspur.com/sbg-jszt/cfn/cfn-schedule-agent/internal/pkg/errors"
|
|
"git.inspur.com/sbg-jszt/cfn/cfn-schedule-agent/internal/pkg/response"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/golang/glog"
|
|
"regexp"
|
|
)
|
|
|
|
const (
|
|
LoginUserKey = "login-user"
|
|
)
|
|
|
|
func AuthenticationHandler() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
match, _ := regexp.MatchString("/healthz", c.Request.RequestURI)
|
|
if match {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
rawToken := c.Request.Header.Get("Authorization")
|
|
if rawToken == "" {
|
|
glog.Warning("unauthorized access, token not specified")
|
|
response.Resp().FailCode(c, errors.AuthorizationError, "token should be specified in header with 'Authorization' key")
|
|
return
|
|
}
|
|
var username, encrypted string
|
|
ok, bearerToken := authen.JWTAuthorizer.IsBearerToken(rawToken)
|
|
if ok {
|
|
loginInfo, err := authen.JWTAuthorizer.ValidateToken(bearerToken)
|
|
//marshal, _ := json.Marshal(loginInfo)
|
|
//fmt.Print(string(marshal))
|
|
|
|
if err != nil {
|
|
if authen.JWTAuthorizer.IsTokenExpired(err) {
|
|
glog.Warning("unauthorized access, bearer token expired")
|
|
response.Resp().FailCode(c, errors.AuthorizationError, "bearer token expired")
|
|
return
|
|
}
|
|
glog.Warningf("validate bearer token failed, %s", err)
|
|
response.Resp().FailCode(c, errors.AuthorizationError, fmt.Sprint("validate bearer token failed, %s", err))
|
|
return
|
|
}
|
|
username = loginInfo.Username
|
|
encrypted = loginInfo.Encrypted
|
|
} else {
|
|
glog.Warningf("validate bearer token failed")
|
|
response.Resp().FailCode(c, errors.AuthorizationError, "validate bearer token failed")
|
|
|
|
return
|
|
}
|
|
//u, err := user.FindOneByName(username, model.DBAuth())
|
|
//if err != nil {
|
|
// if err == gorm.ErrRecordNotFound {
|
|
// glog.Errorf("unauthorized access, user not found, %s", username)
|
|
// response.Resp().FailCode(c, errors.AuthorizationError, "user not found")
|
|
//
|
|
// return
|
|
// }
|
|
// glog.Errorf("get user from db failed, user %s, %s", username, err)
|
|
// response.Resp().FailCode(c, errors.ServerError, fmt.Sprintf("get user from db failed, user %s, %s", username, err))
|
|
//
|
|
// return
|
|
//}
|
|
//
|
|
//if encrypted != "" && encrypted != u.EncryptedPassword {
|
|
// glog.Warningf("unauthorized access, password mismatch, user %s", username)
|
|
// response.Resp().FailCode(c, errors.AuthorizationError, "password mismatch")
|
|
// return
|
|
//}
|
|
|
|
//c.Set(LoginUserKey, u)
|
|
|
|
c.Set(LoginUserKey, username+":"+encrypted)
|
|
c.Next()
|
|
}
|
|
}
|