public IActionResult Login(LoginUser loginUser)
        {
            if (ModelState.IsValid == false)
            {
                return(View("AdminLogin"));
            }
            else
            {
                User dbUser = dbContext.Users.FirstOrDefault(user => loginUser.LoginEmail == user.Email);

                if (dbUser == null)
                {
                    ModelState.AddModelError("LoginEmail", "Invalid Credentials");
                }
                else
                {
                    User viewUser = new User
                    {
                        Email    = loginUser.LoginEmail,
                        Password = loginUser.LoginPassword
                    };

                    PasswordHasher <User> hasher = new PasswordHasher <User>();

                    PasswordVerificationResult result =
                        hasher.VerifyHashedPassword(viewUser, dbUser.Password, viewUser.Password);


                    if (result == 0)
                    {
                        ModelState.AddModelError("LoginEmail", "Invalid Credentials");
                    }
                    else
                    {
                        HttpContext.Session.SetInt32("UserId", dbUser.UserId);
                    }
                }
            }
            if (ModelState.IsValid == false)
            {
                return(View("AdminLogin"));
            }

            return(RedirectToAction("Dashboard"));
        }
Beispiel #2
0
        public async Task <AccountDTO> LoginAsync(string username, string password)
        {
            Account storedAccount = await _accountRepository.GetByUsernameAsync(username);

            if (storedAccount is null)
            {
                throw new UserNotFoundException(username);
            }

            PasswordVerificationResult passwordResult = _passwordHasher.VerifyHashedPassword(storedAccount, storedAccount.PasswordHash, password);

            if (passwordResult != PasswordVerificationResult.Success)
            {
                throw new InvalidPasswordException(username, password);
            }

            return(_mapper.Map <AccountDTO>(storedAccount));
        }
Beispiel #3
0
        public async Task <User> Login(string username, string password)
        {
            User storedUser = await _userDataService.GetByUsername(username);

            if (storedUser == null)
            {
                throw new UserNotFoundException(username);
            }

            PasswordVerificationResult verificationResult = _passwordHasherService.VerifyHashedPassword(storedUser.HashedPassword, password);

            if (verificationResult != PasswordVerificationResult.Success)
            {
                throw new InvalidPasswordException(username, password);
            }

            return(storedUser);
        }
        public bool ValidateCredentials(string username, string password)
        {
            AspNetUser user = _identityRepository.GetUser(username);

            if (user != null)
            {
                // 5 CompareTo(6) = -1      First int is smaller.
                // 6 CompareTo(5) =  1      First int is larger.
                // 5 CompareTo(5) =  0      Ints are equal.
                PasswordVerificationResult result = _hasher.VerifyHashedPassword(user, user.Password, password + user.HashSalt);
                if (result.CompareTo(PasswordVerificationResult.Success) == 0)
                {
                    return(true);
                }
            }

            return(false);
        }
Beispiel #5
0
        public static UserERP FindByEmailAndPassword(this UserManager <UserERP> userManager, string email, string password)
        {
            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            UserERP user = userManager.FindByEmail(email);

            if (user == null || string.IsNullOrEmpty(user.PasswordHash))
            {
                return(null);
            }

            PasswordVerificationResult pResult = userManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, password);

            return(pResult == PasswordVerificationResult.Failed ? null : user);
        }
        public async Task <User> Login(string username, string password)
        {
            User user = await _unitOfWork.UserRepository.GetByUsername(username);

            if (user == null)
            {
                throw new UserNotFoundException(username);
            }

            PasswordVerificationResult passwordResult = _passwordHasher.VerifyHashedPassword(user.PasswordHash, password);

            if (passwordResult != PasswordVerificationResult.Success)
            {
                throw new InvalidPasswordException(username, password);
            }

            return(user);
        }
        public async Task <bool> Login(string email, string password)
        {
            ApplicationUser user = await this.userManager.FindByEmailAsync(email).ConfigureAwait(false);

            if (user == null)
            {
                return(false);
            }
            PasswordVerificationResult result = this.userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, password);

            if (result == PasswordVerificationResult.Failed)
            {
                return(false);
            }
            await this.signInManager.SignInAsync(user, false).ConfigureAwait(false);

            return(true);
        }
