forked from unmojang/drasl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
387 lines (332 loc) · 9.44 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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"bytes"
"encoding/json"
"errors"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
"net/http"
)
/*
Authentication server
*/
func AuthGetServerInfo(app *App) func(c echo.Context) error {
infoMap := make(map[string]string)
infoMap["Status"] = "OK"
infoMap["RuntimeMode"] = "productionMode"
infoMap["ApplicationAuthor"] = "Unmojang"
infoMap["ApplicationDescription"] = ""
infoMap["SpecificationVersion"] = "2.13.34"
infoMap["ImplementationVersion"] = "0.1.0"
infoMap["ApplicationOwner"] = app.Config.ApplicationOwner
infoBlob, err := json.Marshal(infoMap)
Check(err)
return func(c echo.Context) error {
return c.JSONBlob(http.StatusOK, infoBlob)
}
}
type authenticateRequest struct {
Username string `json:"username"`
Password string `json:"password"`
ClientToken *string `json:"clientToken"`
Agent *Agent `json:"agent"`
RequestUser bool `json:"requestUser"`
}
type authenticateResponse struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
SelectedProfile *Profile `json:"selectedProfile,omitempty"`
AvailableProfiles *[]Profile `json:"availableProfiles,omitempty"`
User *UserResponse `json:"user,omitempty"`
}
func AuthAuthenticate(app *App) func(c echo.Context) error {
invalidCredentialsBlob, err := json.Marshal(ErrorResponse{
Error: "ForbiddenOperationException",
ErrorMessage: "Invalid credentials. Invalid username or password.",
})
Check(err)
return func(c echo.Context) (err error) {
AddAuthlibInjectorHeader(app, &c)
req := new(authenticateRequest)
if err = c.Bind(req); err != nil {
return err
}
username := req.Username
doAnonymousLogin := AnonymousLoginEligible(app, username)
var user User
result := app.DB.Preload("TokenPairs").First(&user, "username = ?", username)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
if doAnonymousLogin {
if req.Password != app.Config.AnonymousLogin.Password {
return c.JSONBlob(http.StatusUnauthorized, invalidCredentialsBlob)
}
user, err = MakeAnonymousUser(app, username)
if err != nil {
return err
}
result := app.DB.Create(&user)
if result.Error != nil {
return result.Error
}
} else {
return c.JSONBlob(http.StatusUnauthorized, invalidCredentialsBlob)
}
} else {
return result.Error
}
}
var tokenPair TokenPair
accessToken, err := RandomHex(16)
if err != nil {
return err
}
if req.ClientToken == nil {
clientToken, err := RandomHex(16)
if err != nil {
return err
}
tokenPair = TokenPair{
ClientToken: clientToken,
AccessToken: accessToken,
Valid: true,
}
user.TokenPairs = append(user.TokenPairs, tokenPair)
} else {
clientToken := *req.ClientToken
clientTokenExists := false
for i := range user.TokenPairs {
if user.TokenPairs[i].ClientToken == clientToken {
clientTokenExists = true
user.TokenPairs[i].AccessToken = accessToken
user.TokenPairs[i].Valid = true
tokenPair = user.TokenPairs[i]
break
} else {
if !app.Config.DisableTokenExpiry {
user.TokenPairs[i].Valid = false
}
}
}
if !clientTokenExists {
tokenPair = TokenPair{
ClientToken: clientToken,
AccessToken: accessToken,
Valid: true,
}
user.TokenPairs = append(user.TokenPairs, tokenPair)
}
}
result = app.DB.Save(&user)
if result.Error != nil {
return result.Error
}
var selectedProfile *Profile
var availableProfiles *[]Profile
if req.Agent != nil {
id, err := UUIDToID(user.UUID)
if err != nil {
return err
}
selectedProfile = &Profile{
ID: id,
Name: user.PlayerName,
}
availableProfiles = &[]Profile{*selectedProfile}
}
var userResponse *UserResponse
if req.RequestUser {
id, err := UUIDToID(user.UUID)
if err != nil {
return err
}
userResponse = &UserResponse{
ID: id,
Properties: []UserProperty{UserProperty{
Name: "preferredLanguage",
Value: user.PreferredLanguage,
}},
}
}
res := authenticateResponse{
ClientToken: tokenPair.ClientToken,
AccessToken: tokenPair.AccessToken,
SelectedProfile: selectedProfile,
AvailableProfiles: availableProfiles,
User: userResponse,
}
return c.JSON(http.StatusOK, &res)
}
}
type UserProperty struct {
Name string `json:"name"`
Value string `json:"value"`
}
type UserResponse struct {
ID string `json:"id"`
Properties []UserProperty `json:"properties"`
}
func AuthRefresh(app *App) func(c echo.Context) error {
type refreshRequest struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
RequestUser bool `json:"requestUser"`
}
type refreshResponse struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
SelectedProfile Profile `json:"selectedProfile,omitempty"`
AvailableProfiles []Profile `json:"availableProfiles,omitempty"`
User *UserResponse `json:"user,omitempty"`
}
invalidAccessTokenBlob, err := json.Marshal(ErrorResponse{
Error: "ForbiddenOperationException",
ErrorMessage: "Invalid token.",
})
Check(err)
return func(c echo.Context) error {
AddAuthlibInjectorHeader(app, &c)
req := new(refreshRequest)
if err := c.Bind(req); err != nil {
return err
}
var tokenPair TokenPair
result := app.DB.Preload("User").First(&tokenPair, "client_token = ?", req.ClientToken)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return c.NoContent(http.StatusUnauthorized)
}
return result.Error
}
user := tokenPair.User
if req.AccessToken != tokenPair.AccessToken {
return c.JSONBlob(http.StatusUnauthorized, invalidAccessTokenBlob)
}
accessToken, err := RandomHex(16)
if err != nil {
return err
}
tokenPair.AccessToken = accessToken
tokenPair.Valid = true
result = app.DB.Save(&tokenPair)
if result.Error != nil {
return result.Error
}
id, err := UUIDToID(user.UUID)
if err != nil {
return err
}
selectedProfile := Profile{
ID: id,
Name: user.PlayerName,
}
availableProfiles := []Profile{selectedProfile}
var userResponse *UserResponse
if req.RequestUser {
id, err := UUIDToID(user.UUID)
if err != nil {
return err
}
userResponse = &UserResponse{
ID: id,
Properties: []UserProperty{{
Name: "preferredLanguage",
Value: user.PreferredLanguage,
}},
}
}
res := refreshResponse{
AccessToken: accessToken,
ClientToken: req.ClientToken,
SelectedProfile: selectedProfile,
AvailableProfiles: availableProfiles,
User: userResponse,
}
return c.JSON(http.StatusOK, &res)
}
}
func AuthValidate(app *App) func(c echo.Context) error {
type validateRequest struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
}
return func(c echo.Context) error {
AddAuthlibInjectorHeader(app, &c)
req := new(validateRequest)
if err := c.Bind(req); err != nil {
return err
}
var tokenPair TokenPair
result := app.DB.First(&tokenPair, "client_token = ?", req.ClientToken)
if result.Error != nil {
return c.NoContent(http.StatusForbidden)
}
if !tokenPair.Valid || req.AccessToken != tokenPair.AccessToken {
return c.NoContent(http.StatusForbidden)
}
return c.NoContent(http.StatusNoContent)
}
}
func AuthSignout(app *App) func(c echo.Context) error {
type signoutRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
invalidCredentialsBlob, err := json.Marshal(ErrorResponse{
Error: "ForbiddenOperationException",
ErrorMessage: "Invalid credentials. Invalid username or password.",
})
Check(err)
return func(c echo.Context) error {
AddAuthlibInjectorHeader(app, &c)
req := new(signoutRequest)
if err := c.Bind(req); err != nil {
return err
}
var user User
result := app.DB.First(&user, "username = ?", req.Username)
if result.Error != nil {
return result.Error
}
passwordHash, err := HashPassword(req.Password, user.PasswordSalt)
if err != nil {
return err
}
if !bytes.Equal(passwordHash, user.PasswordHash) {
return c.JSONBlob(http.StatusUnauthorized, invalidCredentialsBlob)
}
app.DB.Model(TokenPair{}).Where("user_uuid = ?", user.UUID).Updates(TokenPair{Valid: false})
if result.Error != nil {
return result.Error
}
return c.NoContent(http.StatusNoContent)
}
}
func AuthInvalidate(app *App) func(c echo.Context) error {
type invalidateRequest struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
}
invalidAccessTokenBlob, err := json.Marshal(ErrorResponse{
Error: "ForbiddenOperationException",
ErrorMessage: "Invalid token.",
})
Check(err)
return func(c echo.Context) error {
AddAuthlibInjectorHeader(app, &c)
req := new(invalidateRequest)
if err := c.Bind(req); err != nil {
return err
}
var tokenPair TokenPair
result := app.DB.First(&tokenPair, "client_token = ?", req.ClientToken)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return c.JSONBlob(http.StatusUnauthorized, invalidAccessTokenBlob)
}
return result.Error
}
app.DB.Table("token_pairs").Where("user_uuid = ?", tokenPair.UserUUID).Updates(map[string]interface{}{"Valid": false})
return c.NoContent(http.StatusNoContent)
}
}