jwt_helper.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * @Author: LinkLeong link@icewhale.com
  3. * @Date: 2022-06-17 14:01:25
  4. * @LastEditors: LinkLeong
  5. * @LastEditTime: 2022-07-29 16:14:33
  6. * @FilePath: /CasaOS/pkg/utils/jwt/jwt_helper.go
  7. * @Description:
  8. * @Website: https://www.casaos.io
  9. * Copyright (c) 2022 by icewhale, All Rights Reserved.
  10. */
  11. package jwt
  12. import (
  13. "fmt"
  14. "strconv"
  15. "time"
  16. "github.com/IceWhaleTech/CasaOS/model"
  17. "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
  18. loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
  19. "github.com/gin-gonic/gin"
  20. )
  21. func JWT() gin.HandlerFunc {
  22. return func(c *gin.Context) {
  23. var code int
  24. code = common_err.SUCCESS
  25. token := c.GetHeader("Authorization")
  26. if len(token) == 0 {
  27. token = c.Query("token")
  28. }
  29. if token == "" {
  30. code = common_err.INVALID_PARAMS
  31. }
  32. claims, err := ParseToken(token, false)
  33. //_, err := ParseToken(token)
  34. if err != nil {
  35. code = common_err.ERROR_AUTH_TOKEN
  36. } else if (c.Request.URL.Path == "/v1/file" || c.Request.URL.Path == "/v1/sys/version/check" || c.Request.URL.Path == "/v1/image" || c.Request.URL.Path == "/v1/file/upload" || c.Request.URL.Path == "/v1/batch") && claims.VerifyIssuer("casaos", true) {
  37. //Special treatment
  38. } else if !claims.VerifyExpiresAt(time.Now(), true) || !claims.VerifyIssuer("casaos", true) {
  39. code = common_err.ERROR_AUTH_TOKEN
  40. }
  41. if code != common_err.SUCCESS {
  42. c.JSON(code, model.Result{Success: code, Message: common_err.GetMsg(code)})
  43. c.Abort()
  44. return
  45. }
  46. c.Request.Header.Add("user_id", strconv.Itoa(claims.Id))
  47. c.Next()
  48. }
  49. }
  50. //get AccessToken
  51. func GetAccessToken(username, pwd string, id int) string {
  52. token, err := GenerateToken(username, pwd, id, "casaos", 3*time.Hour*time.Duration(1))
  53. if err == nil {
  54. return token
  55. } else {
  56. loger2.Error(fmt.Sprintf("Get Token Fail: %V", err))
  57. return ""
  58. }
  59. }
  60. func GetRefreshToken(username, pwd string, id int) string {
  61. token, err := GenerateToken(username, pwd, id, "refresh", 7*24*time.Hour*time.Duration(1))
  62. if err == nil {
  63. return token
  64. } else {
  65. loger2.Error(fmt.Sprintf("Get Token Fail: %V", err))
  66. return ""
  67. }
  68. }