Exemplo n.º 1
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, UserManager<ApplicationUser> userManager, ApplicationDbContext ctx)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
            // Refactor this into a seperate class
            // Remove hard coding of the password in the installDevices routine!
            app.UseBasicAuthentication(o =>
            {
                o.Realm = $"j64 Alarm";

                o.Events = new BasicAuthenticationEvents
                {
                    OnSignIn = c =>
                    {
                        var x = userManager.FindByNameAsync(c.UserName);
                        x.Wait();
                        if (x.Result != null)
                        {
                            var y = userManager.CheckPasswordAsync(x.Result, c.Password);
                            y.Wait();

                            if (y.Result == true)
                            {
                                var z = userManager.GetClaimsAsync(x.Result);
                                z.Wait();
                                var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme);
                                c.Principal = new ClaimsPrincipal(identity);
                            }
                        }

                        return Task.FromResult(true);
                    }
                };
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            // Seed some default entries into the database
            var task = new Data.UserDataInitializer(ctx, userManager).CreateMasterUser();
        }
Exemplo n.º 2
0
        public async Task <bool> ValidateUser(UserForAuthenticationDto userForAuth)
        {
            _user = await _userManager.FindByNameAsync(userForAuth.UserName);

            return(_user != null && await _userManager.CheckPasswordAsync(_user, userForAuth.Password));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Checks if given username and password are correct
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>boolean, true if username exists and the given password is correct</returns>
        private async Task <bool> IsValidUsernameAndPassword(string username, string password)
        {
            var user = await _userManager.FindByNameAsync(username);

            return(await _userManager.CheckPasswordAsync(user, password));
        }
Exemplo n.º 4
0
        public async Task <bool> CheckPasswordAsync(string username, string password)
        {
            var user = await _userManager.FindByNameAsync(username);

            return(user != null && await _userManager.CheckPasswordAsync(user, password));
        }
Exemplo n.º 5
0
        public async Task<IActionResult> Token([FromBody] UserLogin model)
        {
            var user = await userManager.FindByNameAsync(model.UserName);

            // nếu người dùng không tồn tại
            if (user == null)
            {
                return BadRequest(new
                {
                    error = "user or password wrong"
                });
            }

            var passOk = await userManager.CheckPasswordAsync(user, model.Password);

            // nếu mật khẩu không đúng
            if (passOk == false)
            {
                return BadRequest(new
                {
                    error = "user or password wrong"
                });
            }

            // nếu user và pass đúng => sinh token

            var now = DateTime.UtcNow;

            var roles = roleManager.Roles.Where(r =>
                r.Users.Any(u => u.UserId == user.Id)
            ).Select(r => r.Name).ToList();

            var claims = new List<Claim>{
                new Claim(ClaimTypes.NameIdentifier,  user.Id.ToString()),
                new Claim(ClaimTypes.Name,  user.UserName),
                new Claim("AspNet.Identity.SecurityStamp",  user.SecurityStamp),
                new Claim(JwtRegisteredClaimNames.Sub,  user.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(DateTime.Now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
            };

            claims.AddRange(roles.Select(r => new Claim(ClaimTypes.Role, r)));

            var expires = now.Add(TimeSpan.FromDays(15));

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Ngay xua co mot con ga..."));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(
                issuer: "RS",
                audience: "RS",
                claims: claims,
                notBefore: now,
                expires: expires,
                signingCredentials: creds
            );

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return Json(new
            {
                access_token = encodedJwt,
                expires_in = expires,
                userId = user.Id
            });
        }
        public async Task <IActionResult> Exchange(OpenIdConnectRequest request)
        {
            Debug.Assert(request.IsTokenRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                if (!await _signInManager.CanSignInAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    }));
                }

                // Reject the token request if two-factor authentication has been enabled by the user.
                if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    }));
                }

                // Ensure the user is not already locked out.
                if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                // Ensure the password is valid.
                if (!await _userManager.CheckPasswordAsync(user, request.Password))
                {
                    if (_userManager.SupportsUserLockout)
                    {
                        await _userManager.AccessFailedAsync(user);
                    }

                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                if (_userManager.SupportsUserLockout)
                {
                    await _userManager.ResetAccessFailedCountAsync(user);
                }

                // Create a new authentication ticket.
                var ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            }));
        }
Exemplo n.º 7
0
        public async Task <IActionResult> TokenExchange(OpenIdConnectRequest request)
        {
            if (!request.IsPasswordGrantType())
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                    ErrorDescription = "El tipo de concesión especificado no es compatible."
                }));
            }

            var user = await _userManager.FindByNameAsync(request.Username);

            if (user == null)
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "El usuario o contraseña es invalido."
                }));
            }

            // Ensure the user is allowed to sign in
            if (!await _signInManager.CanSignInAsync(user))
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "El usuario no tiene permitido ingresar."
                }));
            }

            // Ensure the user is not already locked out
            if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "El usuario o contraseña es invalido."
                }));
            }

            // Ensure the password is valid
            if (!await _userManager.CheckPasswordAsync(user, request.Password))
            {
                if (_userManager.SupportsUserLockout)
                {
                    await _userManager.AccessFailedAsync(user);
                }

                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "El usuario o contraseña es invalido."
                }));
            }

            // Reset the lockout count
            if (_userManager.SupportsUserLockout)
            {
                await _userManager.ResetAccessFailedCountAsync(user);
            }

            // Look up the user's roles (if any)
            var roles = new string[0];

            if (_userManager.SupportsUserRole)
            {
                roles = (await _userManager.GetRolesAsync(user)).ToArray();
            }

            // Create a new authentication ticket w/ the user identity
            var ticket = await CreateTicketAsync(request, user, roles);

            var signInResult = SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);

            return(signInResult);// SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
        }
