/
AccountController.cs
322 lines (264 loc) · 9.76 KB
/
AccountController.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
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Squidex.Config;
using Squidex.Domain.Users;
using Squidex.Infrastructure;
using Squidex.Infrastructure.Security;
using Squidex.Infrastructure.Translations;
using Squidex.Shared.Identity;
using Squidex.Shared.Users;
using Squidex.Web;
namespace Squidex.Areas.IdentityServer.Controllers.Account;
[AutoValidateAntiforgeryToken]
public sealed class AccountController : IdentityServerController
{
private readonly IUserService userService;
private readonly MyIdentityOptions identityOptions;
public AccountController(
IUserService userService,
IOptions<MyIdentityOptions> identityOptions)
{
this.identityOptions = identityOptions.Value;
this.userService = userService;
}
[HttpGet]
[Route("account/error/")]
public IActionResult LoginError()
{
throw new InvalidOperationException();
}
[HttpGet]
[Route("account/forbidden/")]
public IActionResult Forbidden()
{
throw new DomainForbiddenException(T.Get("users.userLocked"));
}
[HttpGet]
[Route("account/lockedout/")]
public IActionResult LockedOut()
{
return View();
}
[HttpGet]
[Route("account/accessdenied/")]
public IActionResult AccessDenied()
{
return View();
}
[HttpGet]
[Route("account/logout-completed/")]
public IActionResult LogoutCompleted()
{
return View();
}
[HttpGet]
[Route("account/consent/")]
public IActionResult Consent(string? returnUrl = null)
{
return View(new ConsentVM { PrivacyUrl = identityOptions.PrivacyUrl, ReturnUrl = returnUrl });
}
[HttpPost]
[Route("account/consent/")]
public async Task<IActionResult> Consent(ConsentModel model, string? returnUrl = null)
{
// We ask new users to agree to the cookie and privacy agreements and show and error if they do not agree.
if (!model.ConsentToCookies)
{
ModelState.AddModelError(nameof(model.ConsentToCookies), T.Get("users.consent.needed"));
}
if (!model.ConsentToPersonalInformation)
{
ModelState.AddModelError(nameof(model.ConsentToPersonalInformation), T.Get("users.consent.needed"));
}
if (!ModelState.IsValid)
{
var vm = new ConsentVM { PrivacyUrl = identityOptions.PrivacyUrl, ReturnUrl = returnUrl };
return View(vm);
}
var user = await userService.GetAsync(User, HttpContext.RequestAborted);
// There is almost no case where this could have happened.
if (user == null)
{
throw new DomainException(T.Get("users.userNotFound"));
}
var update = new UserValues
{
Consent = true,
ConsentForEmails = model.ConsentToAutomatedEmails
};
await userService.UpdateAsync(user.Id, update, ct: HttpContext.RequestAborted);
return RedirectToReturnUrl(returnUrl);
}
[HttpGet]
[Route("account/logout/")]
public async Task<IActionResult> Logout(string logoutId)
{
await SignInManager.SignOutAsync();
return Redirect("~/../");
}
[HttpGet]
[Route("account/logout-redirect/")]
public async Task<IActionResult> LogoutRedirect()
{
await SignInManager.SignOutAsync();
return RedirectToAction(nameof(LogoutCompleted));
}
[HttpGet]
[Route("account/signup/")]
public Task<IActionResult> Signup(string? returnUrl = null)
{
return LoginViewAsync(returnUrl, false, false);
}
[HttpGet]
[Route("account/login/")]
[ClearCookies]
public Task<IActionResult> Login(string? returnUrl = null)
{
return LoginViewAsync(returnUrl, true, false);
}
[HttpPost]
[Route("account/login/")]
public async Task<IActionResult> Login(LoginModel model, string? returnUrl = null)
{
if (!ModelState.IsValid)
{
return await LoginViewAsync(returnUrl, true, true);
}
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, true, true);
if (!result.Succeeded && result.IsLockedOut)
{
return View(nameof(LockedOut));
}
else if (!result.Succeeded)
{
return await LoginViewAsync(returnUrl, true, true);
}
else
{
return RedirectToReturnUrl(returnUrl);
}
}
private async Task<IActionResult> LoginViewAsync(string? returnUrl, bool isLogin, bool isFailed)
{
// If password authentication is enabled we always show the page.
var allowPasswordAuth = identityOptions.AllowPasswordAuth;
var externalProviders = await SignInManager.GetExternalProvidersAsync();
// If there is only one external authentication provider, we can redirect just directly.
if (externalProviders.Count == 1 && !allowPasswordAuth)
{
var provider = externalProviders[0].AuthenticationScheme;
var challengeRedirectUrl = Url.Action(nameof(ExternalCallback));
var challengeProperties = SignInManager.ConfigureExternalAuthenticationProperties(provider, challengeRedirectUrl);
// Redirect to the external authentication provider.
return Challenge(challengeProperties, provider);
}
var vm = new LoginVM
{
ExternalProviders = externalProviders,
IsFailed = isFailed,
IsLogin = isLogin,
HasPasswordAuth = allowPasswordAuth,
ReturnUrl = returnUrl
};
return View(nameof(Login), vm);
}
[HttpPost]
[Route("account/external/")]
public IActionResult External(string provider, string? returnUrl = null)
{
var challengeRedirectUrl = Url.Action(nameof(ExternalCallback), new { returnUrl });
var challengeProperties = SignInManager.ConfigureExternalAuthenticationProperties(provider, challengeRedirectUrl);
return Challenge(challengeProperties, provider);
}
[HttpGet]
[Route("account/external-callback/")]
public async Task<IActionResult> ExternalCallback(string? returnUrl = null)
{
var login = await SignInManager.GetExternalLoginInfoWithDisplayNameAsync();
if (login == null)
{
return RedirectToAction(nameof(Login));
}
var result = await SignInManager.ExternalLoginSignInAsync(login.LoginProvider, login.ProviderKey, true);
if (!result.Succeeded && result.IsLockedOut)
{
return View(nameof(LockedOut));
}
var isLoggedIn = result.Succeeded;
var isLocked = false;
IUser? user = null;
if (isLoggedIn)
{
user = await userService.FindByLoginAsync(login.LoginProvider, login.ProviderKey, HttpContext.RequestAborted);
}
else
{
var email = login.Principal.GetEmail();
if (string.IsNullOrWhiteSpace(email))
{
throw new DomainException(T.Get("users.noEmailAddress"));
}
user = await userService.FindByEmailAsync(email!, HttpContext.RequestAborted);
// User might not have a login or password if the user got invited.
if (user != null && await HasLoginAsync(user))
{
// If we have a login, we reject this user, otherwise you can login to an account you do not own.
user = null;
}
if (user == null)
{
var values = new UserValues
{
CustomClaims = login.Principal.Claims.GetSquidexClaims().ToList()
};
var locked = identityOptions.LockAutomatically;
// Try to create a user. If the user exists an exception message is shown to the user.
user = await userService.CreateAsync(email!, values, locked, HttpContext.RequestAborted);
}
if (user != null)
{
await userService.AddLoginAsync(user.Id, login, HttpContext.RequestAborted);
// Login might fail if the user is locked out.
(isLoggedIn, isLocked) = await LoginAsync(login);
}
}
if (isLocked)
{
return View(nameof(LockedOut));
}
else if (!isLoggedIn)
{
return RedirectToAction(nameof(Login));
}
else if (user != null && !user.Claims.HasConsent() && !identityOptions.NoConsent)
{
// This should actually never happen, because user should not be null, when logged in.
return RedirectToAction(nameof(Consent), new { returnUrl });
}
else
{
return RedirectToReturnUrl(returnUrl);
}
}
private async Task<bool> HasLoginAsync(IUser user)
{
if (await userService.HasPasswordAsync(user, HttpContext.RequestAborted))
{
return true;
}
var logins = await userService.GetLoginsAsync(user, HttpContext.RequestAborted);
return logins.Count > 0;
}
private async Task<(bool Success, bool Locked)> LoginAsync(UserLoginInfo externalLogin)
{
var result = await SignInManager.ExternalLoginSignInAsync(externalLogin.LoginProvider, externalLogin.ProviderKey, true);
return (result.Succeeded, result.IsLockedOut);
}
}