Пример #1
0
        public async Task <IActionResult> Login(LoginEmployeeViewModel model)
        {
            if (ModelState.IsValid)
            {
                string          hashedPass = HashPassword.GenerateSHA512(model.Password);
                var             query      = from emp in _context.Employees where emp.Username == model.Username && emp.Password == hashedPass select emp;
                List <Employee> employees  = await query.ToListAsync();

                if (employees != null && employees.Count != 0)
                {
                    Employee employee = employees[0];

                    if (employee != null)
                    {
                        HttpContext.Session.Set("empId", Encoding.UTF8.GetBytes(employee.Id.ToString()));
                        if (employee.Id == 1)
                        {
                            ViewData["username"] = employee.Username;
                            return(RedirectToAction("AdminIndex", "Flight"));
                        }
                        else if (employee.Id != 1 && employee.Id > 0)
                        {
                            ViewData["username"] = employee.Username;
                            return(RedirectToAction("Index", "Flight"));
                        }
                        else
                        {
                            ViewData["incorrectCredentials"] = "Your credentials were incorrect! Please, type correct username and password!";
                            return(RedirectToAction(nameof(LoginForm)));
                        }
                    }
                    else
                    {
                        ViewData["incorrectCredentials"] = "Your credentials were incorrect! Please, type correct username and password!";
                        return(RedirectToAction(nameof(LoginForm)));
                    }
                }
                else
                {
                    ViewData["incorrectCredentials"] = "Your credentials were incorrect! Please, type correct username and password!";
                    return(RedirectToAction(nameof(LoginForm)));
                }
            }
            else
            {
                ViewData["incorrectCredentials"] = "Your credentials were incorrect! Please, type correct username and password!";
                return(RedirectToAction(nameof(LoginForm)));
            }
        }
Пример #2
0
        public async Task <IActionResult> LoginEmployeeAsync([Microsoft.AspNetCore.Mvc.FromBody] LoginEmployeeViewModel model)
        {
            if (ModelState.IsValid)
            {
                var result = await _employeeService.LoginEmployeeAsync(model);

                if (result.IsSuccess)
                {
                    return(Ok(result));
                }

                return(Unauthorized(result));
            }

            return(Unauthorized("Some properties are not Valid")); //TODO code 401 not authorized
        }
Пример #3
0
        public async Task <IActionResult> LoginEmployee(LoginEmployeeViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("Kullanici giris yapti.");
                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Basarısız giriş denemesi.");
                    return(View(model));
                }
            }

            return(View(model));
        }
Пример #4
0
        public async Task <IActionResult> Login(LoginEmployeeViewModel model, string returnUrl)
        {
            if (!this.ModelState.IsValid)
            {
                return(View(model));
            }

            var employee = await this._employeeRepository.GetEmployeeByUserNameAndPassword(model.UserName, model.Password);

            if (employee != null)
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, model.UserName),
                    new Claim("EmployeeName", employee.Name)
                };

                var userIdentity = new ClaimsIdentity(claims, "Login");

                ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
                await this.HttpContext.SignInAsync(principal);

                if (!String.IsNullOrEmpty(returnUrl) && this.Url.IsLocalUrl(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                this.ModelState.AddModelError("", "Login Failed");
            }

            return(View(model));
        }
Пример #5
0
        public IActionResult LoginForm()
        {
            LoginEmployeeViewModel model = new LoginEmployeeViewModel();

            return(View(model));
        }
 public ActionResult LoginWithEmployee(LoginEmployeeViewModel model)
 {
     return(View(model));
 }