Exemplo n.º 8
0
        public async Task <Tuple <bool, string, AuthResponse> > AuthenticateUser(AuthVm login)
        {
            try
            {
                if (string.IsNullOrEmpty(login.Phone_Email) || string.IsNullOrEmpty(login.Password))
                {
                    return(new Tuple <bool, string, AuthResponse>(false, "Fill in all the fields", null));
                }
                User user = new User();
                if (!login.Phone_Email.Contains("@"))
                {
                    user = await _userManager.Users.FirstOrDefaultAsync(x => x.PhoneNumber == login.Phone_Email);
                }
                else
                {
                    user = await _userManager.FindByEmailAsync(login.Phone_Email);
                }

                if (user == null)
                {
                    return(new Tuple <bool, string, AuthResponse>(false, "Your email/phone number and or password is incorrect", null));
                }

                var userHasPassword = await _userManager.HasPasswordAsync(user);

                if (!userHasPassword)
                {
                    return(new Tuple <bool, string, AuthResponse>(false, "sorry you do not have a valid password", null));
                }

                var userHasValidPassword = await _userManager.CheckPasswordAsync(user, login.Password);

                if (!userHasValidPassword)
                {
                    return(new Tuple <bool, string, AuthResponse>(false, "Your password is invalid", null));
                }



                var claims = new List <Claim>()
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim("Surname", user.Surname),
                    new Claim("OtherNames", user.OtherNames),
                    new Claim(ClaimTypes.MobilePhone, user.PhoneNumber),
                };

                var          token    = JwtTokenGenerator.GenerateAccessToken(claims, _configuration).ToString();
                AuthResponse response = new AuthResponse
                {
                    Surname     = user.Surname,
                    OtherNames  = user.OtherNames,
                    Token       = token,
                    PhoneNumber = user.PhoneNumber,
                    ImagePath   = user.ImagePath
                };

                var result = await _signinManager.PasswordSignInAsync(login.Phone_Email, login.Password, false, false);



                return(new Tuple <bool, string, AuthResponse>(result.Succeeded, " ", response));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 9
0
        public async Task <Models.AuthResponse> LoginUserAsync(Login _model)
        {
            var user = await user_manager.FindByNameAsync(_model.username);

            if (user == null)
            {
                return new Models.AuthResponse()
                       {
                           Success = false, Error = new ApiError()
                           {
                               Message = "Cannot login user", Detail = "User does not exist", Code = (int)ServerResponse.ErrorCodes.USER_NOT_EXIST
                           }
                       }
            }
            ;
            bool usernameCheck = user.UserName == _model.username;

            if (!usernameCheck)
            {
                return new Models.AuthResponse()
                       {
                           Success = false, Error = new ApiError()
                           {
                               Message = "Cannot login user", Detail = "Credentials are incorrect", Code = (int)ServerResponse.ErrorCodes.USER_CREDENTIALS_INCORRECT
                           }
                       }
            }
            ;

            var passwordCheck = await user_manager.CheckPasswordAsync(user, _model.password);

            if (!passwordCheck)
            {
                return new Models.AuthResponse()
                       {
                           Success = false, Error = new ApiError()
                           {
                               Message = "Cannot login user", Detail = "Credentials are incorrect", Code = (int)ServerResponse.ErrorCodes.USER_CREDENTIALS_INCORRECT
                           }
                       }
            }
            ;

            var getRoles = await user_manager.GetRolesAsync(user);

            var claims = new[]
            {
                new Claim("Username", user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Role, getRoles[0])
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["AuthSettings:Key"]));
            var token = new JwtSecurityToken(issuer: configuration["AuthSettings:Issuer"], audience: configuration["AuthSettings:Audience"], claims: claims, expires: DateTime.Now.AddHours(8),
                                             signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

            string tokenAsString = new JwtSecurityTokenHandler().WriteToken(token);



            string role = "NA";

            if (getRoles.Count >= 1)
            {
                role = getRoles[0];
            }

            return(new Models.AuthResponse()
            {
                Success = true, Token = tokenAsString, Expiry = token.ValidTo, Role = role
            });;
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true


                if (model.Email.ToLower().Equals(PharmixStaticHelper.SuperAdminUsername) && _customerService.ValidateSuperAdminPassword(model.Password))
                {                           //Pharmix user.
                    var user = new ApplicationUser
                    {
                        UserName      = PharmixStaticHelper.SuperAdminUsername,
                        Email         = model.Email,
                        SecurityStamp = DateTime.Now.ToString()
                    };
                    await _signInManager.SignInAsync(user, true);

                    return(RedirectToAction("Index", "Customer"));

                    //model.TrustList = new SelectList(trustService.GetAllTrusts()
                    //    .Select(t => new SelectListItem { Text = t.Name, Value = t.Id.ToString() }), "Value", "Text");

                    //return View(model);
                    ////return RedirectToAction("Index", "User");
                }

                else
                {
                    var user = await _userManager.FindByNameAsync(model.Email);

                    if (user != null && (await _userManager.CheckPasswordAsync(user, model.Password)) && (user.IsResetPasswordRequired ?? false))
                    {           //Password reset required
                        return(RedirectToAction("ChangePassword", new { userName = model.Email }));
                    }
                    else
                    {
                        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false);

                        if (result.Succeeded)
                        {
                            _logger.LogInformation("User logged in.");
                            if (!string.IsNullOrEmpty(returnUrl))
                            {
                                return(RedirectToLocal(returnUrl));
                            }
                            else
                            {
                                return(RedirectToAction("Index", "Customer"));
                            }
                        }
                        else if (result.RequiresTwoFactor)
                        {
                            return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }));
                        }
                        if (result.IsLockedOut)
                        {
                            _logger.LogWarning("User account locked out.");
                            return(RedirectToAction(nameof(Lockout)));
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                            return(View(model));
                        }
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 11
0
 public async Task <bool> CheckPassword(AppUser user, string password)
 {
     return(await _userManager.CheckPasswordAsync(user, password));
 }
