Esempio n. 1
0
        public IActionResult Login(LoginCustomerViewModel loginCustomerViewModel)
        {
            //Customer c = new Customer(fName: loginCustomerViewModel.FName, lName: loginCustomerViewModel.LName, userName: loginCustomerViewModel.UserName);
            //things to do to log in...
            //use DI (dependency injection!) to get instance of customer class
            //and access to its functionality


            //LoginCustomerViewModel loginCustomerViewModel = _businessLogicCLass.LoginCustomer();
            //return View("DisplayCustomerDetails");//, c);

            CustomerViewModel customerViewModel = _businessLogicClass.LoginCustomer(loginCustomerViewModel);

            //return View("DisplayCustomerDetails", customerViewModel);
            if (customerViewModel != null)
            {
                return(View("DisplayCustomerDetails", customerViewModel));
            }
            else
            {
                ModelState.AddModelError("Failure", "Did not find that username. Redirected you to register");
                //System.Threading.Thread.Sleep(2000);
                return(View("../Register/Register"));
                //return View("Register");
            }
        }
Esempio n. 2
0
        public async Task <IActionResult> Login(LoginCustomerViewModel 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
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("Người dùng đã đăng nhập.");
                    return(RedirectToLocal(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("Tài khoản đã khóa.");
                    return(RedirectToAction(nameof(Lockout)));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Đăng nhập không hợp lệ.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Esempio n. 3
0
    public async Task <IActionResult> Login(LoginCustomerViewModel loginCustomerViewModel)
    {
        if (!ModelState.IsValid)
        {
            return(View(loginCustomerViewModel));
        }

        var result = await _signInManager.PasswordSignInAsync(loginCustomerViewModel.Email,
                                                              loginCustomerViewModel.Password, loginCustomerViewModel.RememberMe,
                                                              false);

        if (result.Succeeded)
        {
            var user = await _userManager.FindByEmailAsync(loginCustomerViewModel.Email);

            if (user == null)
            {
                return(RedirectToAction(IndexAction, DefaultController));
            }
            var checkForReliability = DateTimeOffset.Now - user.CreationTime;
            _customerService.TryUpdateCustomerStatus(user.CustomerDbModelId, checkForReliability.Days);

            return(RedirectToAction(IndexAction, DefaultController));
        }

        ModelState.AddModelError(string.Empty, "Invalid Credentials");

        return(View(loginCustomerViewModel));
    }
Esempio n. 4
0
        public async Task <UserManagerResponse> LoginCustomerAsync(LoginCustomerViewModel 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);

            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 IActionResult Register(LoginCustomerViewModel loginCustomerViewModel)
        {
            if (loginCustomerViewModel.UserName == null)
            {
                return(View());
            }

            CustomerViewModel customerViewModel = _businessLogicClass.RegisterCustomer(loginCustomerViewModel);

            return(View("DisplayCustomerDetails", customerViewModel));
        }
Esempio n. 6
0
        public IActionResult LoginCustomer(LoginCustomerViewModel loginCustomerViewModel)
        {
            if (ModelState.IsValid)
            {
                loginCustomerViewModel.UserName = loginCustomerViewModel.UserName.Trim();
                loginCustomerViewModel.Password = loginCustomerViewModel.Password.Trim();
                var account = Mapper.Map <LoginCustomerViewModel, Account>(loginCustomerViewModel);
                if (this.AccountService.Verify(account))
                {
                    var customer = this.CustomerService.GetByUserName(account.UserName);
                    if (customer != null && customer.Account.Role.RoleName == StaticValue.StaticValue.PERMISSION_CUSTOMER)
                    {
                        SessionModel session = HttpContext.Session.GetSession("session");
                        List <ProductInSessionModel> products = session.Products ?? new List <ProductInSessionModel>();
                        HttpContext.Session.Clear();

                        //if (session != null)
                        //{
                        //    session.CustomerName = customer.Name;
                        //    session.CustomerId = customer.Id;
                        //}
                        //else
                        //{
                        //    session = new SessionModel();
                        //}
                        //HttpContext.Session.SetSession("sessionStaff", null);
                        HttpContext.Session.SetSession("session", new SessionModel
                        {
                            Products     = products,
                            CustomerId   = customer.Id,
                            CustomerName = customer.Name
                        });
                        HttpContext.Session.SetString("permission", customer.Account.Role.RoleName);
                        return(RedirectToAction("HomePage", "Product"));
                    }
                    else
                    {
                        ModelState.AddModelError("Password", "Tên tài khoản hoặc mật khẩu không đúng!");
                        return(View(loginCustomerViewModel));
                    }
                }
                else
                {
                    ModelState.AddModelError("Password", "Tên tài khoản hoặc mật khẩu không đúng!");
                    return(View(loginCustomerViewModel));
                }
            }
            else
            {
                return(View(loginCustomerViewModel));
            }
        }
Esempio n. 7
0
        public async Task <ActionResult> LoginCustomer(LoginCustomerViewModel model, string returnUrl)
        {
            // Lets first check if the Model is valid or not
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //await _serverUserCollection.GetUserTokenAsync(model.Email, model.Password);
            //AdminUser serviceUser = await _serverUserCollection.getCustomerAsync();
            CompanyUser companyUser = new CompanyUser();


            companyUser = await _companyUserCollection.Login(model.Email, model.Password, model.pin);

            //TODO: add function for when pin is filled in.

            if (companyUser == null)
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return(View(model));
            }


            //INFO: Claims are use to specify properties of an Identity(a user)
            List <Claim> claims = null;

            if ((companyUser != null))
            {
                claims = new List <Claim>
                {
                    new Claim("Name", companyUser.Name),
                    new Claim("CompanyId", companyUser.CompanyId.ToString()),
                    new Claim("Role", Role.User.ToString()),
                    new Claim("Email", companyUser.Mail),
                    new Claim(ClaimTypes.Role, Role.User)
                };
            }

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authProperties = new AuthenticationProperties();

            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(claimsIdentity),
                authProperties);

            return(LocalRedirect(returnUrl));
        }
Esempio n. 8
0
        public CustomerViewModel RegisterCustomer(LoginCustomerViewModel viewModel)
        {
            Customer c = new Customer()
            {
                FName    = viewModel.FName,
                LName    = viewModel.LName,
                UserName = viewModel.UserName,
                Store    = viewModel.Store
            };
            Customer c1 = _repository.RegisterCustomer(c);

            CustomerViewModel customerViewModel = _mapperClass.ConvertCustomerToCustomerViewModel(c1);

            return(customerViewModel);
        }
        public async Task <IActionResult> LoginCustomer(LoginCustomerViewModel loginViewModel)
        {
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(loginViewModel.Name,
                                                                      loginViewModel.Password, loginViewModel.RememberMe, false);

                if (result.Succeeded)
                {
                    return(RedirectToAction("GetAllProducts", "Product"));
                }
                ModelState.AddModelError("", "Login hatası");
            }
            return(View(loginViewModel));
        }
