public string CheckLogin(CustomerLoginViewModel userInput) { /* * 1.尋找有此帳號 * 2.取出鹽 * 3.輸入密碼與鹽合併後SHA256且HASH 與DB中的HASH相符 即驗證成功 */ if (userInput.Account.Equals("admin") && userInput.Account.Equals("admin")) { return("admin"); } var result = false; var existAcc = this.CustomerRepo.All().FirstOrDefault(x => x.Account.Equals(userInput.Account)); if (existAcc == null) { result = false; } else { string salt = existAcc.Salt; byte[] pwdAndSalt = Encoding.UTF8.GetBytes(userInput.Password + salt); byte[] hashBytes = new SHA256Managed().ComputeHash(pwdAndSalt); string hash = Convert.ToBase64String(hashBytes); if (hash.Equals(existAcc.Password)) { result = true; } } return(result?existAcc.Account:string.Empty); }
public async Task <ActionResult <CustomerViewModel> > Login([FromBody] CustomerLoginViewModel customerLoginViewModel) { var customer = await _context.Customers .Where(u => u.Email == customerLoginViewModel.Email && u.PassWord == customerLoginViewModel.PassWord) .FirstOrDefaultAsync(); CustomerViewModel customerViewModel = null; if (customer == null) { return(Ok("Email hoặc mật khẩu không chính xác.")); } if (customer.IsBlocked) { return(Ok("Tài khoản đang tạm khóa.")); } if (customer != null) { RefreshTokenCustomer refreshToken = GenerateRefreshToken(); customer.RefreshTokenCustomers.Add(refreshToken); await _context.SaveChangesAsync(); customerViewModel = new CustomerViewModel(customer); customerViewModel.RefreshToken = refreshToken.Token; } //sign token here customerViewModel.AccessToken = GenerateAccessToken(customer.CustomerId); return(customerViewModel); }
public async Task <IActionResult> Login(CustomerLoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false); if (result.Succeeded) { logger.LogInformation("User logged in."); return(RedirectToLocal(returnUrl)); } if (result.RequiresTwoFactor) { return(RedirectToAction(nameof(LoginTwoFactor), new { returnUrl, model.RememberMe })); } if (result.IsLockedOut) { logger.LogWarning("UserAccount locked out."); return(RedirectToAction(nameof(Lockout))); } else { ModelState.TryAddModelError(string.Empty, "Failed to login"); return(View(model)); } } //something failed along the way return(View(model)); }
public BusinessLayerResult <Customer> LoginCustomer(CustomerLoginViewModel data) { Customer c = Find(x => x.mail == data.email && x.password != data.password); if (c != null) { c.notifications.Add(new Notification { notification = "IP: " + GetIp() + " - HATALI GİRİŞ YAPILMIŞTIR", link = "#" }); } Customer customer = Find(x => x.mail == data.email && x.password == data.password); BusinessLayerResult <Customer> res = new BusinessLayerResult <Customer>(); res.Result = customer; if (customer != null) { if (!customer.IsActive) { res.AddError(ErrorMessageCode.UserIsNotActive, "Hesap aktifleştirilmemiştir."); res.AddError(ErrorMessageCode.CheckYourEmail, "Lütfen E-Posta adresinizi kontrol ediniz."); } } else { res.AddError(ErrorMessageCode.EMailorPassWrong, "Kullanıcı adı ya da parola uyuşmuyor."); } return(res); }
public ActionResult LogIn(CustomerLoginViewModel model) { if (ModelState.IsValid) { string email = model.Email.Trim(); string pwd = model.Pwd.Trim(); Customer customer = repo.Customers.FirstOrDefault(m => m.Email == email && m.Password.Trim() == pwd); if (customer != null) { Session["customerId"] = customer.CustomerId; Session["name"] = customer.FirstName; return(RedirectToAction("List", "Product")); } else { ModelState.AddModelError("loginFailed", "Incorrect email and password!"); return(View()); //return RedirectToAction("List", "Product"); } } else { return(View()); } }
public ActionResult Login(CustomerLoginViewModel login) { if (!ModelState.IsValid) { return(View(login)); } string accountName = _loginService.CheckLogin(login); if (!string.IsNullOrEmpty(accountName)) { string userRole = ""; if (accountName.Equals("admin")) { userRole = "Manager"; } else { userRole = "Customer"; } var authTicket = new FormsAuthenticationTicket( 1, // version accountName, // user name DateTime.Now, // created DateTime.Now.AddMinutes(20), // expires false, // persistent? userRole // can be used to store roles ); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); HttpContext.Response.Cookies.Add(authCookie); //FormsAuthentication.SetAuthCookie(accountName, false); //設置cookies if (Request.QueryString["ReturnUrl"] != null) { if (Request.QueryString["ReturnUrl"].Contains("LogOut")) { return(RedirectToAction("Index", "Home")); } else { return(Redirect(Request.QueryString["ReturnUrl"])); } } else { return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("error", "帳號不存在或者密碼輸入錯誤"); return(View(login)); } }
public ActionResult 會員登入(CustomerLoginViewModel c登入資料) { MotaiDataEntities dbContext = new MotaiDataEntities(); tCustomer d資料確認 = dbContext.tCustomers.FirstOrDefault (c => c.cAccount == c登入資料.cAccount && c.cPassword.Equals(c登入資料.cPassword)); if (d資料確認 != null) { Session[CSession關鍵字.SK_LOGINED_CUSTOMER] = d資料確認; return(RedirectToAction("首頁")); } return(RedirectToAction("首頁")); }
public IActionResult CustomerLogin(CustomerLoginViewModel customerLoginViewModel) { var loggedInCustomer = DineOutContext.Customer.Where(r => r.Email == customerLoginViewModel.Customer.Email).FirstOrDefault(); if (loggedInCustomer != null) { // Check to see if password matches string[] salt = loggedInCustomer.PasswordHash.Split(":"); string newHashedPin = GenerateHash(customerLoginViewModel.Customer.PasswordHash, salt[0]); bool isValid = newHashedPin.Equals(salt[1]); if (isValid == true) { HttpContext.Session.SetString("customer_id", loggedInCustomer.ToString()); TempData["message"] = "Successfully Logged In!"; if (customerLoginViewModel.RestaurantId != 0 && customerLoginViewModel.MenuId != 0) { return(RedirectToAction("OrderDetails", "CustomerOrder", new { customerId = loggedInCustomer.CustomerId, menuId = customerLoginViewModel.MenuId, restaurantId = customerLoginViewModel.RestaurantId })); } else { return(RedirectToAction("Index")); } } else { // Password does not match TempData["message"] = "Password does not match!"; return(View()); } } else { TempData["message"] = "User Does not Exist!"; return(View()); } }
public IActionResult Login([FromBody] CustomerLoginViewModel viewModel) { if (!ModelState.IsValid) { return(Unauthorized()); } else { Customer existUser = CustomerExists(viewModel.Email); bool validPassword = CheckPassword(existUser, viewModel.PassWord); if (existUser != null && validPassword) { var authClaims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JWT:Secret"])); var token = new JwtSecurityToken( issuer: _config["JWT:ValidIssuer"], audience: _config["JWT:ValidAudience"], expires: DateTime.Now.AddHours(1.5), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo, })); } else { return(Unauthorized()); } } }
public ActionResult CustomerLogin(CustomerLoginViewModel model) { tbl_KhachHang UserLogin = new tbl_KhachHang(); if (Request.HttpMethod == "POST") { try { if (dB.tbl_KhachHang.Any(d => d.UserName == model.UserName)) { if (model.Password == dB.tbl_KhachHang.Where(d => d.UserName == model.UserName).FirstOrDefault().Password) { if (model.RememberMe) { Response.Cookies["CustomerLogin"].Value = model.UserName; } UserLogin = dB.tbl_KhachHang.Where(d => d.UserName == model.UserName).FirstOrDefault(); Session["CustomerLogin"] = model.UserName; CustomerLoginStatus.IsLogin = true; CustomerLoginStatus.CustomerUser = model.UserName; CustomerLoginStatus.CustomerUserId = UserLogin.Id; CustomerLoginStatus.CustomerName = UserLogin.FullName; return(RedirectToAction("Index", "Home")); } else { model.LoginError = "*Mật khẩu không chính xác"; } } else { model.LoginError = "*Tài khoản không chính xác"; } } catch { model.LoginError = "*Lỗi không xác định"; } } return(View(model)); }
public async Task <IActionResult> Login(CustomerLoginViewModel vm) { if (ModelState.IsValid) { var result = await _signInManagerService.PasswordSignInAsync(vm.UserName, vm.Password, vm.RememberMe, false); if (result.Succeeded) { if (!string.IsNullOrEmpty(vm.ReturnUrl)) { return(Redirect(vm.ReturnUrl)); } else { return(RedirectToAction("Index", "Home")); } } } ModelState.AddModelError("", "Username or password is not correct"); return(View(vm)); }
public ActionResult CustomerLogin(CustomerLoginViewModel model) { if (ModelState.IsValid) { CustomerManager cm = new CustomerManager(); BusinessLayerResult <Customer> res = cm.LoginCustomer(model); if (res.Errors.Count > 0) { if (res.Errors.Find(x => x.Code == ErrorMessageCode.UserIsNotActive) != null) { ViewBag.SetLink = "http://localhost:53605/Home/CustomerActivate/" + res.Result.ActivateGuid.ToString(); } res.Errors.ForEach(x => ModelState.AddModelError("", x.Message)); return(View(model)); } Session["login"] = res.Result; return(RedirectToAction("Index")); } return(View()); }
public JsonResult 會員登入(CustomerLoginViewModel c登入資料) { if (c登入資料.cValidateCode != null) { string code = c登入資料.cValidateCode; MotaiDataEntities dbContext = new MotaiDataEntities(); tCustomer d資料確認 = dbContext.tCustomers.FirstOrDefault (c => c.cAccount == c登入資料.cAccount && c.cPassword.Equals(c登入資料.cPassword)); if (d資料確認 != null) { if (code == TempData["codecode"].ToString()) { Session[CSession關鍵字.SK_LOGINED_CUSTOMER] = d資料確認; return(Json(new { result = true, msg = "登入成功", url = Url.Action("首頁", "Customer") })); } return(Json(new { result = false, msg = "驗證碼錯誤" })); } return(Json(new { result = false, msg = "帳號或密碼有誤" })); } return(Json(new { result = false, msg = "請輸入驗證碼" })); }
public ActionResult SendLogin(CustomerLoginViewModel model) { if (ModelState.IsValid) { var dao = new UserDAO(); var result = dao.Login(model.Username, model.Password); if (result) { var user = dao.GetByUsername(model.Username); var customerSession = new CustomerLogin(); customerSession.UserID = user.UserID; customerSession.UserName = user.UserName; Session.Add(CommonConstants.CUSTOMER_SESSION, customerSession); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError("", "Đăng nhập thất bại"); } } return(View("Login")); }
public ActionResult CustomerRegister(CustomerRegisterViewModel model) { if (Request.HttpMethod == "POST") { if (!string.IsNullOrEmpty(model.Password) && !string.IsNullOrEmpty(model.ConfirmPassword) && (model.Password == model.ConfirmPassword)) { if (!dB.tbl_KhachHang.Any(d => d.UserName == model.UserName)) { tbl_KhachHang addKhachHang = new tbl_KhachHang(); addKhachHang.FullName = model.FullName; addKhachHang.UserName = model.UserName; addKhachHang.Password = model.Password; addKhachHang.PhoneNumber = model.PhoneNumber; addKhachHang.DiaChi = model.DiaChi; dB.tbl_KhachHang.Add(addKhachHang); dB.SaveChanges(); //redirect to Login CustomerLoginViewModel login = new CustomerLoginViewModel(); login.UserName = model.UserName; login.Password = model.Password; return(RedirectToAction("CustomerLogin", "Account", login)); } else { model.Error = "Tài khoản đã tồn tại"; } } else { return(View()); } } return(View(model)); }
public async Task <IActionResult> CustomerLogin(CustomerLoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { string phone; if (!Utils.NormalizePhoneNumber(model.Phone, out phone)) { ModelState.AddModelError("", "Номер телефона указан не верно"); } else { Func <Customer, bool> findCustomer = (c) => { if (c.Phones.Any(x => !string.IsNullOrEmpty(x.Number))) { foreach (var p in c.Phones) { string normilized; if (Utils.NormalizePhoneNumber(p.Number, out normilized) && phone.Equals(normilized)) { return(true); } } } return(false); }; Customer dbCustomer = _context.Clients.Include(x => x.Phones).SingleOrDefault(x => findCustomer(x)); if (dbCustomer == null) { ModelState.AddModelError("", "Клиент с таким номером телефона не найден"); } else { var verifyCode = HttpContext.Session.GetString("CustomerSmsCode"); var verifyCodeTimeStampString = HttpContext.Session.GetString("CustomerSmsTimestamp"); DateTime verifyCodeTimeStamp; if (!DateTime.TryParse(verifyCodeTimeStampString, out verifyCodeTimeStamp) || verifyCodeTimeStamp.AddMinutes(5) <= DateTime.Now) { ModelState.AddModelError("", "Истек срок ожидания кода из смс, запросите новый код"); } else { if (verifyCode.Equals(model.SmsCode)) { var customerUser = CustomerUser.CreateInstance(); customerUser.CustomerId = dbCustomer.Id; customerUser.LoginTime = DateTime.Now; customerUser.Phone = model.Phone; customerUser.CustomerName = dbCustomer.MidleName + " " + dbCustomer.LastName; base.CustomerUser = customerUser; return(RedirectToLocal(returnUrl)); } else { ModelState.AddModelError("", "Код из смс введен не верно или истек срок ожидания, запросите новый код"); } } } } } return(View(model)); }