Exemplo n.º 12
0
        public async Task <UserProfileDetailsApiModel> LogInAsync([FromBody] LoginCredentialsApiModel loginCredentials)
        {
            // TODO: Localize all strings
            // The message when we fail to login
            var invalidErrorMessage = "Invalid username or password";

            // The error response for a failed login
            var errorResponse = new UserProfileDetailsApiModel
            {
                // Set error message
                ErrorMessage = invalidErrorMessage
            };

            // Make sure we have a user name
            if (loginCredentials?.UsernameOrEmail == null || string.IsNullOrWhiteSpace(loginCredentials.UsernameOrEmail))
            {
                // Return error message to user
                return(errorResponse);
            }

            // Validate if the user credentials are correct...

            // Is it an email?
            var isEmail = loginCredentials.UsernameOrEmail.Contains("@");

            // Get the user details
            var user = isEmail ?
                       // Find by email
                       await mUserManager.FindByEmailAsync(loginCredentials.UsernameOrEmail) :
                       // Find by username
                       await mUserManager.FindByNameAsync(loginCredentials.UsernameOrEmail);

            // If we failed to find a user...
            if (user == null)
            {
                // Return error message to user
                return(errorResponse);
            }

            // If we got here we have a user...
            // Let's validate the password

            // Get if password is valid
            var isValidPassword = await mUserManager.CheckPasswordAsync(user, loginCredentials.Password);

            // If the password was wrong
            if (!isValidPassword)
            {
                // Return error message to user
                return(errorResponse);
            }

            // If we get here, we are valid and the user passed the correct login details

            // Return token to user
            return(new UserProfileDetailsApiModel
            {
                // Pass back the user details and the token
                FirstName = user.FirstName,
                LastName = user.LastName,
                Email = user.Email,
                Username = user.UserName,
                Token = user.GenerateJwtToken()
            });
        }
