From 9dbd025ba1418a2f7b7aebcd28ff40f13d64e75d Mon Sep 17 00:00:00 2001 From: Enmanuel Toribio Date: Sat, 25 Jul 2020 18:33:27 -0400 Subject: [PATCH] Added claim for userid to user claims --- Web/Controllers/AccountController.cs | 3 +- Web/Controllers/BaseController.cs | 2 +- Web/Framework/ApplicationUser.cs | 18 +---- .../Configurations/AuthConfiguration.cs | 57 ++++++++++++++++ Web/Framework/ViewPageBase.cs | 2 +- Web/appsettings.Development.json | 68 +++++++++++-------- 6 files changed, 103 insertions(+), 47 deletions(-) diff --git a/Web/Controllers/AccountController.cs b/Web/Controllers/AccountController.cs index 0bf1ea5..d77f3f7 100644 --- a/Web/Controllers/AccountController.cs +++ b/Web/Controllers/AccountController.cs @@ -49,7 +49,7 @@ public async Task Login([FromForm] string provider, [FromForm] st return BadRequest(); } - return Challenge(new AuthenticationProperties { RedirectUri = Url.Action("OnPostConfirmation", "Account", new { returnUrl, provider } )}, provider); + return Challenge(new AuthenticationProperties { RedirectUri = returnUrl }, provider); // Url.Action("OnPostConfirmation", "Account", new { returnUrl, provider } )}, provider); } [HttpGet] @@ -67,6 +67,7 @@ public IActionResult LogOut() public async Task OnPostConfirmation(string returnUrl, string provider) { + try { if (string.IsNullOrWhiteSpace(provider)) diff --git a/Web/Controllers/BaseController.cs b/Web/Controllers/BaseController.cs index 7d1f69d..ae32a9d 100644 --- a/Web/Controllers/BaseController.cs +++ b/Web/Controllers/BaseController.cs @@ -10,7 +10,7 @@ namespace Web.Controllers { public class BaseController : Controller { - protected ApplicationUser _currentUser => new ApplicationUser(HttpContext.User, HttpContext.Session); + protected ApplicationUser _currentUser => new ApplicationUser(HttpContext.User); public override void OnActionExecuting(ActionExecutingContext context) diff --git a/Web/Framework/ApplicationUser.cs b/Web/Framework/ApplicationUser.cs index 33bd7dc..20a2bc9 100644 --- a/Web/Framework/ApplicationUser.cs +++ b/Web/Framework/ApplicationUser.cs @@ -10,28 +10,14 @@ namespace Web.Framework { public class ApplicationUser { - ISession _session; private ClaimsPrincipal _user; - public ApplicationUser(ClaimsPrincipal user, ISession session) + public ApplicationUser(ClaimsPrincipal user) { _user = user; - _session= session; - } - - public void SetUserId(int value) - { - var userIdClaim = _user.FindFirst("UserId"); - var claimIdentity = ((ClaimsIdentity)_user.Identity); - if (userIdClaim != null) - claimIdentity.RemoveClaim(userIdClaim); - claimIdentity.AddClaim(new Claim("UserId", value.ToString())); - } - public int UserId { - get { return _session.GetInt32("UserId")??0; } } + public int UserId { get { return Convert.ToInt32(_user.FindFirst("UserId").Value); } } public string SocialId { get { return _user.FindFirst(ClaimTypes.NameIdentifier).Value; } } public string Email { get { return _user.FindFirst(ClaimTypes.Email).Value; } } public string Name { get { return _user.FindFirst(ClaimTypes.Name).Value; } } - } } diff --git a/Web/Framework/Configurations/AuthConfiguration.cs b/Web/Framework/Configurations/AuthConfiguration.cs index b249616..a7fb990 100644 --- a/Web/Framework/Configurations/AuthConfiguration.cs +++ b/Web/Framework/Configurations/AuthConfiguration.cs @@ -7,6 +7,8 @@ using System.Threading.Tasks; using AppServices.Services; using Microsoft.FeatureManagement; +using System; +using Domain.Entities; namespace Web.Framework.Configurations { @@ -41,6 +43,9 @@ public static void Init(IConfiguration configuration, IServiceCollection service googleOptions.ClaimActions.MapJsonKey("urn:google:profile", "link"); googleOptions.ClaimActions.MapJsonKey(ClaimTypes.Email, "email"); googleOptions.SaveTokens = true; + googleOptions.Events.OnCreatingTicket = ctx => { + return ProcessUser(ctx, "Google", services); + }; }); if(featureManager.IsEnabledAsync(FeatureFlags.UseFacebookAuthentication).Result) @@ -48,18 +53,27 @@ public static void Init(IConfiguration configuration, IServiceCollection service { facebookOptions.AppId = configuration["Authentication:Facebook:AppId"]; facebookOptions.AppSecret = configuration["Authentication:Facebook:AppSecret"]; + facebookOptions.Events.OnCreatingTicket = ctx => { + return ProcessUser(ctx, "Facebook", services); + }; }); if(featureManager.IsEnabledAsync(FeatureFlags.UseMicrosoftAuthentication).Result) services.AddAuthentication().AddMicrosoftAccount(microsoftOptions => { microsoftOptions.ClientId = configuration["Authentication:Microsoft:ClientId"]; microsoftOptions.ClientSecret = configuration["Authentication:Microsoft:ClientSecret"]; + microsoftOptions.Events.OnCreatingTicket = ctx => { + return ProcessUser(ctx, "Microsoft", services); + }; }); if(featureManager.IsEnabledAsync(FeatureFlags.UseLinkedInAuthentication).Result) services.AddAuthentication().AddLinkedIn(linkedinOptions => { linkedinOptions.ClientId = configuration["Authentication:LinkedIn:ClientId"]; linkedinOptions.ClientSecret = configuration["Authentication:LinkedIn:ClientSecret"]; + linkedinOptions.Events.OnCreatingTicket = ctx => { + return ProcessUser(ctx, "linkedin", services); + }; }); if(featureManager.IsEnabledAsync(FeatureFlags.UseGithubAuthentication).Result) services.AddAuthentication().AddGitHub(githubOptions => @@ -67,7 +81,50 @@ public static void Init(IConfiguration configuration, IServiceCollection service githubOptions.ClientId = configuration["Authentication:Github:ClientId"]; githubOptions.ClientSecret = configuration["Authentication:Github:ClientSecret"]; githubOptions.Scope.Add("user:email"); + githubOptions.Events.OnCreatingTicket = ctx => { + return ProcessUser(ctx, "github", services); + }; }); } + + + public static Task ProcessUser(OAuthCreatingTicketContext ctx, string provider, IServiceCollection services) + { + var serviceProvider = services.BuildServiceProvider(); + var loginService = serviceProvider.GetService(); + var userService = serviceProvider.GetService(); + + var currentUser = ctx.Identity; + var socialId = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value; + var loginInfo = loginService.GetLogin(provider.ToLower(), socialId); + if (loginInfo == null) //Create new account + { + var newUser = new User + { + Email = currentUser.FindFirst(ClaimTypes.Email).Value, + Name = currentUser.FindFirst(ClaimTypes.Name).Value, + }; + var result = userService.Create(newUser); + + if (result.Success) + { + var newLogin = new Login + { + LoginProvider = provider.ToLower(), + ProviderKey = socialId, + UserId = newUser.Id + }; + loginService.Create(newLogin); + var userIdClaim = new Claim("UserId", newUser.Id.ToString()); + ctx.Identity.AddClaim(userIdClaim); + } + } + else + { + var userIdClaim = new Claim("UserId", loginInfo.UserId.ToString()); + ctx.Identity.AddClaim(userIdClaim); + } + return Task.CompletedTask; + } } } \ No newline at end of file diff --git a/Web/Framework/ViewPageBase.cs b/Web/Framework/ViewPageBase.cs index 2931bf0..0ab11cf 100644 --- a/Web/Framework/ViewPageBase.cs +++ b/Web/Framework/ViewPageBase.cs @@ -8,7 +8,7 @@ public abstract class ViewPageBase : RazorPage { public String Title { get; set; } - protected ApplicationUser CurrentUser => new ApplicationUser(Context.User, Context.Session); + protected ApplicationUser CurrentUser => new ApplicationUser(Context.User); } } diff --git a/Web/appsettings.Development.json b/Web/appsettings.Development.json index 42fb5d1..36d25b7 100644 --- a/Web/appsettings.Development.json +++ b/Web/appsettings.Development.json @@ -1,34 +1,46 @@ { - "Logging": { - "LogLevel": { - "Default": "Debug", - "System": "Information", - "Microsoft": "Information" - } - }, - "ConnectionStrings": { - "DefaultConnection": "Data Source=../mydb.db;" - }, - "Authentication": { - "Google": { - "ClientId": "", - "ClientSecret": "" - }, - "Facebook": { - "AppId": "", - "AppSecret": "" + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } }, - "Github": { - "ClientId": "rtyrty", - "ClientSecret": "ertert" + "ConnectionStrings": { + "DefaultConnection": "Data Source=../mydb.db;" }, - "LinkedIn": { - "ClientId": "", - "ClientSecret": "" + "GoogleMapsApiKey": "AIzaSyCbhsqfnYFGPid88_Ncdm7IPcAN2Joj_VY", + "FeatureManagement": { + "use-facebook-authentication": false, + "use-github-authentication": false, + "use-linkedin-authentication": false, + "use-google-authentication": true, + "use-microsoft-authentication": false, + "jobscontroller-enable-search": false, + "use-mock-data": false, + "jobscontroller-enable-apply-for-job": false, + "jobscontroller-show-preview-warning": false }, - "Microsoft": { - "ClientId": "rtret", - "ClientSecret": "ertert" + "Authentication": { + "Google": { + "ClientId": "184368955865-eq4m1mec3kr504jqhr1tbi9mf2hgskhl.apps.googleusercontent.com", + "ClientSecret": "lLkrYzans4kwKYUARz7cBxKj" + }, + "Facebook": { + "AppId": "", + "AppSecret": "" + }, + "Github": { + "ClientId": "rtyrty", + "ClientSecret": "ertert" + }, + "LinkedIn": { + "ClientId": "", + "ClientSecret": "" + }, + "Microsoft": { + "ClientId": "rtret", + "ClientSecret": "ertert" + } } - } } \ No newline at end of file