Exemplo n.º 1
0
        public static async Task CookieSignin(CookieSigningInContext context)
        {
            UserManager <Models.ApplicationUser>   userManager   = context.HttpContext.RequestServices.GetRequiredService <UserManager <Models.ApplicationUser> >();
            SignInManager <Models.ApplicationUser> signinManager = context.HttpContext.RequestServices.GetRequiredService <SignInManager <Models.ApplicationUser> >();
            RoleManager <IdentityRole>             roleManager   = context.HttpContext.RequestServices.GetRequiredService <RoleManager <IdentityRole> >();
            ILoggerFactory logger = context.HttpContext.RequestServices.GetRequiredService <ILoggerFactory>();
            IMemoryCache   cache  = context.HttpContext.RequestServices.GetRequiredService <IMemoryCache>();

            Utilities.IAuthUtils authutils = context.HttpContext.RequestServices.GetRequiredService <Utilities.IAuthUtils>();
            RedditSharp.RefreshTokenWebAgentPool agentPool = context.HttpContext.RequestServices.GetRequiredService <RedditSharp.RefreshTokenWebAgentPool>();
            await agentPool.RemoveWebAgentAsync(context.Principal.Identity.Name);

            var user = await userManager.FindByNameAsync(context.Principal.Identity.Name);

            await authutils.UpdateModeratedSubredditsAsync(user);

            user = await userManager.FindByNameAsync(context.Principal.Identity.Name);

            var newPrincipal = await signinManager.CreateUserPrincipalAsync(user);

            if (user.HasWiki)
            {
                ((ClaimsIdentity)newPrincipal.Identity).AddClaim(new Claim("uri:snoonotes:haswiki", "true"));
            }
            if (user.HasConfig)
            {
                ((ClaimsIdentity)newPrincipal.Identity).AddClaim(new Claim("uri:snoonotes:hasconfig", "true"));
            }

            ((ClaimsIdentity)newPrincipal.Identity).AddClaim(new Claim("lastupdated", DateTime.UtcNow.ToString()));

            context.Principal = newPrincipal;
        }
Exemplo n.º 2
0
        public virtual async Task RevokeRefreshTokenAsync(string token, string username)
        {
            string ClientId     = Configuration["RedditClientID"];
            string ClientSecret = Configuration["RedditClientSecret"];
            string RediretURI   = Configuration["RedditRedirectURI"];

            RedditSharp.WebAgent     agent = new RedditSharp.WebAgent();
            RedditSharp.AuthProvider ap    = new RedditSharp.AuthProvider(ClientId, ClientSecret, RediretURI, agent);
            await ap.RevokeTokenAsync(token, true);

            await agentPool.RemoveWebAgentAsync(username); //TODO revoke here instead
        }
Exemplo n.º 3
0
 public Task ForceRefresh()
 {
     return(agentPool.RemoveWebAgentAsync(User.Identity.Name));
 }
Exemplo n.º 4
0
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
                return(View(nameof(Login)));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                return(RedirectToAction(nameof(Login)));
            }

            //remove from the webagent pool in case the user exists.
            await _agentPool.RemoveWebAgentAsync(info.Principal.Identity.Name);

            // 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 : true);

            if (result.Succeeded)
            {
                _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
                string scope        = info.Principal.Claims.FirstOrDefault(c => c.Type == "urn:reddit_scope").Value;
                var    scopes       = scope.Split(' ');
                bool   hasWiki      = scopes.Contains("wikiedit");
                bool   hasConfig    = scopes.Contains("modconfig");
                string accessToken  = info.AuthenticationTokens.FirstOrDefault(t => t.Name == "access_token").Value;
                string refreshToken = info.AuthenticationTokens.FirstOrDefault(t => t.Name == "refresh_token").Value;
                string tokenExpires = info.AuthenticationTokens.FirstOrDefault(t => t.Name == "expires_at").Value;

                var theuser = await _userManager.FindByNameAsync(info.Principal.Identity.Name);

                string oldRefreshToken = theuser.RefreshToken;

                if (!string.IsNullOrWhiteSpace(oldRefreshToken))
                {
                    await _authUtils.RevokeRefreshTokenAsync(oldRefreshToken, info.Principal.Identity.Name);
                }

                theuser.AccessToken  = accessToken;
                theuser.HasConfig    = hasConfig;
                theuser.HasWiki      = hasWiki;
                theuser.RefreshToken = refreshToken;
                theuser.TokenExpires = DateTime.Parse(tokenExpires);

                await _userManager.UpdateAsync(theuser);

                return(RedirectToLocal(returnUrl));
            }
            //if (result.RequiresTwoFactor)
            //{
            //    return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
            //}
            if (result.IsLockedOut)
            {
                return(View("Lockout"));
            }
            else
            {
                string scope        = info.Principal.Claims.FirstOrDefault(c => c.Type == "urn:reddit_scope").Value;
                var    scopes       = scope.Split(' ');
                bool   hasWiki      = scopes.Contains("wikiedit");
                bool   hasConfig    = scopes.Contains("modconfig");
                string accessToken  = info.AuthenticationTokens.FirstOrDefault(t => t.Name == "access_token").Value;
                string refreshToken = info.AuthenticationTokens.FirstOrDefault(t => t.Name == "refresh_token").Value;
                string tokenExpires = info.AuthenticationTokens.FirstOrDefault(t => t.Name == "expires_at").Value;
                // If the user does not have an account, then ask the user to create an account.
                var user = new ApplicationUser {
                    UserName     = info.Principal.Identity.Name,
                    AccessToken  = accessToken,
                    RefreshToken = refreshToken,
                    TokenExpires = DateTime.Parse(tokenExpires),
                    HasConfig    = hasConfig,
                    HasWiki      = hasWiki
                };
                var signresult = await _userManager.CreateAsync(user);

                if (signresult.Succeeded)
                {
                    signresult = await _userManager.AddLoginAsync(user, info);

                    if (signresult.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : true);

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                        return(RedirectToAction("PopulateClaims", new { ReturnUrl = returnUrl }));
                    }
                }
                AddErrors(signresult);
                ViewData["ReturnUrl"] = returnUrl;
                return(View());
            }
        }