Exemplo n.º 13
0
        public async Task <OmbiIdentityResult> UpdateLocalUser([FromBody] UpdateLocalUserModel ui)
        {
            if (string.IsNullOrEmpty(ui.CurrentPassword))
            {
                return(Error("You need to provide your current password to make any changes"));
            }

            var changingPass = !string.IsNullOrEmpty(ui.Password) || !string.IsNullOrEmpty(ui.ConfirmNewPassword);

            if (changingPass)
            {
                if (!ui.Password.Equals(ui?.ConfirmNewPassword, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(Error("Passwords do not match"));
                }
            }

            if (!EmailValidator.IsValidEmail(ui.EmailAddress))
            {
                return(Error($"The email address {ui.EmailAddress} is not a valid format"));
            }
            // Get the user
            var user = await UserManager.Users.FirstOrDefaultAsync(x => x.Id == ui.Id);

            if (user == null)
            {
                return(Error("The user does not exist"));
            }

            // Make sure the pass is ok
            var passwordCheck = await UserManager.CheckPasswordAsync(user, ui.CurrentPassword);

            if (!passwordCheck)
            {
                return(Error("Your password is incorrect"));
            }

            user.Email = ui.EmailAddress;

            var updateResult = await UserManager.UpdateAsync(user);

            if (!updateResult.Succeeded)
            {
                return(new OmbiIdentityResult
                {
                    Errors = updateResult.Errors.Select(x => x.Description).ToList()
                });
            }

            if (changingPass)
            {
                var result = await UserManager.ChangePasswordAsync(user, ui.CurrentPassword, ui.Password);

                if (!result.Succeeded)
                {
                    return(new OmbiIdentityResult
                    {
                        Errors = result.Errors.Select(x => x.Description).ToList()
                    });
                }
            }
            return(new OmbiIdentityResult
            {
                Successful = true
            });
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Post([FromBody] CrearClaveViewModel claveViewModel)
        {
            var parNuevo = KeyPair.GenerarNuevo();


            if (ModelState.IsValid)
            {
                var currentUserId = _userManager.GetUserId(User);
                var currentUser   = _context.Users.Include(u => u.Claves).First(u => u.Id == currentUserId);

                if (!await _userManager.CheckPasswordAsync(currentUser, claveViewModel.Password))
                {
                    return(Ok(new Response(false, "La contraseña es incorrecta.")));
                }

                var securityData = new SecurityData(currentUser.DatosSeguridad);

                var iv = new byte[16];
                using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create())
                {
                    rng.GetBytes(iv);
                }


                var encryptedPrivateKey = securityData.Encrypt(parNuevo.PrivateKey.ByteArray, claveViewModel.Password, iv);



                //System.Security.Claims.ClaimsPrincipal currentUser = this.User;
                //bool IsAdmin = currentUser.IsInRole("Admin");
                //var id = _userManager.GetUserId(User); // Get user id:
                //var user = await _userManager.GetUserAsync(User);

                var csrString = LibreriaCriptografica.CertificateSigningRequest.GeneratePkcs10(
                    parNuevo.PrivateKey,
                    parNuevo.PublicKey,
                    claveViewModel.CommonName,
                    claveViewModel.Organization,
                    claveViewModel.OrganizationUnit,
                    claveViewModel.City,
                    claveViewModel.State,
                    claveViewModel.CountryIso2Characters,
                    claveViewModel.Email
                    );

                _context.Add(new Clave()
                {
                    ApplicationUser      = currentUser,
                    EncPrivKey           = Convert.ToBase64String(encryptedPrivateKey) + "|" + Convert.ToBase64String(iv), //parNuevo.PrivateKey.ByteArray.ToHexString(),
                    PublicKey            = parNuevo.PublicKey.ByteArray.ToHexString(),
                    NombreIdentificativo = claveViewModel.NombreIdentificativo,
                    Organizacion         = claveViewModel.Organization,
                    UnidadOrganizacional = claveViewModel.OrganizationUnit,
                    Localidad            = claveViewModel.City,
                    EstadoOProvincia     = claveViewModel.State,
                    Pais          = claveViewModel.CountryIso2Characters,
                    Email         = claveViewModel.Email,
                    NombreComun   = claveViewModel.CommonName,
                    CSR           = Encoding.ASCII.GetBytes(csrString),
                    FechaCreacion = DateTime.Now
                });

                _context.SaveChanges();
                return(Ok(new Response(true)));;
            }
            return(Ok(new Response(false)));;
            //return View();
        }
Exemplo n.º 15
0
        public IActionResult Index([FromBody] ProfileDTO Profile)
        {
            ProfileStatus objProfileStatus = new ProfileStatus();

            objProfileStatus.isSuccessful = true;
            objProfileStatus.status       = "";

            #region Validation ****************************
            EmailValidation objEmailValidation = new EmailValidation();
            if (!objEmailValidation.IsValidEmail(Profile.email))
            {
                objProfileStatus.status       = "This Email is not valid.";
                objProfileStatus.isSuccessful = false;
                return(Ok(objProfileStatus));
            }

            if ((Profile.firstName == null) || (Profile.firstName.Length < 1))
            {
                objProfileStatus.status       = "This First Name is not long enough.";
                objProfileStatus.isSuccessful = false;
                return(Ok(objProfileStatus));
            }

            if ((Profile.lastName == null) || (Profile.lastName.Length < 1))
            {
                objProfileStatus.status       = "This Last Name is not long enough.";
                objProfileStatus.isSuccessful = false;
                return(Ok(objProfileStatus));
            }
            #endregion

            // Update User ****************************

            string CurrentUser = this.User.Identity.Name;

            var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();
            optionsBuilder.UseSqlServer(GetConnectionString());

            using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
            {
                try
                {
                    // Check the Email
                    string strEmailToCheck      = Profile.email.Trim().ToLower();
                    var    objAdefHelpDeskEmail = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers
                                                   where AdefHelpDeskUsers.Email.ToLower() == strEmailToCheck
                                                   where AdefHelpDeskUsers.Username != CurrentUser
                                                   select AdefHelpDeskUsers).FirstOrDefault();

                    if (objAdefHelpDeskEmail != null)
                    {
                        // User is already taken
                        objProfileStatus.status       = "This Email address is already taken.";
                        objProfileStatus.isSuccessful = false;
                        return(Ok(objProfileStatus));
                    }

                    // Get the user
                    var objUser = (from user in context.AdefHelpDeskUsers
                                   where user.Username == CurrentUser
                                   select user).FirstOrDefault();

                    if (objUser != null)
                    {
                        // Update them
                        objUser.FirstName = Profile.firstName.Trim();
                        objUser.LastName  = Profile.lastName.Trim();
                        objUser.Email     = Profile.email.Trim();

                        #region See if the password will be updated
                        if (
                            (Profile.orginalpassword != null) &&
                            (Profile.orginalpassword.Trim().Length > 1) &&
                            (Profile.password != null) &&
                            (Profile.password.Trim().Length > 1)
                            )
                        {
                            // The original password must be correct
                            var user         = _userManager.Users.Where(x => x.UserName == CurrentUser).FirstOrDefault();
                            var SignInResult = _userManager.CheckPasswordAsync(user, Profile.orginalpassword.Trim()).Result;

                            if (!SignInResult)
                            {
                                objProfileStatus.status =
                                    "The original password must be correct to set the new password.";
                                objProfileStatus.isSuccessful = false;
                                return(Ok(objProfileStatus));
                            }

                            // First try to update the password in the ASP.NET Membership provider
                            var result = _userManager.ChangePasswordAsync(
                                user, Profile.orginalpassword.Trim(), Profile.password.Trim()).Result;

                            if (!result.Succeeded)
                            {
                                // Return the errors
                                string strErrors = "";
                                foreach (var Error in result.Errors)
                                {
                                    strErrors = strErrors + "\n" + Error.Description;
                                }

                                objProfileStatus.status       = strErrors;
                                objProfileStatus.isSuccessful = false;
                                return(Ok(objProfileStatus));
                            }
                        }
                        #endregion

                        // Save changes
                        context.SaveChanges();
                    }
                    else
                    {
                        objProfileStatus.isSuccessful = false;
                        objProfileStatus.status       = $"Could not find {CurrentUser} in database";
                    }
                }
                catch (Exception ex)
                {
                    objProfileStatus.isSuccessful = false;
                    objProfileStatus.status       = ex.GetBaseException().Message;
                }
            }

            return(Ok(objProfileStatus));
        }