Beispiel #8
0
        public async Task <Account> Login(string username, string password)
        {
            Account storedAccount = await _accountService.GetByUsername(username);

            if (storedAccount == null)
            {
                throw new UserNotFoundException(username);
            }

            PasswordVerificationResult passwordResult = _passwordHasher.VerifyHashedPassword(storedAccount.AccountHolder.PasswordHash, password);

            if (passwordResult != PasswordVerificationResult.Success)
            {
                throw new InvalidPasswordException(username, password);
            }

            return(storedAccount);
        }
        public IActionResult Login(EmployeeViewModel employeeViewModel)
        {
            EmployeeApplicationUser employee = new EmployeeApplicationUser();

            employee = iEmployeeRepository.GetEmployees().Where(x => x.UserName == employeeViewModel.UserName).FirstOrDefault();
            if (employee != null)
            {
                PasswordVerificationResult isNormalPasswordEqualToHashedPassword =
                    userManager.PasswordHasher.VerifyHashedPassword(employee, employee.PasswordHash, employeeViewModel.NormalPassword);
                List <EmployeeApplicationUser> employees = iEmployeeRepository.GetEmployees();
                if (isNormalPasswordEqualToHashedPassword != PasswordVerificationResult.Failed)
                {
                    // password is correct
                    if (employees.Exists(x => x.UserName == employee.UserName && x.PasswordHash == employee.PasswordHash))
                    {
                        string secret   = Configuration["JWTConfiguration:secret"];
                        string issuer   = Configuration["JWTConfiguration:issuer"];
                        string audience = Configuration["JWTConfiguration:audience"];

                        SymmetricSecurityKey secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
                        SigningCredentials   signInCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
                        List <Claim>         claims            = new List <Claim>()
                        {
                            new Claim(ClaimTypes.NameIdentifier, employee.Id.ToString()),
                            new Claim(ClaimTypes.Name, employee.UserName)
                        };
                        if (employee.Position != null)
                        {
                            claims.Add(new Claim(ClaimTypes.Role, employee.Position.Name));
                        }
                        JwtSecurityToken tokenOptions = new JwtSecurityToken(
                            issuer: issuer,
                            audience: audience,
                            claims: claims,
                            expires: DateTime.Now.AddMinutes(5),
                            signingCredentials: signInCredentials
                            );
                        string tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                        return(Ok(new { Token = tokenString }));
                    }
                }
            }
            return(NotFound("Wrong username/password!"));
        }
        public async Task <Account.ChangePassword> ChangePassword(ChangePasswordModel passwords)
        {
            try
            {
                string oldPassword = string.Empty;
                string newPassword = string.Empty;
                Users  user        = await _dbContex.Users
                                     .FirstOrDefaultAsync(u => u.UserName == passwords.UserName);

                if (user != null)
                {
                    PasswordVerificationResult result = _passwordHasher.VerifyHashedPassword(user, user.Password, passwords.oldPassword);
                    if (result == PasswordVerificationResult.Success)
                    {
                        if (passwords.newPassword == passwords.confirmNewPassword)
                        {
                            user.Password = _passwordHasher.HashPassword(user, passwords.newPassword);
                            _dbContex.Entry(user).State = EntityState.Modified;
                            if (await _dbContex.SaveChangesAsync() == 0)
                            {
                                return(Account.ChangePassword.Not_Changed);
                            }
                        }
                        else
                        {
                            return(Account.ChangePassword.Password_Dont_Match);
                        }
                    }
                    else
                    {
                        return(Account.ChangePassword.Password_Verification_Failure);
                    }
                }
                else
                {
                    return(Account.ChangePassword.Password_Not_Linked);
                }
                return(Account.ChangePassword.Changed);
            }
            catch (Exception)
            {
                return(Account.ChangePassword.Unknown_Error);
            }
        }
Beispiel #11
0
        public async Task <IActionResult> LoginAsync(LoginDto userModel, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (userModel == null)
            {
                throw new ArgumentNullException(nameof(userModel));
            }
            try
            {
                /* write your logic to compare username and password to that in the database */
                bool loginSuccess = false;
                var  userFromDb   = await authUtility.RetrieveEntityUsingPointQueryAsync <AzureTableUser>(AzureTableUser.PARTITIONKEY, userModel.NormalizedUserName, cancellationToken)
                                    .ConfigureAwait(false);

                if (userFromDb == null)
                {
                    throw new NullReferenceException($"User does not exist with username {userModel.UserName}");
                }

                PasswordVerificationResult passwordVerificationResult = _userManager.PasswordHasher.VerifyHashedPassword(userFromDb, userFromDb.PasswordHash, userModel.Password);


                if (passwordVerificationResult == PasswordVerificationResult.Success)
                {
                    // fetch user from the database instead of using dummy user object below
                    AzureTableUser user = new AzureTableUser()
                    {
                        Email    = userModel.UserName,
                        UserName = userModel.UserName,
                        Name     = "someName",
                    };
                    var token    = GenerateToken(user);
                    var response = ComposeTokenResponse(token, user);
                    return(Ok(response));
                }
                else
                {
                    return(Unauthorized(userModel));
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #12
0
        public override Task <ApplicationUser> FindAsync(string userName, string password)
        {
            Task <ApplicationUser> taskInvoke = Task <ApplicationUser> .Factory.StartNew(() =>
            {
                PasswordVerificationResult result = PasswordHasher.VerifyHashedPassword(userName, password);
                if (result == PasswordVerificationResult.SuccessRehashNeeded)
                {
                    ///
                    /// We can do a call to our data base here for profile data
                    ///
                    ApplicationUser applicationuser = new ApplicationUser();
                    applicationuser.UserName        = "******";
                    return(applicationuser);
                }
                return(null);
            });

            return(taskInvoke);
        }
Beispiel #13
0
        public IActionResult Login(LoginUser user)
        {
            List <Dictionary <string, object> > userRows = DbConnector.Query($"SELECT * FROM users WHERE email = '{user.email}'");

            if (userRows.Count < 1)
            {
                ModelState.AddModelError("email", "Invalid email/password");
            }
            else
            {
                Dictionary <string, object> theUser = userRows.First();
                string pwInDB     = (string)theUser["password"];
                int    userIdInDB = (int)theUser["user_id"];

                PasswordHasher <LoginUser> hasher = new PasswordHasher <LoginUser>();
                PasswordVerificationResult result = hasher.VerifyHashedPassword(user, pwInDB, user.password);
            }
            return(View("Login"));
        }
        public async Task <User> Login(string username, string password)
        {
            User userStored = await _userService.GetByUserName(username);

            if (userStored is null)
            {
                throw new UserNotFoundException(username);
            }

            PasswordVerificationResult passwordResult =
                _passwordHasher.VerifyHashedPassword(userStored.Password, password);

            if (passwordResult is not PasswordVerificationResult.Success)
            {
                throw new InvalidPasswordException(username, password);
            }

            return(userStored);
        }
Beispiel #15
0
        /// <summary>Authenticates the specified user.</summary>
        /// <param name="userDto">The user.</param>
        /// <returns>ClaimsIdentity.</returns>
        public ClaimsIdentity Authenticate(UserDTO userDto)
        {
            ClaimsIdentity claim = null;
            // находим пользователя
            PasswordVerificationResult result = PasswordVerificationResult.Failed;
            User user = Database.UserManager.FindByName(userDto.UserName);

            if (user != null)
            {
                result = Database.UserManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, userDto.Password);
            }
            if ((result == PasswordVerificationResult.Success))
            {
                claim = Database.UserManager.CreateIdentity(user,
                                                            DefaultAuthenticationTypes.ApplicationCookie);
            }

            return(claim);
        }
        public override System.Threading.Tasks.Task <ApplicationUser> FindAsync(string userName, string password)
        {
            Task <ApplicationUser> taskInvoke = Task <ApplicationUser> .Factory.StartNew(() =>
            {
                //First Verify Password...
                PasswordVerificationResult result = this.PasswordHasher.VerifyHashedPassword(userName, password);
                if (result == PasswordVerificationResult.SuccessRehashNeeded)
                {
                    //Return User Profile Object...
                    //So this data object will come from Database we can write custom ADO.net to retrieve details/
                    ApplicationUser applicationUser = new ApplicationUser();
                    applicationUser.UserName        = "******";
                    return(applicationUser);
                }
                return(null);
            });

            return(taskInvoke);
        }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            PasswordHasher hasher  = new PasswordHasher();
            string         pwdhash = hasher.HashPassword(model.Password);

            using (GamePool2016.Data.GamePoolContext context = new GamePoolContext())
            {
                //find the user, compare the hash
                Player player = context.Players.FirstOrDefault(item => item.UserName == model.UserName);
                if (player == null)
                {
                    ModelState.AddModelError("", "Invalid user name");
                    return(View(model));
                }
                else
                {
                    PasswordVerificationResult result = hasher.VerifyHashedPassword(player.PasswordHash, model.Password);
                    if (result == PasswordVerificationResult.Success)//(player.PasswordHash == pwdhash)
                    {
                        //success
                        HttpCookie cookie = new HttpCookie("UserName", model.UserName);
                        if (model.RememberMe)
                        {
                            cookie.Expires = DateTime.Now.AddYears(1);
                        }
                        Response.Cookies.Add(cookie);
                        FormsAuthentication.SetAuthCookie(model.UserName, true);
                        //return RedirectToLocal(returnUrl);
                        return(RedirectToAction("MyPicks", "Picks"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid password");
                        return(View(model));
                    }
                }
            }
        }
Beispiel #18
0
        public IActionResult submitLogin(LoginUser loginUser)
        {
            if (ModelState.IsValid == false)
            {
                return(View("Login"));
            }

            User oneUser = db.Users.FirstOrDefault(user => user.Email == loginUser.LoginEmail);

            string loginError = "Incorrect Email/Password or User does not exist";

            if (oneUser == null)
            {
                ModelState.AddModelError("LoginEmail", loginError);
                return(View("Login"));
            }

            PasswordHasher <LoginUser> hasher          = new PasswordHasher <LoginUser>();
            PasswordVerificationResult pwCompareResult = hasher.VerifyHashedPassword(loginUser, oneUser.Password, loginUser.LoginPassword);

            if (pwCompareResult == 0)
            {
                ModelState.AddModelError("LoginEmail", loginError);
                return(View("Login"));
            }

            Console.WriteLine("\n User exists \n");
            HttpContext.Session.SetInt32("UserId", oneUser.UserId);
            HttpContext.Session.SetString("FirstName", oneUser.FirstName);
            HttpContext.Session.SetString("LastName", oneUser.LastName);

            int?   userId    = HttpContext.Session.GetInt32("UserAge");
            string userFname = HttpContext.Session.GetString("FirstName");
            string userLname = HttpContext.Session.GetString("LastName");

            Console.WriteLine($"\n {userId} \n");
            Console.WriteLine($"\n {userFname} \n");
            Console.WriteLine($"\n {userLname} \n");



            return(RedirectToAction("Success"));
        }
Beispiel #19
0
        internal SignInResult ValidateUserCredentials(string emailAddress, string password)
        {
            var result = new SignInResult();

            if (string.IsNullOrWhiteSpace(emailAddress) || string.IsNullOrWhiteSpace(password))
            {
                result.Status = SignInStatus.Failure;
                return(result);
            }

            var user = GetUserInfo(emailAddress);

            if (user == null)
            {
                result.Status = SignInStatus.Failure;
            }
            else
            {
                if (!user.IsEnabled)
                {
                    result.Status = SignInStatus.Failure;
                }
                else if (user.LockoutEnabled && user.LockoutEndDateUtc.CompareTo(DateTime.UtcNow) <= 0)
                {
                    result.Status = SignInStatus.LockedOut;
                }
                else
                {
                    PasswordVerificationResult pwdResult = ValidatePassword(user.Password, password);
                    if (pwdResult == PasswordVerificationResult.Success)
                    {
                        result.Status   = SignInStatus.Success;
                        result.UserInfo = GetUserViewModel(user);
                        SetUserAccessSuccess(user);
                    }
                    else
                    {
                        result.Status = SetUserAccessFailed(user);
                    }
                }
            }
            return(result);
        }
Beispiel #20
0
        public async Task <User> LoginAsync(string email, string password)
        {
            var user = await _storage.FindUserAsync(email);

            if (user == null)
            {
                return(null);
            }

            PasswordHasher <User>      pw     = new PasswordHasher <User>();
            PasswordVerificationResult result = pw.VerifyHashedPassword(user, user.PasswordHash, password);
            bool pwdOk = result == PasswordVerificationResult.Success || result == PasswordVerificationResult.SuccessRehashNeeded;

            if (pwdOk && user.IsEmailConfirmed)
            {
                return(user);
            }
            return(null);
        }
        public async System.Threading.Tasks.Task <ApplicationUser> FindUserAsync(string userName, string password)
        {
            ApplicationUser applicationUser = new ApplicationUser();

            applicationUser = await FindByNameAsync(userName);

            if (applicationUser != null)
            {
                PasswordVerificationResult result = PasswordHasher.VerifyHashedPassword(applicationUser.PasswordHash, password);
                if (result == PasswordVerificationResult.Success)
                {
                    return(applicationUser);
                }
                return(null);
            }


            return(applicationUser);
        }
Beispiel #22
0
        public IActionResult LoginUser(LoginUser loginUser)
        {
            string genericError = "Invalid Credentials";

            if (ModelState.IsValid == false)
            {
                return(View("Login"));
            }

            User dbUser = dbContext.Users.FirstOrDefault(user => loginUser.LoginEmail == user.Email);

            if (dbUser == null)
            {
                ModelState.AddModelError("LoginEmail", genericError);
                return(View("Login"));
            }

            // dbUser is not null
            // Convert LoginUser to User for PasswordVerification
            User viewUser = new User
            {
                Email    = loginUser.LoginEmail,
                Password = loginUser.LoginPassword
            };

            PasswordHasher <User> hasher = new PasswordHasher <User>();

            PasswordVerificationResult passwordCheck =
                hasher.VerifyHashedPassword(viewUser, dbUser.Password, viewUser.Password);

            // failed pw match
            if (passwordCheck == 0)
            {
                ModelState.AddModelError("LoginEmail", genericError);
                return(View("Index"));
            }

            HttpContext.Session.SetInt32("UserId", dbUser.UserId);
            // AARON MAKE TO CHANGE THE REDIRECTION TO THE PROPER
            // PLACE NOT Home
            return(RedirectToAction("Dashboard"));
        }
Beispiel #23
0
        public async Task <ActionResult <object> > Login(AccountVM account)
        {
            var accountInDB = await _context.Accounts.Where(a => a.UserName.ToLower() == account.Username.ToLower() && a.IsDeleted == false).Include(a => a.User).FirstOrDefaultAsync();

            if (accountInDB == null)
            {
                return(NotFound());
            }
            if (!accountInDB.EmailConfirmed)
            {
                return(new JsonResult("email"));
            }
            if (accountInDB.LockoutEnabled)
            {
                return(new JsonResult("locked"));
            }
            PasswordVerificationResult passresult = _userManager.PasswordHasher.VerifyHashedPassword(accountInDB, accountInDB.PasswordHash, account.Password);

            if (passresult == PasswordVerificationResult.Failed)
            {
                return(NotFound());
            }
            account.Id         = accountInDB.Id;
            account.Password   = null;
            account.RoleName   = _userManager.GetRolesAsync(accountInDB).Result.ToList()[0];
            account.User.Image = accountInDB.User.Image;

            var rates = await _context.Reviews.Where(r => r.AccountId == account.Id).ToListAsync();

            var movieLikes = await _context.MovieLikes.Where(r => r.AccountId == account.Id).ToListAsync();

            var reviewLikes = await _context.ReviewLikes.Where(r => r.AccountId == account.Id).Select(r => new ReviewLike {
                AccountId = r.AccountId, ReviewId = r.ReviewId, Liked = r.Liked, DisLiked = r.DisLiked
            }).ToListAsync();

            ActivityVM activity = new ActivityVM()
            {
                RateIds = rates.Select(r => r.MovieId).ToList(), MovieLikeIds = movieLikes.Select(r => r.MovieId).ToList(), ReviewLikes = reviewLikes
            };

            return(new { Account = account, Activities = activity });
        }
        public Client Login(string username, string password)
        {
            Client storedClient = _unitOfWork.Clients.GetByUsername(username);

            try
            {
                PasswordVerificationResult passwordsMatch = _passwordHasher.VerifyHashedPassword(storedClient.PasswordHash, password);

                if (passwordsMatch != PasswordVerificationResult.Success)
                {
                    throw new Exception();
                }

                return(storedClient);
            }
            catch
            {
                return(null);
            }
        }
Beispiel #25
0
        public object Authenticate(string Email, string Password)
        {
            User User = Db.Users.Where(user => user.Email == Email).FirstOrDefault();

            if (User is null)
            {
                return("No user found");
            }

            PasswordHasher <User>      Validator = new PasswordHasher <User>();
            PasswordVerificationResult Result    = Validator.VerifyHashedPassword(User, User.Password, Password);

            if (Result is 0)
            {
                return("Invalid username or password");
            }

            User.Token = GenerateToken(User.Id);
            return(User.WithoutPassword());
        }
Beispiel #26
0
        public IActionResult Login(User user)
        {
            User UserInDb = dbContext.Users.FirstOrDefault(u => u.Username == user.Username);

            if (UserInDb == null)
            {
                ModelState.AddModelError("Username", "Username is invalid");
                return(View("Index"));
            }
            PasswordHasher <User>      hasher = new PasswordHasher <User>();
            PasswordVerificationResult result = hasher.VerifyHashedPassword(user, UserInDb.Password, user.Password);

            if (result == 0)
            {
                ModelState.AddModelError("Password", "Password entered is incorrect");
                return(View("Index"));
            }
            HttpContext.Session.SetInt32("sessionid", UserInDb.UserId);
            return(RedirectToAction("Dashboard"));
        }
        public async Task <string> GetToken(RegisterDto registerDto)
        {
            UserModel usuario = _mapper.Map <UserModel>(registerDto);

            try
            {
                UserModel user = await _dbset.FirstOrDefaultAsync(x => x.UserName == usuario.UserName);

                PasswordVerificationResult res = _passwordHasher.VerifyHashedPassword(user, user.PassWord, registerDto.PassWord);
                if (user != null && res == PasswordVerificationResult.Success)
                {
                    return(_tokenService.GenerarToken(user));
                }
                return(null);
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }
Beispiel #28
0
        private async void BtnLogin_Click(object sender, EventArgs e)
        {
            //ApplicationSignInManager signInManager=new ApplicationSignInManager(,)

            var user = unitOfWork.UsersRepo.Fetch(m => m.UserName == txtUserName.Text)
                       .Select(x => new { UserId = x.Id, PasswordHash = x.PasswordHash, FullName = x.FirstName + " - " + x.LastName, UserRoles = x.UserRoles }).FirstOrDefault();

            if (user == null)
            {
                // lblStatus.Text = "Username is invalid";
                txtPassword.Text = "";
                txtUserName.Text = "";
                return;
            }


            PasswordVerificationResult ret =
                userManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, txtPassword.Text);

            if (ret != PasswordVerificationResult.Success)
            {
                //   lblStatus.Text = "Password is invalid";
                txtPassword.Text = "";
                txtUserName.Text = "";
                return;
            }

            if (chkRemember.Checked)
            {
                Properties.Settings.Default.UserName  = txtUserName.Text;
                Properties.Settings.Default.Password  = txtPassword.Text;
                Properties.Settings.Default.RemembeMe = chkRemember.Checked;
                Properties.Settings.Default.Save();
            }

            User.UserId = user.UserId;
            //frmMain.lblUser.Text = user.FullName;
            //frmMain.lblUserLevel.Text = string.Join(",", user.UserRoles.Select(x => x.Name));
            this.isLogged = true;
            this.Close();
        }
Beispiel #29
0
        public IActionResult Login(LoginUser loginUser)
        {
            /*
             * For security, don't reveal what was invalid.
             * You can make your error messages more specific to help with testing
             * but on a live site it should be ambiguous.
             */
            string genericErrMsg = "Invalid Email or Password";

            if (ModelState.IsValid == false)
            {
                // So error messages will be displayed.
                return(View("Index"));
            }

            User dbUser = db.Users.FirstOrDefault(user => user.Email == loginUser.LoginEmail);

            if (dbUser == null)
            {
                ModelState.AddModelError("LoginEmail", genericErrMsg);
                Console.WriteLine(new String('*', 30) + "Login: Email not found");
                // So error messages will be displayed.
                return(View("Index"));
            }

            // User found b/c the above didn't return.
            PasswordHasher <LoginUser> hasher          = new PasswordHasher <LoginUser>();
            PasswordVerificationResult pwCompareResult = hasher.VerifyHashedPassword(loginUser, dbUser.Password, loginUser.LoginPassword);

            if (pwCompareResult == 0)
            {
                ModelState.AddModelError("LoginEmail", genericErrMsg);
                Console.WriteLine(new String('*', 30) + "Login: Password incorrect.");
                return(View("Index"));
            }

            // Password matched.
            HttpContext.Session.SetInt32("UserId", dbUser.UserId);
            HttpContext.Session.SetString("FullName", dbUser.FullName());
            return(RedirectToAction("All", "Trips"));
        }
Beispiel #30
0
        public ActionResult Connect([FromBody] User value)
        {
            PasswordHasher <string> pw = new PasswordHasher <string>();
            User user = _context.Users.FirstOrDefault(p => p.Email == value.Email);

            if (user == null)
            {
                return(BadRequest(new Error {
                    Type = "Error", Msg = "Bad credentials"
                }));
            }
            PasswordVerificationResult verify = pw.VerifyHashedPassword(value.Email, user.Password, value.Password);

            if (verify.ToString() == "Success")
            {
                return(Ok(user));
            }
            return(BadRequest(new Error {
                Type = "Error", Msg = "Bad credentials"
            }));
        }