Esempio n. 10
0
        public async Task <IActionResult> LoginCustomerAsync([Microsoft.AspNetCore.Mvc.FromBody] LoginCustomerViewModel model)
        {
            if (ModelState.IsValid && validateCustomerWithEmail(model.Email))
            {
                var result = await _customerService.LoginCustomerAsync(model);

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

                return(Unauthorized(result));
            }

            return(Unauthorized("Some properties are not Valid"));
        }
Esempio n. 11
0
        public IActionResult LoginStaff(LoginCustomerViewModel loginCustomerViewModel)
        {
            if (ModelState.IsValid)
            {
                loginCustomerViewModel.UserName = loginCustomerViewModel.UserName.Trim();
                loginCustomerViewModel.Password = loginCustomerViewModel.Password.Trim();

                var account = Mapper.Map <LoginCustomerViewModel, Account>(loginCustomerViewModel);
                if (this.AccountService.Verify(account))
                {
                    var staff = this.StaffService.GetByUserName(account.UserName);
                    if (staff != null)
                    {
                        SessionStaffModel session = HttpContext.Session.GetStaffSession("sessionStaff");
                        if (session == null)
                        {
                            session = new SessionStaffModel();
                        }
                        session.StaffName = staff.Name;
                        session.StaffId   = staff.Id;
                        //HttpContext.Session.SetSession("session", null);
                        HttpContext.Session.SetSession("sessionStaff", session);
                        HttpContext.Session.SetString("permission", staff.Account.Role.RoleName);
                        return(RedirectToAction("Index", "Staff"));
                    }
                    else
                    {
                        ModelState.AddModelError("Password", "Tên tài khoản hoặc mật khẩu không đúng!");
                        return(View(loginCustomerViewModel));
                    }
                }
                else
                {
                    ModelState.AddModelError("Password", "Tên tài khoản hoặc mật khẩu không đúng!");
                    return(View(loginCustomerViewModel));
                }
            }
            else
            {
                return(View(loginCustomerViewModel));
            }
        }
Esempio n. 12
0
        public IActionResult Login(LoginCustomerViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }


            var dataManager = new DataManager(context);

            HttpContext.Authentication.SignOutAsync("Cookies");
            var a = dataManager.GetCustomer(viewModel.Email, viewModel.Password);

            if (a != null && a.Length > 0)
            {
                var s     = new Claim("FirstName", a.First().FirstName);
                var newId = new ClaimsIdentity("application", "name", "role");

                newId.AddClaim(new Claim("FirstName", a.First().FirstName));
                newId.AddClaim(new Claim("Email", a.First().Email));
                newId.AddClaim(new Claim("Id", a.First().Id.ToString()));

                HttpContext.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(newId));

                Response.Cookies.Append("Email", a.First().Email);
                Response.Cookies.Append("FirstName", a.First().FirstName);
                Response.Cookies.Append("Id", a.First().Id.ToString());

                var isAdmin = dataManager.GetAdminAccess(a.First().Id);
                if (isAdmin)
                {
                    Response.Cookies.Append("Admin", "true");
                }
                return(RedirectToAction(nameof(CustomersController.MyPages)));
            }
            //var x = dataManager.GetCustomer(1);
            //return RedirectToAction(nameof(CustomersController.Index));
            return(View(viewModel));
            //return RedirectToAction(Index());
        }
Esempio n. 13
0
 public IActionResult Login(LoginCustomerViewModel model)
 {
     if (ModelState.IsValid)
     {
         bool checkLogin = _customerService.CheckLogin(model.Email, model.Password);
         if (checkLogin)
         {
             var customerObj = _customerService.GetSingleByEmail(model.Email);
             HttpContext.Session.SetObject(key, customerObj);
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             ModelState.AddModelError("", "Sai email hoặc mật khẩu");
         }
     }
     else
     {
         ModelState.AddModelError("", "Đăng nhập không thành công");
     }
     return(View("Login"));
 }