Exemplo n.º 16
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            if (button != "login")
            {
                // the user clicked the "cancel" button
                var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Username);

                // validate username/password against in-memory store
                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration),
                            AllowRefresh = true,
                            IssuedUtc    = DateTimeOffset.UtcNow
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(user.Id, user.UserName, props);

                    // make sure the returnUrl is still valid, and if so redirect back to authorize endpoint or a local page
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl) || Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(Redirect("~/"));
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError("", AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await _account.BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Exemplo n.º 17
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.DenyAuthorizationAsync(context, AuthorizationError.AccessDenied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (context.IsNativeClient())
                    {
                        // The client is native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.Username);

                if (await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    var tokenLifetime = _configuration.GetValue("TokenLifetimeMinutes", 120);

                    var props = new AuthenticationProperties
                    {
                        ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(tokenLifetime),
                        AllowRefresh = true,
                        RedirectUri  = model.ReturnUrl
                    };

                    if (model.RememberLogin)
                    {
                        var permanentTokenLifetime = _configuration.GetValue("PermanentTokenLifetimeDays", 365);

                        props.ExpiresUtc   = DateTimeOffset.UtcNow.AddDays(permanentTokenLifetime);
                        props.IsPersistent = true;
                    }

                    await _signInManager.SignInAsync(user, props);

                    // make sure the returnUrl is still valid, and if yes - redirect back to authorize endpoint
                    if (_interaction.IsValidReturnUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }

                    return(Redirect("~/"));
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials", clientId : context?.Client.ClientId));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            ViewData["ReturnUrl"] = model.ReturnUrl;

            return(View(vm));
        }
Exemplo n.º 18
0
        private async Task <IActionResult> GetToken(TokenRequestViewModel model)
        {
            try
            {
                // check if there's an user with the given username
                var user = await UserManager.FindByNameAsync(model.username);

                // fallback to support e-mail address instead of username
                if (user == null && model.username.Contains("@"))
                {
                    user = await UserManager.FindByEmailAsync(model.username);
                }

                if (user == null || !await UserManager.CheckPasswordAsync(user, model.password))
                {
                    // user does not exists or password mismatch
                    return(new UnauthorizedResult());
                }

                // username & password matches: create and return the Jwt token.
                DateTime now = DateTime.UtcNow;

                // add the registered claims for JWT (RFC7519).
                // For more info, see https: //tools.ietf.org/html/rfc7519#section-4.1
                var claims = new []
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUnixTimeSeconds().ToString())

                    // TODO: add additional claims here
                };

                var tokenExpirationMins = Configuration.GetValue <int>("Auth:Jwt:TokenExpirationInMinutes");
                var issuerSigningKey    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Auth:Jwt:Key"]));

                var token = new JwtSecurityToken(
                    issuer: Configuration["Auth:Jwt:Issuer"],
                    audience: Configuration["Auth:Jwt:Audience"],
                    claims: claims,
                    notBefore: now,
                    expires: now.Add(TimeSpan.FromMinutes(tokenExpirationMins)),
                    signingCredentials: new SigningCredentials(
                        issuerSigningKey,
                        SecurityAlgorithms.HmacSha256)
                    );

                var encodedToken = new JwtSecurityTokenHandler().WriteToken(token);

                // build & return the response
                var response = new TokenResponseViewModel()
                {
                    token      = encodedToken,
                    expiration = tokenExpirationMins
                };
                return(Json(response));
            }
            catch (Exception ex)
            {
                return(new UnauthorizedResult());
            }
        }
Exemplo n.º 19
0
 public async Task <bool> CheckPassword(User user, string password)
 {
     return(await _userManager.CheckPasswordAsync(_mapper.Map <AppUser>(user), password));
 }
Exemplo n.º 20
0
 public async Task <bool> VerificarCredencialesAsync(UsuariosEntidad usuario, string password)
 {
     return(await _userManager.CheckPasswordAsync(usuario, password));
 }
        public async Task <IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            RequirePassword = await _userManager.HasPasswordAsync(user);

            if (RequirePassword)
            {
                if (!await _userManager.CheckPasswordAsync(user, Input.Password))
                {
                    ModelState.AddModelError(string.Empty, "Incorrect password.");
                    return(Page());
                }
            }

            var userId = await _userManager.GetUserIdAsync(user);

            //Delete the user and all related information in a single database transaction.
            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                try
                {
                    //Delete KnuthMorrisPratt input sets owned by the user.
                    var knuthMorrisPrattInputs =
                        from input in _dbContext.KnuthMorrisPrattInputs
                        join owner in _dbContext.KnuthMorrisPrattInputOwners on input.KnuthMorrisPrattInputId equals owner.KnuthMorrisPrattInputId into inputs
                        from i in inputs.DefaultIfEmpty()
                        where i.AspNetUserId == _userManager.GetUserId(User)
                        select input;
                    _dbContext.KnuthMorrisPrattInputs.RemoveRange(knuthMorrisPrattInputs);
                    _dbContext.SaveChanges();

                    //Now delete the user.
                    var result = await _userManager.DeleteAsync(user);

                    if (result.Succeeded)
                    {
                        transaction.Commit();

                        await _signInManager.SignOutAsync();

                        _logger.LogInformation("User with ID '{UserId}' deleted themselves.", userId);

                        return(Redirect("~/"));
                    }
                    else
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw new InvalidOperationException($"Unexpected error occurred deleting user with ID '{userId}'.");
                }
            }
        }
