-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathendpoints-auth.go
More file actions
301 lines (226 loc) · 7.6 KB
/
Copy pathendpoints-auth.go
File metadata and controls
301 lines (226 loc) · 7.6 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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package main
import (
"fmt"
"log"
"os"
"time"
"net/http"
"github.com/caTUstrophy/backend/db"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator"
"github.com/leebenson/conform"
"golang.org/x/crypto/bcrypt"
)
// Structs
type LoginPayload struct {
Mail string `conform:"trim,email" validate:"required,email"`
Password string `validate:"required"`
}
// Functions
// Check if provided authorization data in request
// is correct and all validity checks are positive.
func (app *App) Authorize(req *http.Request) (bool, *db.User, string) {
jwtSigningSecret := []byte(os.Getenv("JWT_SIGNING_SECRET"))
// Extract JWT from request headers.
requestJWT, err := request.ParseFromRequest(req, request.AuthorizationHeaderExtractor, func(token *jwt.Token) (interface{}, error) {
// Verify that JWT was signed with correct algorithm.
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("[Authorize] Unexpected signing method: %v.", token.Header["alg"])
}
// Return our JWT signing secret as the key to verify integrity of JWT.
return jwtSigningSecret, nil
})
// Check if JWT is valid.
if err != nil {
// Check every useful error variant.
if validationError, ok := err.(*jwt.ValidationError); ok {
if (validationError.Errors & (jwt.ValidationErrorExpired | jwt.ValidationErrorNotValidYet)) != 0 {
// JWT is not yet valid or expired.
return false, nil, "JWT not yet valid or expired"
} else {
// Invalid JWT was delivered.
return false, nil, "JWT was invalid"
}
} else {
// Something went wrong.
return false, nil, "JWT was invalid"
}
}
claims := requestJWT.Claims.(jwt.MapClaims)
// Check if JWT is expired.
jwtExp, ok := claims["exp"].(string)
if !ok {
return false, nil, "JWT contained invalid date"
}
exp, _ := time.Parse(time.RFC3339, jwtExp)
if exp.Before(time.Now()) {
return false, nil, "JWT was expired"
}
// Extract mail of JWT claimed user.
email := claims["iss"].(string)
// Retrieve user from database.
var User db.User
app.DB.Preload("Groups").First(&User, "mail = ?", email)
for i, _ := range User.Groups {
app.DB.Model(&User.Groups[i]).Related(&User.Groups[i].Region)
}
return true, &User, ""
}
// Helper function for Authorize.
// Avoids copy'n'paste and returns the user
// if authentication was succcessful.
// On fail writes an unauthorized response header.
func (app *App) AuthorizeShort(c *gin.Context) *db.User {
// Check authorization for this function.
ok, User, message := app.Authorize(c.Request)
if !ok {
// Signal client an error and expect authorization.
c.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"CaTUstrophy\", error=\"invalid_token\", error_description=\"%s\"", message))
c.Status(http.StatusUnauthorized)
return nil
}
return User
}
// Checks if the supplied user is allowed to execute
// operations labelled with permission for a given region.
func (app *App) CheckScope(user *db.User, region db.Region, permission string) bool {
// Fast, because the typical user is member of few groups.
for _, group := range user.Groups {
if group.AccessRight == "superadmin" {
return true
}
// If someone wants to check only for superadmin without region,
// an empty region is sufficient. Otherwise, the region has
// to be present.
if region.ID == "" {
continue
}
if group.RegionId == region.ID {
if group.AccessRight == permission {
return true
}
}
}
// No group found that gives permission to user.
return false
}
// Check supplied user's access to multiple regions.
func (app *App) CheckScopes(user *db.User, regions []db.Region, permission string) bool {
// Check for superadmin privilege.
if su := app.CheckScope(user, db.Region{}, "superadmin"); su {
return true
}
// Iterate over regions until region with permission is found.
for _, Region := range regions {
if ok := app.CheckScope(user, Region, "admin"); ok {
return true
}
}
// No group found that gives permission to user.
return false
}
// Produce a JWT and store it in application's session cache.
func (app *App) makeToken(c *gin.Context, user *db.User) string {
// Retrieve the session signing key from environment.
jwtSigningSecret := os.Getenv("JWT_SIGNING_SECRET")
// Save current timestamp.
nowTime := time.Now()
expTime := nowTime.Add(app.SessionValidFor).Format(time.RFC3339)
// At this point, the user exists and provided a correct password.
// Create a JWT with claims to identify user.
sessionJWT := jwt.New(jwt.SigningMethodHS512)
claims := sessionJWT.Claims.(jwt.MapClaims)
// Add these claims.
claims["iss"] = user.Mail
claims["iat"] = nowTime.Format(time.RFC3339)
claims["nbf"] = nowTime.Add((-1 * time.Minute)).Format(time.RFC3339)
claims["exp"] = expTime
sessionJWTString, err := sessionJWT.SignedString([]byte(jwtSigningSecret))
if err != nil {
log.Fatalf("[makeToken] Creating JWT went wrong: %s.\nTerminating.", err)
}
return sessionJWTString
}
func (app *App) Login(c *gin.Context) {
var Payload LoginPayload
// Expect login struct fields in JSON request body.
err := c.BindJSON(&Payload)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"Error": "Supplied values in JSON body could not be parsed",
})
return
}
// Validate sent user login data.
conform.Strings(&Payload)
errs := app.Validator.Struct(&Payload)
if errs != nil {
errResp := make(map[string]string)
// Iterate over all validation errors.
for _, err := range errs.(validator.ValidationErrors) {
if err.Tag == "required" {
errResp[err.Field] = "Is required"
} else if err.Tag == "email" {
errResp[err.Field] = "Is not a valid mail address"
}
}
// Send prepared error message to client.
c.JSON(http.StatusBadRequest, errResp)
return
}
// Find user in database.
var User db.User
app.DB.First(&User, "mail = ?", Payload.Mail)
// Check if user is not known to our system.
if User.Mail == "" {
User.PasswordHash = ""
}
// Compare password hash from database with possible plaintext
// password from request. Compares in constant time.
err = bcrypt.CompareHashAndPassword([]byte(User.PasswordHash), []byte(Payload.Password))
if err != nil {
// Signal client that an error occured.
c.JSON(http.StatusBadRequest, gin.H{
"Error": "Mail and/or password is wrong",
})
return
}
// Create session JWT and expiration time of JWT.
sessionJWTString := app.makeToken(c, &User)
// Deliver JWT to client that made the request.
c.JSON(http.StatusOK, gin.H{
"AccessToken": sessionJWTString,
})
}
func (app *App) RenewToken(c *gin.Context) {
// Check authorization for this function.
ok, User, message := app.Authorize(c.Request)
if !ok {
// Signal client an error and expect authorization.
c.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"CaTUstrophy\", error=\"invalid_token\", error_description=\"%s\"", message))
c.Status(http.StatusUnauthorized)
return
}
// Create session JWT and expiration time of JWT.
sessionJWTString := app.makeToken(c, User)
// Deliver JWT to client that made the request.
c.JSON(http.StatusOK, gin.H{
"AccessToken": sessionJWTString,
})
}
func (app *App) Logout(c *gin.Context) {
// Check authorization for this function.
ok, User, message := app.Authorize(c.Request)
if !ok {
// Signal client an error and expect authorization.
c.Header("WWW-Authenticate", fmt.Sprintf("Bearer realm=\"CaTUstrophy\", error=\"invalid_token\", error_description=\"%s\"", message))
c.Status(http.StatusUnauthorized)
return
}
// Signal client success and return ID of logged out user.
c.JSON(http.StatusOK, gin.H{
"ID": User.ID,
})
}