You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.5 KiB

4 years ago
  1. package auth
  2. import (
  3. "context"
  4. "encoding/base64"
  5. "encoding/json"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gissleh/stufflog/internal/slerrors"
  8. "net/http"
  9. "strings"
  10. )
  11. var contextKey = struct{}{}
  12. func UserID(ctx context.Context) string {
  13. if c, ok := ctx.(*gin.Context); ok {
  14. return UserID(c.Request.Context())
  15. }
  16. return ctx.Value(&contextKey).(string)
  17. }
  18. func DummyMiddleware(uuid string) gin.HandlerFunc {
  19. return func(c *gin.Context) {
  20. c.Request = c.Request.WithContext(
  21. context.WithValue(c.Request.Context(), &contextKey, uuid),
  22. )
  23. }
  24. }
  25. func abortRequest(c *gin.Context) {
  26. c.AbortWithStatusJSON(http.StatusUnauthorized, slerrors.ErrorResponse{
  27. Code: http.StatusUnauthorized,
  28. Message: "You're not supposed to be here!",
  29. })
  30. }
  31. // TrustingJwtParserMiddleware is meant to be put behind an AWS API gateway that has already
  32. // verified this token.
  33. func TrustingJwtParserMiddleware() gin.HandlerFunc {
  34. return func(c *gin.Context) {
  35. auth := c.GetHeader("Authorization")
  36. split := strings.Split(auth, ".")
  37. if len(split) >= 3 {
  38. data, err := base64.RawStdEncoding.DecodeString(split[1])
  39. if err != nil {
  40. abortRequest(c)
  41. return
  42. }
  43. fields := make(map[string]interface{})
  44. err = json.Unmarshal(data, &fields)
  45. if err != nil {
  46. abortRequest(c)
  47. return
  48. }
  49. if sub, ok := fields["sub"].(string); ok {
  50. c.Request = c.Request.WithContext(
  51. context.WithValue(c.Request.Context(), &contextKey, sub),
  52. )
  53. } else {
  54. abortRequest(c)
  55. return
  56. }
  57. } else {
  58. abortRequest(c)
  59. }
  60. }
  61. }