Exemplo n.º 22
0
        public async Task <ServiceModels.ServiceResponse> UpdateAccount(InputModels.UpdateAccountInput input)
        {
            var serviceResponse = new ServiceModels.ServiceResponse();

            if (!await UserManager.CheckPasswordAsync(UserContext.ApplicationUser, input.Password))
            {
                var message = $"Invalid password for '{input.DisplayName}'.";
                serviceResponse.Error(nameof(InputModels.UpdateAccountInput.Password), message);
                Log.LogWarning(message);
            }

            var userRecord = await UserManager.FindByIdAsync(input.Id);

            if (userRecord is null)
            {
                var message = $"No user record found for '{input.DisplayName}'.";
                serviceResponse.Error(message);
                Log.LogCritical(message);
            }

            CanEdit(userRecord.Id);

            if (userRecord is null)
            {
                var message = $"No user account found for '{input.DisplayName}'.";
                serviceResponse.Error(message);
                Log.LogCritical(message);
            }

            if (!serviceResponse.Success)
            {
                return(serviceResponse);
            }

            if (input.DisplayName != userRecord.DisplayName)
            {
                userRecord.DisplayName = input.DisplayName;
                DbContext.Update(userRecord);

                Log.LogInformation($"Display name was modified by '{UserContext.ApplicationUser.DisplayName}' for account '{userRecord.DisplayName}'.");
            }

            var birthday = new DateTime(input.BirthdayYear, input.BirthdayMonth, input.BirthdayDay);

            if (birthday != userRecord.Birthday)
            {
                userRecord.Birthday = birthday;
                DbContext.Update(userRecord);

                Log.LogInformation($"Birthday was modified by '{UserContext.ApplicationUser.DisplayName}' for account '{userRecord.DisplayName}'.");
            }

            DbContext.SaveChanges();

            if (input.NewEmail != userRecord.Email)
            {
                serviceResponse.RedirectPath = UrlHelper.Action(nameof(Account.Details), nameof(Account), new { id = input.DisplayName });

                var identityResult = await UserManager.SetEmailAsync(userRecord, input.NewEmail);

                if (!identityResult.Succeeded)
                {
                    foreach (var error in identityResult.Errors)
                    {
                        Log.LogError($"Error modifying email by '{UserContext.ApplicationUser.DisplayName}' from '{userRecord.Email}' to '{input.NewEmail}'. Message: {error.Description}");
                        serviceResponse.Error(error.Description);
                    }

                    return(serviceResponse);
                }

                identityResult = await UserManager.SetUserNameAsync(userRecord, input.NewEmail);

                if (!identityResult.Succeeded)
                {
                    foreach (var error in identityResult.Errors)
                    {
                        Log.LogError($"Error modifying username by '{UserContext.ApplicationUser.DisplayName}' from '{userRecord.Email}' to '{input.NewEmail}'. Message: {error.Description}");
                        serviceResponse.Error(error.Description);
                    }

                    return(serviceResponse);
                }

                Log.LogInformation($"Email address was modified by '{UserContext.ApplicationUser.DisplayName}' from '{userRecord.Email}' to '{input.NewEmail}'.");

                var code = await UserManager.GenerateEmailConfirmationTokenAsync(userRecord);

                if (EmailSender.Ready)
                {
                    var callbackUrl = EmailConfirmationLink(userRecord.Id, code);

                    await EmailSender.SendEmailConfirmationAsync(input.NewEmail, callbackUrl);

                    if (userRecord.Id == UserContext.ApplicationUser.Id)
                    {
                        await SignOut();
                    }
                }
                else
                {
                    identityResult = await UserManager.ConfirmEmailAsync(userRecord, code);

                    if (!identityResult.Succeeded)
                    {
                        foreach (var error in identityResult.Errors)
                        {
                            Log.LogError($"Error confirming '{userRecord.Email}'. Message: {error.Description}");
                            serviceResponse.Error(error.Description);
                        }
                    }
                    else
                    {
                        Log.LogInformation($"User confirmed email '{userRecord.Email}'.");
                    }
                }

                return(serviceResponse);
            }

            SettingsRepository.UpdateUserSettings(input);

            if (!string.IsNullOrEmpty(input.NewPassword) && input.Password != input.NewPassword && UserContext.ApplicationUser.Id == input.Id)
            {
                var identityResult = await UserManager.ChangePasswordAsync(userRecord, input.Password, input.NewPassword);

                if (!identityResult.Succeeded)
                {
                    foreach (var error in identityResult.Errors)
                    {
                        Log.LogError($"Error modifying password by '{UserContext.ApplicationUser.DisplayName}' for '{userRecord.DisplayName}'. Message: {error.Description}");
                        serviceResponse.Error(nameof(InputModels.UpdateAccountInput.NewPassword), error.Description);
                    }
                }
                else if (userRecord.Id == UserContext.ApplicationUser.Id)
                {
                    Log.LogInformation($"Password was modified by '{UserContext.ApplicationUser.DisplayName}' for '{userRecord.DisplayName}'.");
                    await SignOut();

                    serviceResponse.RedirectPath = UrlHelper.Action(nameof(Login));
                    return(serviceResponse);
                }
            }

            if (serviceResponse.Success)
            {
                serviceResponse.RedirectPath = UrlHelper.Action(nameof(Account.Details), nameof(Account), new { id = input.DisplayName });
            }

            return(serviceResponse);
        }
