/
AccountsController.cs
466 lines (372 loc) · 14.5 KB
/
AccountsController.cs
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
using Arise.Server.Web.Authentication;
using Arise.Server.Web.Cryptography;
using Arise.Server.Web.Mail;
using Arise.Server.Web.Models.Api.Accounts;
namespace Arise.Server.Web.Controllers.Api;
public sealed class AccountsController : ApiController
{
// TODO: Add rate limiting throughout.
[BindProperty]
[FromServices]
public required IClock Clock { get; init; }
[BindProperty]
[FromServices]
public required IDocumentStore Store { get; init; }
[BindProperty]
[FromServices]
public required MailSender Sender { get; init; }
[BindProperty]
[FromServices]
public required IOptionsSnapshot<WebOptions> Options { get; init; }
[AllowAnonymous]
[HttpPost]
public async ValueTask<IActionResult> CreateAsync(AccountsCreateRequest body)
{
if (User.Identity!.IsAuthenticated)
return StatusCode(StatusCodes.Status403Forbidden);
var normalized = body.Address.Normalize().ToUpperInvariant();
var token = TokenGenerator.GenerateToken();
var options = Options.Value;
var now = Clock.GetCurrentInstant();
var end = now + options.AccountVerificationTime;
var strategy = PasswordStrategy.GetLatestStrategy();
var salt = strategy.GenerateSalt();
var key = TokenGenerator.GenerateToken();
var account = new AccountDocument
{
Email = new()
{
Address = normalized,
Verification = new()
{
Value = token,
Period = new(now, end),
},
},
Password = new()
{
Kind = strategy.Kind,
Salt = salt,
Hash = strategy.CalculateHash(body.Password, salt),
},
Access = AccountAccess.User,
GameKey = new()
{
Value = key,
Period = new(now, now + options.AccountKeyTime),
},
};
await using (var session = Store.LightweightSession())
{
session.Insert(account);
try
{
await session.SaveChangesAsync(CancellationToken);
}
catch (DocumentAlreadyExistsException)
{
// Email address already taken.
return UnprocessableEntity();
}
}
await Sender.SendAsync(
normalized,
"Email Address Verification",
$"""
Welcome to TERA Arise.
To verify your email address, use this token in the launcher: {token}
The token will expire on: {end.InUtc().Date.ToString(null, CultureInfo.InvariantCulture)}
""",
CancellationToken);
return Ok(new AccountsCreateResponse
{
GameKey = key,
});
}
[HttpPatch]
public async ValueTask<IActionResult> SendAsync(AccountDocument account)
{
var email = account.Email;
if (email.Verification == null)
return BadRequest();
var token = TokenGenerator.GenerateToken();
var now = Clock.GetCurrentInstant();
var end = now + Options.Value.AccountVerificationTime;
email.Verification = new()
{
Value = token,
Period = new(now, end),
};
if (!await UpdateAccountAsync(account))
return Conflict();
await Sender.SendAsync(
email.Address,
"Email Address Verification",
$"""
Welcome to TERA Arise.
To verify your email address, use this token in the launcher: {token}
The token will expire on: {end.InUtc().Date.ToString(null, CultureInfo.InvariantCulture)}
""",
CancellationToken);
return NoContent();
}
[HttpPatch]
public async ValueTask<IActionResult> VerifyAsync(AccountDocument account, AccountsVerifyRequest body)
{
var now = Clock.GetCurrentInstant();
bool MatchToken([NotNullWhen(true)] AccountToken? token)
{
return (token?.Period.Contains(now) ?? false) && body.Token == token.Value;
}
var email = account.Email;
var change = account.ChangingEmail;
var deletion = account.Deletion;
if (MatchToken(change?.Verification))
{
account.Email = new()
{
Address = change.Address,
Verification = null,
};
account.ChangingEmail = null;
}
else if (MatchToken(email.Verification))
email.Verification = null;
else if (MatchToken(deletion?.Verification))
deletion.Verification = null;
else
return Gone();
bool saved;
try
{
saved = await UpdateAccountAsync(account);
}
catch (DocumentAlreadyExistsException)
{
// This indicates that the unique constraint on AccountDocument.Email.Address was violated; that is, the
// email address the user is changing to is already in use by another account.
return UnprocessableEntity();
}
return saved ? NoContent() : Conflict();
}
[HttpPatch]
public async ValueTask<IActionResult> UpdateAsync(AccountDocument account, AccountsUpdateRequest body)
{
var email = account.Email;
if (body.Address is string address)
{
// Unverified accounts cannot change their email address.
if (email.Verification != null)
return BadRequest();
var token = TokenGenerator.GenerateToken();
var now = Clock.GetCurrentInstant();
var end = now + Options.Value.AccountVerificationTime;
account.ChangingEmail = new()
{
Address = address.Normalize().ToUpperInvariant(),
Verification = new()
{
Value = token,
Period = new(now, end),
},
};
if (!await UpdateAccountAsync(account))
return Conflict();
await Sender.SendAsync(
email.Address,
"Email Address Change Verification",
$"""
An email address change was recently requested for your TERA Arise account.
The new email address is: {address}
To confirm the change, use this token in the launcher: {token}
The token will expire on: {end.InUtc().Date.ToString(null, CultureInfo.InvariantCulture)}
If you did not initiate this request, please change your password immediately.
""",
CancellationToken);
}
if (body.Password is string password)
{
var strategy = PasswordStrategy.GetLatestStrategy();
var salt = strategy.GenerateSalt();
account.Password = new()
{
Kind = strategy.Kind,
Salt = salt,
Hash = strategy.CalculateHash(password, salt),
};
if (!await UpdateAccountAsync(account))
return Conflict();
await Sender.SendAsync(
email.Address,
"Password Change",
$"""
A password change was recently performed for your TERA Arise account.
If you did not perform this change, please change your password immediately.
""",
CancellationToken);
}
return NoContent();
}
[AllowAnonymous]
[HttpPatch]
public async ValueTask<IActionResult> RecoverAsync(AccountsRecoverRequest body)
{
if (User.Identity!.IsAuthenticated)
return StatusCode(StatusCodes.Status403Forbidden);
var normalized = body.Address.Normalize().ToUpperInvariant();
var account = default(AccountDocument);
await using (var session = Store.QuerySession())
account = await session
.Query<AccountDocument>()
.SingleOrDefaultAsync(account => account.Email.Address == normalized, CancellationToken);
if (account != null)
{
var strategy = PasswordStrategy.GetLatestStrategy();
var salt = strategy.GenerateSalt();
var password = PasswordStrategy.GeneratePassword();
var now = Clock.GetCurrentInstant();
var end = now + Options.Value.AccountRecoveryTime;
account.Recovery = new()
{
Password = new()
{
Kind = strategy.Kind,
Salt = salt,
Hash = strategy.CalculateHash(password, salt),
},
Period = new(now, end),
};
if (!await UpdateAccountAsync(account))
return Conflict();
// TODO: This should ideally be done in a separate thread to prevent timing-based user enumeration.
//
// https://cheatsheetseries.owasp.org/cheatsheets/Forgot_Password_Cheat_Sheet.html#forgot-password-request
await Sender.SendAsync(
normalized,
"Password Recovery",
$"""
Password recovery was recently requested for your TERA Arise account.
A temporary password has been generated for you: {password}
The temporary password will expire on: {end.InUtc().Date.ToString(null, CultureInfo.InvariantCulture)}
If you log in with the above password, it will replace your current password.
If you log in with your normal password, the temporary password will be removed from your account.
If you did not initiate this request, you can safely ignore this message.
""",
CancellationToken);
}
// https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#password-recovery
return NoContent();
}
[HttpDelete]
public async ValueTask<IActionResult> DeleteAsync(AccountDocument account)
{
if (account.Deletion != null)
return BadRequest();
var token = TokenGenerator.GenerateToken();
var options = Options.Value;
var now = Clock.GetCurrentInstant();
var end = now + options.AccountVerificationTime;
account.Deletion = new()
{
Period = new(now, now + options.AccountDeletionTime),
Verification = new()
{
Value = token,
Period = new(now, end),
},
};
if (!await UpdateAccountAsync(account))
return Conflict();
await Sender.SendAsync(
account.Email.Address,
"Account Deletion Verification",
$"""
Deletion of your TERA Arise account was recently requested.
To confirm account deletion, use this token in the launcher: {token}
The token will expire on: {end.InUtc().Date.ToString(null, CultureInfo.InvariantCulture)}
If you did not initiate this request, please change your password immediately.
""",
CancellationToken);
return NoContent();
}
[HttpPatch]
public async ValueTask<IActionResult> RestoreAsync(AccountDocument account)
{
if (account.Deletion is null or { Verification: not null })
return BadRequest();
account.Deletion = null;
return await UpdateAccountAsync(account) ? NoContent() : Conflict();
}
[HttpPatch]
public async ValueTask<IActionResult> AuthenticateAsync(AccountClaimsPrincipal principal)
{
var account = principal.Document;
var now = Clock.GetCurrentInstant();
// Do some housekeeping of account state while we are here...
var verifying = account.Email.Verification != null;
var changing = false;
if (account.ChangingEmail is AccountEmailChange change)
{
if (change.Verification.Period.Contains(now))
changing = true;
else
account.ChangingEmail = null; // Clear expired email address change request.
}
if (principal.IsRecovered)
account.Password = account.Recovery!.Password;
account.Recovery = null; // Clear used/expired recovery password.
var deleting = false;
if (account.Deletion is AccountDeletion deletion)
{
if (deletion.Verification is AccountToken verification && !verification.Period.Contains(now))
account.Deletion = null; // Clear expired deletion request.
else if (deletion.Verification == null)
deleting = true;
}
var reason = default(string);
if (account.Ban is AccountBan ban)
{
if (ban.Period.Contains(now))
reason = ban.Reason;
else
account.Ban = null; // Clear expired ban.
}
// Accounts that are banned or in the process of being deleted cannot access the world service. We also prevent
// unverified accounts from accessing it since the user could have signed up with a wrong email address and
// might otherwise not notice until they have made significant progress in the game.
var key = !(verifying || deleting) && reason == null ? TokenGenerator.GenerateToken() : null;
// Save new key or clear the previous one (for ban or deletion).
account.GameKey = key == null ? null : new()
{
Value = key,
Period = new(now, now + Options.Value.AccountKeyTime),
};
return await UpdateAccountAsync(account)
? Ok(new AccountsAuthenticateResponse
{
IsVerifying = verifying,
IsChangingEmail = changing,
IsRecovered = principal.IsRecovered,
IsDeleting = deleting,
BanReason = reason,
GameKey = key,
})
: Conflict();
}
private async ValueTask<bool> UpdateAccountAsync(AccountDocument account)
{
await using var session = Store.LightweightSession();
// TODO: https://github.com/JasperFx/marten/issues/2439
session.Store(account, account.Version);
try
{
await session.SaveChangesAsync(CancellationToken);
}
catch (ConcurrencyException e)
{
Console.WriteLine(e);
return false;
}
return true;
}
}