Пример #7
0
        public async Task <UserManagerResponse> LoginEmployeeAsync(LoginEmployeeViewModel model)
        {
            var user = await _userManger.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(new UserManagerResponse
                {
                    Message = "There is no user with that Email address",
                    IsSuccess = false,
                });
            }

            var result = await _userManger.CheckPasswordAsync(user, model.Password);

            if (!result)
            {
                return new UserManagerResponse
                       {
                           Message   = "Invalid password",
                           IsSuccess = false,
                       }
            }
            ;

            var userRole = _context.UserRoles.SingleOrDefault(ur => ur.UserId == user.Id);
            var role     = _context.Roles.FirstOrDefault(x => x.Id == userRole.RoleId);

            if (role.Name != "Admin" && role.Name != "Employee")
            {
                return(new UserManagerResponse
                {
                    Message = "Unauthorized",
                    IsSuccess = false,
                });
            }

            var claims = new[]
            {
                new Claim("Email", model.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim("Role", role.Name)
            };

            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.AddDays(30),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));

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

            return(new UserManagerResponse
            {
                Message = tokenAsString,
                IsSuccess = true,
                ExpireDate = token.ValidTo
            });
        }

        /**
         * public async Task<UserManagerResponse> ConfirmEmailAsync(string userId, string token)
         * {
         *  var user = await _userManger.FindByIdAsync(userId);
         *  if (user == null)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "User not found"
         *      };
         *
         *  var decodedToken = WebEncoders.Base64UrlDecode(token);
         *  string normalToken = Encoding.UTF8.GetString(decodedToken);
         *
         *  var result = await _userManger.ConfirmEmailAsync(user, normalToken);
         *
         *  if (result.Succeeded)
         *      return new UserManagerResponse
         *      {
         *          Message = "Email confirmed successfully!",
         *          IsSuccess = true,
         *      };
         *
         *  return new UserManagerResponse
         *  {
         *      IsSuccess = false,
         *      Message = "Email did not confirm",
         *      Errors = result.Errors.Select(e => e.Description)
         *  };
         * }
         **/
        /**
         * public async Task<UserManagerResponse> ForgetPasswordAsync(string email)
         * {
         *  var user = await _userManger.FindByEmailAsync(email);
         *  if (user == null)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "No user associated with email",
         *      };
         *
         *  var token = await _userManger.GeneratePasswordResetTokenAsync(user);
         *  var encodedToken = Encoding.UTF8.GetBytes(token);
         *  var validToken = WebEncoders.Base64UrlEncode(encodedToken);
         *
         *  string url = $"{_configuration["AppUrl"]}/ResetPassword?email={email}&token={validToken}";
         *
         *  await _mailService.SendEmailAsync(email, "Reset Password", "<h1>Follow the instructions to reset your password</h1>" +
         *      $"<p>To reset your password <a href='{url}'>Click here</a></p>");
         *
         *  return new UserManagerResponse
         *  {
         *      IsSuccess = true,
         *      Message = "Reset password URL has been sent to the email successfully!"
         *  };
         * }
         **/
        /**
         * public async Task<UserManagerResponse> ResetPasswordAsync(ResetPasswordViewModel model)
         * {
         *  var user = await _userManger.FindByEmailAsync(model.Email);
         *  if (user == null)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "No user associated with email",
         *      };
         *
         *  if (model.NewPassword != model.ConfirmPassword)
         *      return new UserManagerResponse
         *      {
         *          IsSuccess = false,
         *          Message = "Password doesn't match its confirmation",
         *      };
         *
         *  var decodedToken = WebEncoders.Base64UrlDecode(model.Token);
         *  string normalToken = Encoding.UTF8.GetString(decodedToken);
         *
         *  var result = await _userManger.ResetPasswordAsync(user, normalToken, model.NewPassword);
         *
         *  if (result.Succeeded)
         *      return new UserManagerResponse
         *      {
         *          Message = "Password has been reset successfully!",
         *          IsSuccess = true,
         *      };
         *
         *  return new UserManagerResponse
         *  {
         *      Message = "Something went wrong",
         *      IsSuccess = false,
         *      Errors = result.Errors.Select(e => e.Description),
         *  };
         * }
         **/
    }