Exemplo n.º 23
0
 public async Task <bool> ValidateCredentials(ApplicationUser user, string password)
 {
     return(await _userManager.CheckPasswordAsync(user, password));
 }
Exemplo n.º 24
0
        private async Task CreateToken(HttpContext httpContext)
        {
            try
            {
                // retrieve the relevant FORM data
                string username = httpContext.Request.Form["username"];
                string password = httpContext.Request.Form["password"];

                // check if there's an user with the given username
                var user = await UserManager.FindByNameAsync(username);

                // fallback to support e-mail address instead of username
                if (user == null && username.Contains("@"))
                {
                    user = await UserManager.FindByEmailAsync(username);
                }

                var success = user != null && await UserManager.CheckPasswordAsync(user, password);

                if (success)
                {
                    DateTime now = DateTime.UtcNow;

                    // add the registered claims for JWT (RFC7519).
                    // For more info, see https://tools.ietf.org/html/rfc7519#section-4.1
                    var claims = new[] {
                        new Claim(JwtRegisteredClaimNames.Iss, Issuer),
                        new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
                        // TODO: add additional claims here
                    };

                    // Create the JWT and write it to a string
                    var token = new JwtSecurityToken(
                        claims: claims,
                        notBefore: now,
                        expires: now.Add(TokenExpiration),
                        signingCredentials: SigningCredentials);
                    var encodedToken = new JwtSecurityTokenHandler().WriteToken(token);

                    // build the json response
                    var jwt = new
                    {
                        access_token = encodedToken,
                        expiration   = (int)TokenExpiration.TotalSeconds
                    };

                    // return token
                    httpContext.Response.ContentType = "application/json";
                    await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(jwt));

                    return;
                }
            }
            catch (Exception ex)
            {
                // TODO: handle errors
                throw ex;
            }

            httpContext.Response.StatusCode = 400;
            await httpContext.Response.WriteAsync("Invalid username or password.");
        }
        private async Task GenerateToken(HttpContext context)
        {
            string username = context.Request.Form["username"];
            string password = context.Request.Form["password"];

            User user = null;

            user = await Task.Run(() => _db.Users.SingleOrDefault(x => x.UserName == username));

            var result = _userManager.CheckPasswordAsync(user, password);

            if (result.Result == false)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid username or password");

                return;
            }
            var now = DateTime.UtcNow;


            /*var claims = new Claim[]
             * {
             *  new Claim(JwtRegisteredClaimNames.Sub, username),
             *  new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
             *  new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
             * };
             */
            var userClaims = await _userManager.GetRolesAsync(user);

            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));
            //claims.AddRange(user.Claims.ToArray());

            foreach (var x in userClaims)
            {
                claims.Add(new Claim(ClaimTypes.Role, x));
            }


            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                expires_in   = (int)_options.Expiration.TotalSeconds
            };

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Exemplo n.º 26
0
        public async Task <IActionResult> EditProfile(EditProfileViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = _unitOfWork.Users.GetUser(_signInManager.UserManager.GetUserId(User));
                if (model.NewPassword != null && model.CurrentPassword != null)
                {
                    if (await _userManager.CheckPasswordAsync(user, model.CurrentPassword))
                    {
                        var result = await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);

                        if (!result.Succeeded)
                        {
                            return(RedirectToAction(nameof(ResultOperation), new { op = "failed. Password couldn't be changed" }));
                        }
                    }
                    else
                    {
                        return(RedirectToAction(nameof(ResultOperation), new { op = "failed. Your old password is not correct" }));
                    }
                }
                else
                {
                    return(View(model));
                }
                if (model.Image != null)
                {
                    string type = model.Image.ContentType.Split("/")[0];
                    if (type != "image")
                    {
                        throw new InvalidDataException();
                    }
                    string currentFileName = model.Image.FileName.Trim('"');
                    string fileExtension   = Path.GetExtension(currentFileName);
                    string newFileName     = Guid.NewGuid().ToString() + fileExtension;
                    string semiPath        = $@"images\profileimages\{newFileName}";
                    string filePath        = Path.Combine(_hostingEnvironment.WebRootPath, semiPath);
                    string dbPath          = $"/images/profileimages/{newFileName}";
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        model.Image.CopyTo(stream);
                        stream.Flush();
                    }
                    if (user.Image != null)
                    {
                        string delPath     = user.Image.Replace("/", @"\");
                        string fulldelPath = _hostingEnvironment.WebRootPath + delPath;
                        System.IO.File.Delete(fulldelPath);
                    }
                    user.Image = dbPath;
                }
                else
                {
                    return(RedirectToAction(nameof(ResultOperation), new { op = "failed. The file you uploaded is not in a correct format" }));
                }
                user.FirstName = model.FirstName;
                user.LastName  = model.LastName;
                user.Email     = model.Email;
                user.Biography = model.Bio;
                _unitOfWork.Users.Update(user);
                await _unitOfWork.Save();

                return(RedirectToAction(nameof(ResultOperation), new { op = "succeded." }));
            }
            else
            {
                return(View(model));
            }
        }
