-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
134 lines (110 loc) · 2.5 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/MicahParks/keyfunc"
"github.com/golang-jwt/jwt/v4"
"github.com/labstack/echo/v4"
)
const (
RoleAdmin = "admin"
)
type User interface {
IsAdmin() bool
Username() string
GetClaim(name string) string
}
type user struct {
claims jwt.MapClaims
}
func GetUser(c echo.Context) User {
user := c.Get("user")
if user, ok := user.(User); ok {
return user
}
return nil
}
func (u *user) getClaim(claimName string) string {
if s, ok := u.claims[claimName]; ok {
switch s := s.(type) {
case string:
return s
case []string:
if len(s) > 0 {
return s[0]
}
case []interface{}:
if len(s) > 0 {
return fmt.Sprintf("%v", s[0])
}
}
}
return ""
}
func (u *user) IsAdmin() bool {
return u.getClaim("blocks:role") == RoleAdmin
}
func (u *user) Username() string {
return u.getClaim("name")
}
func (u *user) GetClaim(name string) string {
return u.getClaim(name)
}
type anonymous struct{}
func (d *anonymous) IsAdmin() bool {
return false
}
func (d *anonymous) Username() string {
return "anonymous"
}
func (d *anonymous) GetClaim(string) string {
return ""
}
func AnonymousAccess() echo.MiddlewareFunc {
user := &anonymous{}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Set("user", user)
return next(c)
}
}
}
func Authorize(jwksUri string) echo.MiddlewareFunc {
options := keyfunc.Options{
Ctx: context.Background(),
RefreshErrorHandler: func(err error) {
log.Printf("There was an error with the jwt.Keyfunc\nError: %s", err.Error())
},
RefreshInterval: 5 * time.Minute,
RefreshRateLimit: 10 * time.Second,
RefreshTimeout: 10 * time.Second,
RefreshUnknownKID: true,
}
jwks, err := keyfunc.Get(jwksUri, options)
if err != nil {
log.Fatalf("Failed to create JWKS from resource at the given URL.\nError: %s", err.Error())
}
const bearerPrefix = "bearer "
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
headerValue := c.Request().Header.Get("authorization")
if headerValue == "" || !strings.HasPrefix(strings.ToLower(headerValue), bearerPrefix) {
return echo.ErrUnauthorized
}
jwtB64 := headerValue[len(bearerPrefix):]
claims := make(jwt.MapClaims)
token, err := jwt.ParseWithClaims(jwtB64, claims, jwks.Keyfunc)
if err != nil {
return err
}
if !token.Valid {
return echo.ErrUnauthorized
}
c.Set("user", &user{claims})
return next(c)
}
}
}