auth.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package service
  2. import (
  3. "context"
  4. jwt "github.com/gogf/gf-jwt/v2"
  5. "go-gpt/internal/model"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "time"
  8. )
  9. var authService *jwt.GfJWTMiddleware
  10. func Auth() *jwt.GfJWTMiddleware {
  11. return authService
  12. }
  13. func init() {
  14. auth := jwt.New(&jwt.GfJWTMiddleware{
  15. Realm: "test zone",
  16. Key: []byte("secret key"),
  17. Timeout: time.Minute * 5,
  18. MaxRefresh: time.Minute * 5,
  19. IdentityKey: "id",
  20. TokenLookup: "header: Authorization, query: token, cookie: jwt",
  21. TokenHeadName: "Bearer",
  22. TimeFunc: time.Now,
  23. Authenticator: Authenticator,
  24. Unauthorized: Unauthorized,
  25. PayloadFunc: PayloadFunc,
  26. IdentityHandler: IdentityHandler,
  27. })
  28. authService = auth
  29. }
  30. // PayloadFunc is a callback function that will be called during login.
  31. // Using this function it is possible to add additional payload data to the webtoken.
  32. // The data is then made available during requests via c.Get("JWT_PAYLOAD").
  33. // Note that the payload is not encrypted.
  34. // The attributes mentioned on jwt.io can't be used as keys for the map.
  35. // Optional, by default no additional data will be set.
  36. func PayloadFunc(data interface{}) jwt.MapClaims {
  37. claims := jwt.MapClaims{}
  38. params := data.(map[string]interface{})
  39. if len(params) > 0 {
  40. for k, v := range params {
  41. claims[k] = v
  42. }
  43. }
  44. return claims
  45. }
  46. // IdentityHandler get the identity from JWT and set the identity for every request
  47. // Using this function, by r.GetParam("id") get identity
  48. func IdentityHandler(ctx context.Context) interface{} {
  49. claims := jwt.ExtractClaims(ctx)
  50. return claims[authService.IdentityKey]
  51. }
  52. // Unauthorized is used to define customized Unauthorized callback function.
  53. func Unauthorized(ctx context.Context, code int, message string) {
  54. r := g.RequestFromCtx(ctx)
  55. r.Response.WriteJson(g.Map{
  56. "code": code,
  57. "message": message,
  58. })
  59. r.ExitAll()
  60. }
  61. // Authenticator is used to validate login parameters.
  62. // It must return user data as user identifier, it will be stored in Claim Array.
  63. // if your identityKey is 'id', your user data must have 'id'
  64. // Check error (e) to determine the appropriate error message.
  65. func Authenticator(ctx context.Context) (interface{}, error) {
  66. var (
  67. r = g.RequestFromCtx(ctx)
  68. in model.UserLoginInput
  69. )
  70. if err := r.Parse(&in); err != nil {
  71. return "", err
  72. }
  73. //if user := User().GetUserByUserNamePassword(ctx, in); user != nil {
  74. // return user, nil
  75. //}
  76. return nil, jwt.ErrFailedAuthentication
  77. }