- rename Go module, binary, systemd unit, PG_DATABASE default, frontend package and docs from shared-album to galo - add theme-aware halo emblem and favicon (new ui-branding capability) - add make build-release (versioned, stripped, static binary) and run the binary from the repo root
62 lines
1.1 KiB
Go
62 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"galo/internal/httpx"
|
|
)
|
|
|
|
const (
|
|
ctxUserID = "auth.user_id"
|
|
ctxEmail = "auth.email"
|
|
)
|
|
|
|
func (s *Service) Middleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
token := extractToken(c)
|
|
if token == "" {
|
|
httpx.Abort(c, httpx.Unauthorized("unauthorized", "missing access token"))
|
|
return
|
|
}
|
|
claims, err := s.tm.ParseAccess(token)
|
|
if err != nil {
|
|
httpx.Abort(c, httpx.Unauthorized("unauthorized", "invalid or expired access token"))
|
|
return
|
|
}
|
|
c.Set(ctxUserID, claims.UserID)
|
|
c.Set(ctxEmail, claims.Email)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func extractToken(c *gin.Context) string {
|
|
h := c.GetHeader("Authorization")
|
|
if strings.HasPrefix(h, "Bearer ") {
|
|
return strings.TrimPrefix(h, "Bearer ")
|
|
}
|
|
if t := c.Query("token"); t != "" {
|
|
return t
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func UserID(c *gin.Context) string {
|
|
if v, ok := c.Get(ctxUserID); ok {
|
|
return v.(string)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func Email(c *gin.Context) string {
|
|
if v, ok := c.Get(ctxEmail); ok {
|
|
return v.(string)
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func (s *Service) ParseToken(token string) (*Claims, error) {
|
|
return s.tm.ParseAccess(token)
|
|
}
|