Browse Source

Refactored external login.

pull/190/head
Halil İbrahim Kalkan 8 years ago
parent
commit
84a4668dfa
  1. 6
      src/AbpDesk/AbpDesk.Web.Mvc/AbpDesk.Web.Mvc.csproj
  2. 29
      src/Volo.Abp.Account.Web/Pages/Account/ExternalLogin.cshtml
  3. 138
      src/Volo.Abp.Account.Web/Pages/Account/ExternalLogin.cshtml.cs
  4. 44
      src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml
  5. 70
      src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs

6
src/AbpDesk/AbpDesk.Web.Mvc/AbpDesk.Web.Mvc.csproj

@ -51,10 +51,8 @@
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Facebook" Version="2.0.1" />
</ItemGroup>
</Project>

29
src/Volo.Abp.Account.Web/Pages/Account/ExternalLogin.cshtml

@ -1,29 +0,0 @@
@page
@model Volo.Abp.Account.Web.Pages.Account.ExternalLoginModel
@{
ViewData["Title"] = "Register";
}
<h2>@ViewData["Title"]</h2>
<h4>Associate your @Model.LoginProvider account.</h4>
<hr />
<p class="text-info">
You've successfully authenticated with <strong>@Model.LoginProvider</strong>.
Please enter an email address for this site below and click the Register button to finish
logging in.
</p>
<div class="row">
<div class="col-md-4">
<form asp-page-handler="Confirmation" asp-route-returnUrl="@Model.ReturnUrl" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Input.Email"></label>
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-default">Register</button>
</form>
</div>
</div>

138
src/Volo.Abp.Account.Web/Pages/Account/ExternalLogin.cshtml.cs

@ -1,138 +0,0 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Identity;
using Volo.Abp.Ui;
using Volo.Abp.Uow;
namespace Volo.Abp.Account.Web.Pages.Account
{
public class ExternalLoginModel : AccountModelBase
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
public ExternalLoginModel(
SignInManager<IdentityUser> signInManager,
UserManager<IdentityUser> userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
[BindProperty]
public InputModel Input { get; set; }
public string LoginProvider { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
public IActionResult OnGetAsync()
{
return RedirectToPage("./Login");
}
[UnitOfWork]
public virtual IActionResult OnPost(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
[UnitOfWork]
public virtual async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null, string returnUrlHash = "")
{
if (remoteError != null)
{
ErrorMessage = $"Error from external provider: {remoteError}";
return RedirectToPage("./Login");
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToPage("./Login");
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
return RedirectSafely(returnUrl, returnUrlHash);
}
if (result.IsLockedOut)
{
throw new UserFriendlyException("Cannot proceed because user is locked out!");
}
ReturnUrl = returnUrl;
LoginProvider = info.LoginProvider;
//User does not have an account, create an account.
var success = await CreateUserAsync(returnUrl, returnUrlHash);
if (success)
{
return RedirectSafely(returnUrl, returnUrlHash);
}
return Page();
}
[UnitOfWork]
public virtual async Task<bool> CreateUserAsync(string returnUrl = null, string returnUrlHash = null)
{
if (!ModelState.IsValid)
{
return false;
}
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
throw new ApplicationException("Error loading external login information during confirmation.");
}
var user = new IdentityUser(GuidGenerator.Create(), info.Principal.FindFirstValue(ClaimTypes.Email));
var result = await _userManager.CreateAsync(user);
//todo: needs to check identity errors?
//CheckIdentityErrors( await _userManager.CreateAsync(user));
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, false);
return true;
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
return false;
}
}
}

44
src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml

@ -26,36 +26,20 @@
</div>
</div>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
@if (Model.ExternalLogins.Any())
{
<div class="col-md-6">
<h4>Use another service to log in.</h4>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
for details on setting up this ASP.NET application to support logging in via external services.
</p>
</div>
}
else
{
<form asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn btn-default" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
<form asp-page="./Login" asp-page-handler="ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" asp-route-returnUrlHash="@Model.ReturnUrlHash" method="post">
<div>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</div>
</form>
</div>
}
</div>

70
src/Volo.Abp.Account.Web/Pages/Account/Login.cshtml.cs

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
@ -21,10 +22,12 @@ namespace Volo.Abp.Account.Web.Pages.Account
public IList<AuthenticationScheme> ExternalLogins { get; set; }
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IdentityUserManager _userManager; //TODO: We should not use domain from presentation..?
public LoginModel(SignInManager<IdentityUser> signInManager)
public LoginModel(SignInManager<IdentityUser> signInManager, IdentityUserManager userManager)
{
_signInManager = signInManager;
_userManager = userManager;
}
public async Task OnGetAsync(string returnUrl = "", string returnUrlHash = "")
@ -61,6 +64,71 @@ namespace Volo.Abp.Account.Web.Pages.Account
//TODO: Use LocalRedirect and Url.GetLocalUrl methods instead of a custom one!
return RedirectSafely(returnUrl, returnUrlHash);
}
[UnitOfWork]
public virtual IActionResult OnPostExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Page("./Login", pageHandler: "ExternalLoginCallback", values: new { returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
[UnitOfWork]
public virtual async Task<IActionResult> OnGetExternalLoginCallbackAsync(string returnUrl = null, string returnUrlHash = "", string remoteError = null)
{
if (remoteError != null)
{
return RedirectToPage("./Login");
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToPage("./Login");
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
return RedirectSafely(returnUrl, returnUrlHash);
}
if (result.IsLockedOut)
{
throw new UserFriendlyException("Cannot proceed because user is locked out!");
}
ReturnUrl = returnUrl;
//User does not have an account, create an account.
await CreateUserAsync();
return RedirectSafely(returnUrl, returnUrlHash);
}
[UnitOfWork]
protected virtual async Task CreateUserAsync()
{
ValidateModel();
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
throw new ApplicationException("Error loading external login information during confirmation.");
}
var emailAddress = info.Principal.FindFirstValue(ClaimTypes.Email);
var user = new IdentityUser(GuidGenerator.Create(), emailAddress);
CheckIdentityErrors(await _userManager.CreateAsync(user));
CheckIdentityErrors(await _userManager.SetEmailAsync(user, emailAddress));
CheckIdentityErrors(await _userManager.AddLoginAsync(user, info));
await _signInManager.SignInAsync(user, false);
}
public class PostInput
{

Loading…
Cancel
Save