-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
233 lines (192 loc) · 4.91 KB
/
auth.go
File metadata and controls
233 lines (192 loc) · 4.91 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package auth
import (
"context"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"dario.cat/mergo"
"github.com/golang-jwt/jwt/v5"
"github.com/lemmego/api/app"
"github.com/lemmego/api/session"
"golang.org/x/crypto/bcrypt"
)
var (
ErrUsernameMismatch = errors.New("username mismatch")
ErrPasswordMismatch = errors.New("password mismatch")
ErrJwtCouldNotBeSigned = errors.New("jwt could not be signed")
)
func init() {
gob.Register(&User{})
}
const UserKey = "user"
type Opts struct {
DisableSession bool
JwtSecret string
JwtClaims jwt.MapClaims
HomeRoute string
}
type Provider struct {
Opts *Opts
}
type Auth struct {
sess *session.Session
jwtSecret []byte
jwtClaims jwt.MapClaims
homeRoute string
}
type LoginResult struct {
Err error
JwtToken string
Cookie *http.Cookie
}
func New() *Auth {
return &Auth{}
}
func (ap *Provider) Provide(a app.App) error {
fmt.Println("Registering Auth")
var sess *session.Session
var jwtSecret string
if !ap.Opts.DisableSession {
sess = app.Get[*session.Session](a)
}
if ap.Opts.JwtSecret != "" {
jwtSecret = ap.Opts.JwtSecret
}
auth := &Auth{sess: sess, jwtSecret: []byte(jwtSecret), homeRoute: "/home"}
if ap.Opts.HomeRoute != "" {
auth.homeRoute = ap.Opts.HomeRoute
}
a.AddService(auth)
return nil
}
func Guest(c app.Context) error {
return Get(c.App()).Guest(c)
}
func Protected(c app.Context) error {
return Get(c.App()).Protected(c)
}
func Login(c app.Context, provider UserProvider, username, password string) *LoginResult {
return Get(c.App()).Login(c, provider, username, password)
}
func Check(c app.Context) error {
return Get(c.App()).Check(c)
}
func AuthUser(c app.Context) any {
return c.Get(UserKey)
}
func (p *Provider) WithConfig(config *Opts) *Provider {
p.Opts = config
return p
}
func (a *Auth) Guest(c app.Context) error {
if err := a.Check(c); err == nil {
// Redirect to home
return c.Redirect(a.homeRoute)
}
return c.Next()
}
func (a *Auth) Protected(c app.Context) error {
if err := a.Check(c); err != nil {
return c.Unauthorized(fmt.Errorf("unauthorized: %w", err))
}
return c.Next()
}
func (a *Auth) Check(c app.Context) error {
if a.sess != nil {
if user := a.sess.Get(c.RequestContext(), UserKey); user == nil {
return errors.New("user not found in session")
} else {
c.Set(UserKey, user)
}
}
if string(a.jwtSecret) != "" {
jwtToken := ""
jwtCookie, err := c.Request().Cookie("jwt")
if err == nil {
jwtToken = strings.Replace(jwtCookie.Value, "jwt=", "", -1)
} else {
jwtToken = strings.Replace(c.Header("Authorization"), "bearer ", "", -1)
}
if jwtToken == "" {
return errors.New("jwt cookie not found")
}
token, err := jwt.Parse(jwtToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return a.jwtSecret, nil
})
if err != nil {
return err
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
var authUser map[string]any
if err = json.Unmarshal([]byte(claims["user"].(string)), &authUser); err != nil {
return err
}
c.Set(UserKey, authUser)
return nil
}
}
return nil
}
func (a *Auth) Login(c app.Context, userProvider UserProvider, username, password string) *LoginResult {
loginResult := &LoginResult{}
if userProvider == nil || userProvider.GetUsername() != username {
loginResult.Err = ErrUsernameMismatch
return loginResult
}
if err := bcrypt.CompareHashAndPassword([]byte(userProvider.GetPassword()), []byte(password)); err != nil {
loginResult.Err = ErrPasswordMismatch
return loginResult
}
var token *jwt.Token
userSubEncoded, err := json.Marshal(userProvider)
if err != nil {
loginResult.Err = err
return loginResult
}
defaultClaims := jwt.MapClaims{
"user": string(userSubEncoded),
"sub": userProvider.GetID() + "|" + userProvider.GetUsername(),
}
if string(a.jwtSecret) != "" {
if a.jwtClaims != nil {
err = mergo.Merge(a.jwtClaims, defaultClaims)
if err != nil {
loginResult.Err = errors.New("provided claims could not be merged with the default claims")
return loginResult
}
token = jwt.NewWithClaims(jwt.SigningMethodHS256, a.jwtClaims)
} else {
token = jwt.NewWithClaims(jwt.SigningMethodHS256, defaultClaims)
}
tokenString, err := token.SignedString(a.jwtSecret)
if err != nil {
loginResult.Err = fmt.Errorf(ErrJwtCouldNotBeSigned.Error()+": %w", err)
return loginResult
}
loginResult.JwtToken = tokenString
}
if a.sess != nil {
a.sess.Put(c.RequestContext(), UserKey, userProvider)
}
if loginResult.JwtToken != "" {
c.SetCookie(&http.Cookie{
Name: "jwt",
Value: loginResult.JwtToken,
})
}
return loginResult
}
func (a *Auth) Logout(ctx context.Context) {
if a.sess != nil {
a.sess.Pop(ctx, UserKey)
}
}
func Get(a app.App) *Auth {
return app.Get[*Auth](a)
}