-
Notifications
You must be signed in to change notification settings - Fork 18
/
auth.go
372 lines (325 loc) · 9.24 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
package main
import (
"bytes"
"encoding/json"
"errors"
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"gorm.io/gorm"
"net/http"
)
/*
Authentication server
*/
type UserProperty struct {
Name string `json:"name"`
Value string `json:"value"`
}
type UserResponse struct {
ID string `json:"id"`
Properties []UserProperty `json:"properties"`
}
var invalidCredentialsBlob []byte = Unwrap(json.Marshal(ErrorResponse{
Error: Ptr("ForbiddenOperationException"),
ErrorMessage: Ptr("Invalid credentials. Invalid username or password."),
}))
var invalidAccessTokenBlob []byte = Unwrap(json.Marshal(ErrorResponse{
Error: Ptr("ForbiddenOperationException"),
ErrorMessage: Ptr("Invalid token."),
}))
type serverInfoResponse struct {
Status string `json:"Status"`
RuntimeMode string `json:"RuntimeMode"`
ApplicationAuthor string `json:"ApplicationAuthor"`
ApplicationDescription string `json:"ApplcationDescription"`
SpecificationVersion string `json:"SpecificationVersion"`
ImplementationVersion string `json:"ImplementationVersion"`
ApplicationOwner string `json:"ApplicationOwner"`
}
// GET /
func AuthServerInfo(app *App) func(c echo.Context) error {
info := serverInfoResponse{
Status: "OK",
RuntimeMode: "productionMode",
ApplicationAuthor: "Unmojang",
ApplicationDescription: "",
SpecificationVersion: "2.13.34",
ImplementationVersion: "0.1.0",
ApplicationOwner: app.Config.ApplicationOwner,
}
infoBlob := Unwrap(json.Marshal(info))
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"`
}
// POST /authenticate
// https://wiki.vg/Legacy_Mojang_Authentication#Authenticate
func AuthAuthenticate(app *App) func(c echo.Context) error {
return func(c echo.Context) (err error) {
req := new(authenticateRequest)
if err = c.Bind(req); err != nil {
return err
}
username := req.Username
doTransientLogin := app.TransientLoginEligible(username)
var user User
result := app.DB.Preload("Clients").First(&user, "username = ?", username)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
if doTransientLogin {
user, err = MakeTransientUser(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
}
}
if doTransientLogin {
if req.Password != app.Config.TransientUsers.Password {
return c.JSONBlob(http.StatusUnauthorized, invalidCredentialsBlob)
}
} else {
passwordHash, err := HashPassword(req.Password, user.PasswordSalt)
if err != nil {
return err
}
if !bytes.Equal(passwordHash, user.PasswordHash) {
return c.JSONBlob(http.StatusUnauthorized, invalidCredentialsBlob)
}
}
var client Client
if req.ClientToken == nil {
clientToken, err := RandomHex(16)
if err != nil {
return err
}
client = Client{
UUID: uuid.New().String(),
ClientToken: clientToken,
Version: 0,
}
user.Clients = append(user.Clients, client)
} else {
clientToken := *req.ClientToken
clientExists := false
for i := range user.Clients {
if user.Clients[i].ClientToken == clientToken {
clientExists = true
user.Clients[i].Version += 1
client = user.Clients[i]
break
} else {
if !app.Config.AllowMultipleAccessTokens {
user.Clients[i].Version += 1
}
}
}
if !clientExists {
client = Client{
UUID: uuid.New().String(),
ClientToken: clientToken,
Version: 0,
}
user.Clients = append(user.Clients, client)
}
}
// Save changes to user.Clients
result = app.DB.Session(&gorm.Session{FullSaveAssociations: true}).Save(&user)
if result.Error != nil {
return result.Error
}
id, err := UUIDToID(user.UUID)
if err != nil {
return err
}
var selectedProfile *Profile
var availableProfiles *[]Profile
if req.Agent != nil {
selectedProfile = &Profile{
ID: id,
Name: user.PlayerName,
}
availableProfiles = &[]Profile{*selectedProfile}
}
var userResponse *UserResponse
if req.RequestUser {
userResponse = &UserResponse{
ID: id,
Properties: []UserProperty{{
Name: "preferredLanguage",
Value: user.PreferredLanguage,
}},
}
}
accessToken, err := app.MakeAccessToken(client)
if err != nil {
return err
}
res := authenticateResponse{
ClientToken: client.ClientToken,
AccessToken: accessToken,
SelectedProfile: selectedProfile,
AvailableProfiles: availableProfiles,
User: userResponse,
}
return c.JSON(http.StatusOK, &res)
}
}
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"`
}
// POST /refresh
// https://wiki.vg/Legacy_Mojang_Authentication#Refresh
func AuthRefresh(app *App) func(c echo.Context) error {
return func(c echo.Context) error {
req := new(refreshRequest)
if err := c.Bind(req); err != nil {
return err
}
client := app.GetClient(req.AccessToken, StalePolicyAllow)
if client == nil || client.ClientToken != req.ClientToken {
return c.JSONBlob(http.StatusUnauthorized, invalidAccessTokenBlob)
}
user := client.User
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 {
userResponse = &UserResponse{
ID: id,
Properties: []UserProperty{{
Name: "preferredLanguage",
Value: user.PreferredLanguage,
}},
}
}
client.Version += 1
accessToken, err := app.MakeAccessToken(*client)
if err != nil {
return err
}
result := app.DB.Save(client)
if result.Error != nil {
return result.Error
}
res := refreshResponse{
AccessToken: accessToken,
ClientToken: client.ClientToken,
SelectedProfile: selectedProfile,
AvailableProfiles: availableProfiles,
User: userResponse,
}
return c.JSON(http.StatusOK, &res)
}
}
type validateRequest struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
}
// POST /validate
// https://wiki.vg/Legacy_Mojang_Authentication#Validate
func AuthValidate(app *App) func(c echo.Context) error {
return func(c echo.Context) error {
req := new(validateRequest)
if err := c.Bind(req); err != nil {
return err
}
client := app.GetClient(req.AccessToken, StalePolicyDeny)
if client == nil || client.ClientToken != req.ClientToken {
return c.NoContent(http.StatusForbidden)
}
return c.NoContent(http.StatusNoContent)
}
}
type signoutRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
// POST /signout
// https://wiki.vg/Legacy_Mojang_Authentication#Signout
func AuthSignout(app *App) func(c echo.Context) error {
return func(c echo.Context) error {
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)
}
err = app.InvalidateUser(app.DB, &user)
if err != nil {
return err
}
return c.NoContent(http.StatusNoContent)
}
}
type invalidateRequest struct {
AccessToken string `json:"accessToken"`
ClientToken string `json:"clientToken"`
}
// POST /invalidate
// https://wiki.vg/Legacy_Mojang_Authentication#Invalidate
func AuthInvalidate(app *App) func(c echo.Context) error {
return func(c echo.Context) error {
req := new(invalidateRequest)
if err := c.Bind(req); err != nil {
return err
}
client := app.GetClient(req.AccessToken, StalePolicyAllow)
if client == nil || client.ClientToken != req.ClientToken {
return c.JSONBlob(http.StatusUnauthorized, invalidAccessTokenBlob)
}
err := app.InvalidateUser(app.DB, &client.User)
if err != nil {
return err
}
return c.NoContent(http.StatusNoContent)
}
}