Exemple #1
0
        public async Task <IdentityResult> CreateAsync(IdentityUser user, string password)
        {
            var identityResult = await _userManager.CreateAsync(user, password);

            CheckUpdatePersonId(user);
            return(identityResult);
        }
 private static IEnumerable <Claim> GetTokenClaims(IdentityUser identityUser, string googleOauthToken)
 {
     return(new List <Claim>
     {
         new Claim(JwtRegisteredClaimNames.Jti, identityUser.Id.ToString()),
         new Claim(JwtRegisteredClaimNames.Email, identityUser.Email ?? string.Empty),
         new Claim(ClaimPersonId, identityUser.PersonId?.ToString() ?? string.Empty),
         new Claim("oauth", googleOauthToken ?? string.Empty)
     });
 }
Exemple #3
0
        public async Task GoogleSignIn(AuthenticationProperties authProperties)
        {
            var          googleId = User.FindFirstValue(ClaimTypeId);
            IdentityUser user     = await _userService.FindByLoginAsync("Google", googleId);

            if (user == null)
            {
                var email = User.FindFirstValue(ClaimTypeEmail);
                if (!email.EndsWith(GisEmailSufix) && email != "*****@*****.**")
                {
                    throw new AuthenticationException("Only gis users or khahn are allowed to login with google sso");
                }

                //check for user by email
                user = await _userService.FindByEmailAsync(email);

                if (user == null)
                {
                    user = new IdentityUser
                    {
                        Email    = email,
                        UserName = email.Substring(0, email.Length - GisEmailSufix.Length)
                    };
                    var newUserResult = await _userService.CreateAsync(user);

                    if (!newUserResult.Succeeded)
                    {
                        throw newUserResult.Errors();
                    }
                }

                var newLoginResult =
                    await _userService.AddLoginAsync(user, new UserLoginInfo("Google", googleId, User.Identity.Name));

                if (!newLoginResult.Succeeded)
                {
                    throw newLoginResult.Errors();
                }
            }

            var authTokenResult = await _signInManager.UserManager.SetAuthenticationTokenAsync(user,
                                                                                               "Google",
                                                                                               GoogleOAuthTokenName,
                                                                                               authProperties.GetTokenValue(GoogleOAuthTokenName));

            if (!authTokenResult.Succeeded)
            {
                throw authTokenResult.Errors();
            }
            Response.Cookies.Append(JwtCookieName, await _jwtService.GetJwtSecurityTokenAsString(user));
        }
Exemple #4
0
        private async Task <IActionResult> SignIn(IdentityUser user, string password)
        {
            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, password, false);

            if (signInResult.IsLockedOut)
            {
                throw new ArgumentException("Account Locked, please contact an administrator");
            }

            if (!signInResult.Succeeded)
            {
                throw ThrowLoginFailed();
            }

            return(await JsonLoginResult(user));
        }
Exemple #5
0
        private async Task <IActionResult> JsonLoginResult(IdentityUser user)
        {
            if (user.ResetPassword)
            {
                //don't generate and return an access token if the reset password flag is set
                return(Json(new Dictionary <string, object>
                {
                    { "user", new UserProfile(user) }
                }));
            }

            var accessTokenString = await _jwtService.GetJwtSecurityTokenAsString(user);

            Response.Cookies.Append(JwtCookieName, accessTokenString);
            return(Json(new Dictionary <string, object>
            {
                { "access_token", accessTokenString }
            }));
        }
        private async Task <JwtSecurityToken> GetJwtSecurityToken(IdentityUser identityUser)
        {
            var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(identityUser);

            var oauthToken =
                await _signInManager.UserManager.GetAuthenticationTokenAsync(identityUser,
                                                                             "Google",
                                                                             GoogleOAuthTokenName);

            return(new JwtSecurityToken(
                       issuer: _jwtOptions.Issuer,
                       audience: _jwtOptions.Audience,
                       claims: GetTokenClaims(identityUser, oauthToken).Union(claimsPrincipal.Claims),
                       expires: DateTime.UtcNow.AddDays(7),
                       signingCredentials: new SigningCredentials(
                           new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtOptions.SecretKey)),
                           SecurityAlgorithms.HmacSha256)
                       ));
        }
Exemple #7
0
        public void InsertUser(string userName,
                               Guid?personId          = null,
                               string[] roles         = null,
                               bool sendHrLeaveEmails = false)
        {
            var userService  = Get <UserService>();
            var identityUser = new IdentityUser
            {
                UserName          = userName,
                ResetPassword     = true,
                PersonId          = personId,
                SendHrLeaveEmails = sendHrLeaveEmails
            };

            userService.CreateAsync(identityUser, "password").Wait();
            if (roles != null)
            {
                Task.WaitAll(roles.Select(role => userService.AddToRoleAsync(identityUser, role)).ToArray());
            }
        }
Exemple #8
0
        public async Task <IActionResult> Register([FromBody] RegisterUser registerUser)
        {
            var user = new IdentityUser().CopyFrom(registerUser);

            user.ResetPassword = true;
            if (string.IsNullOrEmpty(user.Email))
            {
                throw new UserError("User email required");
            }

            var result = await _userService.CreateAsync(user, registerUser.Password);

            if (!result.Succeeded)
            {
                throw result.Errors();
            }

            if (user.Id <= 0)
            {
                throw new ArgumentException("user id not generated error");
            }

            return(Json(new { Status = "Success" }));
        }
Exemple #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddFile("Logs/log-{Date}.txt", LogLevel.Warning);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });
//            app.UseRequestLocalization();
            app.Use(async(context, next) =>
            {
                await next();
                //redirect to login
                if (context.Response.StatusCode == 401 && !context.IsJsonRequest())
                {
                    context.Response.Redirect(ControllerExtensions.RedirectLogin(context.Request.GetDisplayUrl()));
                }

                if (context.Response.StatusCode == 404 &&
                    !Path.HasExtension(context.Request.Path.Value) &&
                    !context.Request.Path.Value.StartsWith("/api/"))
                {
//                    var requestCulture = context.Features.Get<IRequestCultureFeature>().RequestCulture;
//                    context.Request.Path = $"/{requestCulture.Culture.TwoLetterISOLanguageName}/index.html";
                    context.Request.Path = "/index.html";
                    await next();
                }
            });
            app.UseStaticFiles();
//            app.UseResponseCaching();
            app.UseAuthentication();
            app.UseSentinel();
            app.UseMvc();

            ConfigureDatabase(app.ApplicationServices, loggerFactory.CreateLogger("database"));
#if DEBUG
            using (var scope = app.ApplicationServices.CreateScope())
            {
                var dbConnection = scope.ServiceProvider.GetService <IDbConnection>();
                var roleManager  = scope.ServiceProvider.GetService <RoleManager <LinqToDB.Identity.IdentityRole <int> > >();
                var missingRoles =
                    new[] { "admin", "hr", "hradmin" }.Except(roleManager.Roles.Select(role => role.Name));
                foreach (var missingRole in missingRoles)
                {
                    roleManager.CreateAsync(new LinqToDB.Identity.IdentityRole <int>(missingRole)).Wait();
                }

                //to configure db look at ServiceFixture.SetupSchema
                if (!dbConnection.Users.Any())
                {
                    var userService  = scope.ServiceProvider.GetService <UserService>();
                    var identityUser = new IdentityUser
                    {
                        UserName      = "******",
                        ResetPassword = true
                    };
                    userService.CreateAsync(identityUser, "password").Wait();
                    userService.AddToRoleAsync(identityUser, "admin").Wait();
                }
            }
#endif
        }
Exemple #10
0
 public Task <IdentityResult> AddLoginAsync(IdentityUser user, UserLoginInfo login)
 {
     return(_userManager.AddLoginAsync(user, login));
 }
Exemple #11
0
 public Task <IdentityResult> ChangePasswordAsync(IdentityUser user, string currentPassword, string newPassword)
 {
     return(_userManager.ChangePasswordAsync(user, currentPassword, newPassword));
 }
Exemple #12
0
 public Task <IdentityResult> UpdateAsync(IdentityUser user)
 {
     CheckUpdatePersonId(user);
     return(_userManager.UpdateAsync(user));
 }
Exemple #13
0
 public Task <IdentityResult> AddToRoleAsync(IdentityUser user, string role)
 {
     return(_userManager.AddToRoleAsync(user, role));
 }