Exemplo n.º 27
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            if (!CanLoginOrRegister())
            {
                return(RedirectToAction("Login"));
            }
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                // Require the user to have a confirmed email before they can log on.
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    if (user.RequiresEmailConfirmation && !await _userManager.IsEmailConfirmedAsync(user))
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "You must have a confirmed email to log in.");
                        return(View(model));
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }

                if (!await _userManager.IsLockedOutAsync(user) && await _u2FService.HasDevices(user.Id))
                {
                    if (await _userManager.CheckPasswordAsync(user, model.Password))
                    {
                        LoginWith2faViewModel twoFModel = null;

                        if (user.TwoFactorEnabled)
                        {
                            // we need to do an actual sign in attempt so that 2fa can function in next step
                            await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : true);

                            twoFModel = new LoginWith2faViewModel
                            {
                                RememberMe = model.RememberMe
                            };
                        }

                        return(View("SecondaryLogin", new SecondaryLoginViewModel()
                        {
                            LoginWith2FaViewModel = twoFModel,
                            LoginWithU2FViewModel = await BuildU2FViewModel(model.RememberMe, user)
                        }));
                    }
                    else
                    {
                        var incrementAccessFailedResult = await _userManager.AccessFailedAsync(user);

                        ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                        return(View(model));
                    }
                }


                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(RedirectToLocal(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(View("SecondaryLogin", new SecondaryLoginViewModel()
                    {
                        LoginWith2FaViewModel = new LoginWith2faViewModel()
                        {
                            RememberMe = model.RememberMe
                        }
                    }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToAction(nameof(Lockout)));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 28
0
        public async Task <IActionResult> Login([FromBody] UserCredentials credentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // get the user to verify
            // NOTE: the find is case INsensitive so "Kip" will find "kip"
            // result is cased correctly for subsequent calls.
            var userToVerify = await _userManager.FindByNameAsync(credentials.UserName);

            if (userToVerify == null)
            {
                _logger.LogWarning("Login attempt from invalid user ({0})", credentials.UserName);
                return(Unauthorized());
            }

            // check the credentials
            if (await _userManager.CheckPasswordAsync(userToVerify, credentials.Password))
            {
                // thumbs up, create the Jawt
                var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Consts.SECRET_KEY));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
                var claims            = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, userToVerify.UserName)
                };
                // TODO probably would be better to use a role manager etc, but none are available for Marten/Postgres yet.
                if (userToVerify.IsAGod)
                {
                    claims.Add(new Claim(ClaimTypes.Role, Consts.CLAIM_GOD));
                }

                var token = new JwtSecurityToken(
                    issuer: _jwtOptions.Issuer,
                    audience: _jwtOptions.Audience,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(3600), // TODO: Is this a decent timeout?
                    signingCredentials: signinCredentials
                    );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
                _logger.LogInformation($"Login success for unchecked user ({credentials.UserName}) exact user ({userToVerify.UserName})");

                var userLeagues = await _leagueService.ReadUserLeagues(userToVerify.UserName);

                var pickemUser = new UserLoggedIn
                {
                    DefaultLeagueCode = userToVerify.DefaultLeagueCode,
                    Email             = userToVerify.Email,
                    UserName          = userToVerify.UserName,
                    Token             = tokenString,
                    Leagues           = userLeagues
                };

                return(new OkObjectResult(pickemUser));
            }
            else
            {
                _logger.LogWarning("Login attempt failure from user ({0})", credentials.UserName);
                return(Unauthorized());
            }
        }
Exemplo n.º 29
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                // validate username/password
                var user = await _userManager.FindByNameAsync(model.Username);

                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.Name));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }
                    ;

                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(user.Id, user.UserName, props);

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials"));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
Exemplo n.º 30
0
        public async Task <bool> ValidateUser(LoginUserDto userDto)
        {
            _user = await _userManager.FindByNameAsync(userDto.Email);

            return(_user != null && await _userManager.CheckPasswordAsync(_user, userDto.Password));
        }
Exemplo n.º 31
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, SampleDataInitializer sampleData, UserManager<ApplicationUser> userManager)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
                try
                {
                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                    }
                }
                catch { }
            }

            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            app.UseStaticFiles();

            app.UseIdentity();

            // Refactor this into a seperate class
            // Remove hard coding of the password in the installDevices routine!
            app.UseBasicAuthentication(o =>
            {
                o.Realm = $"j64 Alarm";

                o.Events = new BasicAuthenticationEvents
                {
                    OnSignIn = c =>
                    {
                        var x = userManager.FindByNameAsync(c.UserName);
                        x.Wait();
                        if (x.Result != null)
                        {
                            var y = userManager.CheckPasswordAsync(x.Result, c.Password);
                            y.Wait();

                            if (y.Result == true)
                            {
                                var z = userManager.GetClaimsAsync(x.Result);
                                z.Wait();
                                var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme);
                                c.Principal = new ClaimsPrincipal(identity);
                            }
                        }

                        return Task.FromResult(true);
                    }
                };
            });
            
            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            
            // Seed some default entries into the database
            var task = sampleData.CreateMasterUser();
        }
Exemplo n.º 32
0
 public Task <bool> CheckPasswordAsync(BlogUser user, string password)
 {
     return(userManager.CheckPasswordAsync(user, password));
 }