hoping that fixes the tzo factor option

... It needs unitary testing
This commit is contained in:
2019-11-14 14:09:06 +00:00
parent 343c613622
commit 28067d12b2
8 changed files with 77 additions and 27 deletions

View File

@ -14,9 +14,6 @@ namespace Yavsc.ViewModels.Account
public string ReturnUrl { get; set; } public string ReturnUrl { get; set; }
[Display(Name = "Se souvenir de ce navigateur?")] [Display(Name = "Se souvenir de ce navigateur?")]
public bool RememberBrowser { get; set; }
[Display(Name = "Se souvenir de moi?")]
public bool RememberMe { get; set; } public bool RememberMe { get; set; }
} }
} }

View File

@ -26,10 +26,10 @@ namespace Yavsc.Controllers
public class AccountController : Controller public class AccountController : Controller
{ {
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
const string nextPageTokenKey = "nextPageTokenKey"; const string nextPageTokenKey = "nextPageTokenKey";
const int defaultLen = 10; const int defaultLen = 10;
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender; private readonly IEmailSender _emailSender;
// private readonly ISmsSender _smsSender; // private readonly ISmsSender _smsSender;
private readonly ILogger _logger; private readonly ILogger _logger;
@ -323,6 +323,19 @@ namespace Yavsc.Controllers
_siteSettings.Audience)); _siteSettings.Audience));
return res; return res;
} }
private async Task<EmailSentViewModel> SendEMailFactorAsync(ApplicationUser user, string provider)
{
var code = await _userManager.GenerateTwoFactorTokenAsync(user, provider);
var callbackUrl = Url.Action("VerifyCode", "Account",
new { userId = user.Id, code, provider }, protocol: "https", host: Startup.Authority);
var res = await _emailSender.SendEmailAsync(user.UserName, user.Email,
this._localizer["AccountEmailFactorTitle"],
string.Format(this._localizer["AccountEmailFactorBody"],
_siteSettings.Title, callbackUrl, _siteSettings.Slogan,
_siteSettings.Audience, code));
return res;
}
// //
// POST: /Account/LogOff // POST: /Account/LogOff
[HttpPost(Constants.LogoutPath)] [HttpPost(Constants.LogoutPath)]
@ -366,7 +379,7 @@ namespace Yavsc.Controllers
} }
if (result.RequiresTwoFactor) if (result.RequiresTwoFactor)
{ {
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe= true });
} }
if (result.IsLockedOut) if (result.IsLockedOut)
{ {
@ -465,13 +478,41 @@ namespace Yavsc.Controllers
IdentityResult result=null; IdentityResult result=null;
try { try {
result = await _userManager.ConfirmEmailAsync(user, code); result = await _userManager.ConfirmEmailAsync(user, code);
_dbContext.SaveChanges(userId);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex.StackTrace); _logger.LogError(ex.StackTrace);
_logger.LogError(ex.Message); _logger.LogError(ex.Message);
} }
return View(result.Succeeded ? "ConfirmEmail" : "Error"); return View(result.Succeeded ? "EmailConfirmed" : "Error");
}
// GET: /Account/ConfirmTwoFactorToken
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmTwoFactorToken(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
bool result=false;
try {
result = await _userManager.VerifyTwoFactorTokenAsync(user, Constants.DefaultFactor, code);
_dbContext.SaveChanges(userId);
}
catch (Exception ex)
{
_logger.LogError(ex.StackTrace);
_logger.LogError(ex.Message);
}
return View(result ? "EmailConfirmed" : "Error");
} }
// //
@ -607,7 +648,7 @@ namespace Yavsc.Controllers
// //
// GET: /Account/SendCode // GET: /Account/SendCode
[HttpGet, AllowAnonymous] [HttpGet, AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = true)
{ {
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null) if (user == null)
@ -615,11 +656,8 @@ namespace Yavsc.Controllers
return View("Error", new Exception("No Two factor authentication user")); return View("Error", new Exception("No Two factor authentication user"));
} }
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
} }
@ -645,7 +683,7 @@ namespace Yavsc.Controllers
{ {
return View("Error", new Exception("No mobile app service was activated")); return View("Error", new Exception("No mobile app service was activated"));
} }
else // if (model.SelectedProvider == Constants.EMailFactor || model.SelectedProvider == "Default" ) else
if (model.SelectedProvider == Constants.SMSFactor) if (model.SelectedProvider == Constants.SMSFactor)
{ {
return View("Error", new Exception("No SMS service was activated")); return View("Error", new Exception("No SMS service was activated"));
@ -653,7 +691,7 @@ namespace Yavsc.Controllers
} }
else // if (model.SelectedProvider == Constants.EMailFactor || model.SelectedProvider == "Default" ) else // if (model.SelectedProvider == Constants.EMailFactor || model.SelectedProvider == "Default" )
{ {
var sent = await this.SendEMailForConfirmAsync(user); var sent = await this.SendEMailFactorAsync(user, model.SelectedProvider);
} }
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
} }
@ -662,7 +700,7 @@ namespace Yavsc.Controllers
// GET: /Account/VerifyCode // GET: /Account/VerifyCode
[HttpGet] [HttpGet]
[AllowAnonymous] [AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) public async Task<IActionResult> VerifyCode(string code, string provider, bool rememberMe=true, string returnUrl = null)
{ {
// Require that the user has already logged in via username/password or external login // Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
@ -670,7 +708,8 @@ namespace Yavsc.Controllers
{ {
return View("Error", new Exception("user is null")); return View("Error", new Exception("user is null"));
} }
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); // it may be a GET response from some email url, or the web response to second fqctor requirement
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe, Code = code });
} }
// //
@ -690,12 +729,14 @@ namespace Yavsc.Controllers
// will be locked out for a specified amount of time. // will be locked out for a specified amount of time.
_logger.LogWarning("Signin with code: {0} {1}", model.Provider, model.Code); _logger.LogWarning("Signin with code: {0} {1}", model.Provider, model.Code);
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberMe);
if (result.Succeeded) if (result.Succeeded)
{ {
ViewData["StatusMessage"] = "Your code was verified"; ViewData["StatusMessage"] = "Your code was verified";
_logger.LogInformation($"Signed in. returning to {model.ReturnUrl}"); _logger.LogInformation($"Signed in. returning to {model.ReturnUrl}");
if (model.ReturnUrl!=null)
return Redirect(model.ReturnUrl); return Redirect(model.ReturnUrl);
else RedirectToAction("Index","Home");
} }
if (result.IsLockedOut) if (result.IsLockedOut)
{ {

View File

@ -47,7 +47,8 @@ namespace Yavsc.TagHelpers
string actual; string actual;
var settings = CommonMarkSettings.Default.Clone(); var settings = CommonMarkSettings.Default.Clone();
settings.OutputFormat = OutputFormat.Html; settings.OutputFormat = OutputFormat.Html;
// settings.PrologueLineHandler = null; settings.AdditionalFeatures |= CommonMarkAdditionalFeatures.StrikethroughTilde;
Block document; Block document;
// Act // Act

View File

@ -463,10 +463,22 @@
<data name="ConfirmPassword"><value>Confirmation du mot de passe</value></data> <data name="ConfirmPassword"><value>Confirmation du mot de passe</value></data>
<data name="ErrorSendingEmailForConfirm"><value>L'envoi de de courrier pour confirmation de l'adresse e-mail a échoué.</value></data> <data name="ErrorSendingEmailForConfirm"><value>L'envoi de de courrier pour confirmation de l'adresse e-mail a échoué.</value></data>
<data name="EmailSentForConfirm"><value>Un courrier a été envoyé pour confirmation de l'adresse e-mail .</value></data> <data name="EmailSentForConfirm"><value>Un courrier a été envoyé pour confirmation de l'adresse e-mail .</value></data>
<data name="AccountEmailFactorTitle"><value>Le second facteur de votre identification</value></data>
<data name="AccountEmailFactorBody"><value>Votre compte est endurci d'une requisition d'un second facteur d'identification.
Une nouvelle connection depuis un navigateur web nécéssite votre authorisation.
Vous pouvez l'accorder en suivant le lien suivant : &lt;{1}&gt;.
Votre code dáctivation est : {4}
Vour pourrez cochez la case "Se souvenir de ce navigateur" pour conserver cette authorisation pour ce navigateur.
{0} - {2} &lt;{3}&gt;</value></data>
<data name="ConfirmYourAccountTitle"><value>S'il vous plait, confirmez votre addresse e-mail</value></data> <data name="ConfirmYourAccountTitle"><value>S'il vous plait, confirmez votre addresse e-mail</value></data>
<data name="ConfirmYourAccountBody"><value>Vous avez créé avec succès votre compte {0}, <data name="ConfirmYourAccountBody"><value>Vous avez créé avec succès votre compte {0},
mais votre adresse e-mail reste à confirmer. mais votre adresse e-mail reste à confirmer.
Pour ce faire, suivez le lien suivant : &lt;{1}&gt;.
Pour ce faire, veuillez, s'il vous plait, suivre le lien suivant
dans votre navigateur favori : &lt;{1}&gt;.
-- --
{0} - {2} &lt;{3}&gt;</value></data> {0} - {2} &lt;{3}&gt;</value></data>

View File

@ -65,31 +65,30 @@ namespace Yavsc
IdentityAppOptions = option; IdentityAppOptions = option;
option.User.AllowedUserNameCharacters += " "; option.User.AllowedUserNameCharacters += " ";
option.User.RequireUniqueEmail = true; option.User.RequireUniqueEmail = true;
// option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookie.LoginPath = "/signin"; option.Cookies.ApplicationCookie.LoginPath = "/signin";
// option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
// option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = ProtectionProvider;
// option.Cookies.ApplicationCookie.DataProtectionProvider = ProtectionProvider;
// option.Cookies.ExternalCookie.DataProtectionProvider = ProtectionProvider;
// option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; // option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
/* /*
option.Cookies.ApplicationCookie.DataProtectionProvider = protector;
option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1)); option.Cookies.ApplicationCookie.LoginPath = new PathString(Constants.LoginPath.Substring(1));
option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1)); option.Cookies.ApplicationCookie.AccessDeniedPath = new PathString(Constants.AccessDeniedPath.Substring(1));
option.Cookies.ApplicationCookie.AutomaticAuthenticate = true; option.Cookies.ApplicationCookie.AutomaticAuthenticate = true;
option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookie.AuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme; option.Cookies.ApplicationCookieAuthenticationScheme = Constants.ApplicationAuthenticationSheme;
option.Cookies.TwoFactorRememberMeCookie.ExpireTimeSpan = TimeSpan.FromDays(30);
option.Cookies.TwoFactorRememberMeCookie.DataProtectionProvider = protector;
option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.ExternalCookieAuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.AutomaticAuthenticate = true; option.Cookies.ExternalCookie.AutomaticAuthenticate = true;
option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme; option.Cookies.ExternalCookie.AuthenticationScheme = Constants.ExternalAuthenticationSheme;
option.Cookies.ExternalCookie.DataProtectionProvider = protector;
*/ */
} }
).AddEntityFrameworkStores<ApplicationDbContext>() ).AddEntityFrameworkStores<ApplicationDbContext>()
.AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.DefaultFactor) .AddTokenProvider<EmailTokenProvider<ApplicationUser>>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor) // .AddTokenProvider<UserTokenProvider>(Constants.DefaultFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor) // .AddTokenProvider<UserTokenProvider>(Constants.SMSFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.EMailFactor) .AddTokenProvider<UserTokenProvider>(Constants.EMailFactor)
// .AddTokenProvider<UserTokenProvider>(Constants.AppFactor) // .AddTokenProvider<UserTokenProvider>(Constants.AppFactor)
// .AddDefaultTokenProviders() //
; ;
} }
private void ConfigureOAuthApp(IApplicationBuilder app, private void ConfigureOAuthApp(IApplicationBuilder app,

View File

@ -22,8 +22,8 @@
<div class="form-group"> <div class="form-group">
<div class="col-md-offset-2 col-md-10"> <div class="col-md-offset-2 col-md-10">
<div class="checkbox"> <div class="checkbox">
<input asp-for="RememberBrowser" /> <input asp-for="RememberMe" />
<label asp-for="RememberBrowser"></label> <label asp-for="RememberMe"></label>
</div> </div>
</div> </div>
</div> </div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB