Пример #1
0
        public ActionResult SignIn(UserLoginVm userLoginVm)
        {
            if (userLoginVm == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            if (ModelState.IsValid)
            {
                UserEntity user = Mapper.Map <UserLoginVm, UserEntity>(userLoginVm);

                if (_userLogic.IsExists(user))
                {
                    FormsAuthentication.SetAuthCookie(user.Name, userLoginVm.RememberMe);

                    return(RedirectToAction("Index", "Product"));
                }
                else
                {
                    userLoginVm.IsExist = false;
                }
            }

            return(View(new UserAggregatedVm
            {
                LoginVm = userLoginVm
            }));
        }
Пример #2
0
        public async Task <IActionResult> Login(UserLoginVm userlogin)
        {
            try
            {
                var user = await _userManager.FindByEmailAsync(userlogin.Email);

                var result = await _signInManager.CheckPasswordSignInAsync(user, userlogin.Password, false);

                if (!result.Succeeded)
                {
                    return(Unauthorized());
                }

                var appUser = await _userManager.Users
                              .FirstOrDefaultAsync(u => u.NormalizedEmail == userlogin.Email.ToUpper());

                var userToReturn = _mapper.Map <UserLoginVm>(appUser);

                return(Ok(new {
                    token = GenerateJWToken(appUser).Result,
                    user = userToReturn
                }));
            }
            catch (System.Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Banco de dados falhou {ex.Message}"));
            }
        }
        public async Task <IActionResult> Login(UserLoginVm userLoginVm, string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(userLoginVm.UserName);

                if (user != null)
                {
                    await _signInManager.SignOutAsync();

                    var result = await _signInManager.PasswordSignInAsync(user, userLoginVm.Password,
                                                                          userLoginVm.RememberMe, false);

                    if (result.Succeeded)
                    {
                        ViewBag.returnUrl = returnUrl;
                        return(Redirect(returnUrl ?? "/"));
                    }
                }
            }

            return(View(userLoginVm));
        }
Пример #4
0
        public ActionResult Login(UserLoginVm vm)
        {
            UserModel user = new UserModel()
            {
                Email = vm.Email, Password = vm.Password
            };

            user        = userService.GetEmail(user.Email);
            vm.RoleName = user.RoleName;
            vm.UserId   = user.UserId;

            if (ModelState.IsValid && vm.Email == user.Email && CreatePasswordHash(vm.Password, user.VCode) == user.Password)
            {
                FormsAuthentication.SetAuthCookie(vm.Email, false);

                var    authTicket      = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(20), false, user.RoleName);
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpContext.Response.Cookies.Add(authCookie);

                if (vm.RoleName == "Admin")
                {
                    return(RedirectToAction("Admin", "Account", vm));
                }
                else
                {
                    return(RedirectToAction("Loggedin", "Address", vm));
                }
            }
            else
            {
                ModelState.AddModelError("", @"Invalid login attempt.");
                return(RedirectToAction("Register", "Account", vm));
            }
        }
Пример #5
0
        public async Task <IActionResult> Login([FromBody] UserLoginVm login)
        {
            User user = await _userManager.FindByNameAsync(login.UserName);

            if (user == null)
            {
                return(NotFound());
            }
            if (string.IsNullOrEmpty(user.PasswordHash))
            {
                await _signInManager.SignInAsync(user, true);

                return(Json(_mapper.Map <User, UserVm>(user)));
            }
            if (string.IsNullOrEmpty(login.Password))
            {
                return(Forbid());
            }
            SignInResult result = await _signInManager.PasswordSignInAsync(user, login.Password, true, false);

            if (!result.Succeeded)
            {
                return(Unauthorized());
            }
            return(Json(_mapper.Map <User, UserVm>(user)));
        }
Пример #6
0
        public ActionResult SignInForm(UserLoginVm userLoginVm)
        {
            ModelState.Clear();

            if (userLoginVm.IsExist.HasValue && !userLoginVm.IsExist.Value)
            {
                ModelState.AddModelError(string.Empty, "Incorrect login or password");
            }

            return(View("_SignInPartial", userLoginVm));
        }
Пример #7
0
        public async Task <IActionResult> UpdateUserName([FromBody] UserLoginVm newInfo)
        {
            User user = await _userManager.GetUserAsync(User);

            if (await _userManager.FindByNameAsync(newInfo.UserName) != null)
            {
                return(StatusCode(409));
            }
            user.UserName = newInfo.UserName;
            await _userManager.UpdateAsync(user);

            return(Json(_mapper.Map <User, UserVm>(user)));
        }
        public void LoginFail()
        {
            var clientRepository = new RepositoriesMock.ClientsRepositoryMock();
            var securityMock     = new SecurityMock.FormsAuthMock();

            UsersController controller = new UsersController(clientRepository, securityMock);

            UserLoginVm user = new UserLoginVm()
            {
                Email = "123456"
            };
            RedirectToRouteResult result = controller.Login(user) as RedirectToRouteResult;

            Assert.IsNull(result);
        }
        public void LoginOk()
        {
            var clientRepository = new RepositoriesMock.ClientsRepositoryMock();
            var securityMock     = new SecurityMock.FormsAuthMock();

            UsersController controller = new UsersController(clientRepository, securityMock);

            UserLoginVm user = new UserLoginVm()
            {
                Email = clientRepository.Clients[0].Email
            };
            RedirectToRouteResult result = controller.Login(user) as RedirectToRouteResult;

            Assert.IsNotNull(result);
            Assert.IsTrue(result.RouteValues.ContainsValue("Search"));
            Assert.IsTrue(result.RouteValues.ContainsValue("Clients"));
        }
Пример #10
0
        public async Task <IActionResult> UpdatePassword([FromBody] UserLoginVm newInfo)
        {
            User user = await _userManager.GetUserAsync(User);

            if (newInfo.Password == null)
            {
                user.PasswordHash = null;
            }
            else
            {
                PasswordHasher <User> hasher = new PasswordHasher <User>();
                user.PasswordHash = hasher.HashPassword(user, newInfo.Password);
            }
            await _userManager.UpdateAsync(user);

            return(Json(_mapper.Map <User, UserVm>(user)));
        }
Пример #11
0
        public ActionResult Login(UserLoginVm user)
        {
            if (ModelState.IsValid)
            {
                //Se valida que exista el usuario
                var userFind = this.clientsRepository.GetClients().Where(p => p.Email.ToUpper().Trim().Equals(user.Email.ToUpper().Trim())).FirstOrDefault();
                if (userFind != null)
                {
                    this.auth.SetAuthCookie(userFind.Name, false);
                    return(RedirectToAction("Search", "Clients"));
                }

                ModelState.AddModelError(nameof(user.Email), "Invalid Email");
            }

            return(View(user));
        }
Пример #12
0
        public async Task <HttpStatusCode> AuthenticateUser(UserLoginVm userLoginVm)
        {
            var user = await _userManager.FindByNameAsync(userLoginVm.UserName);

            if (user == null || !user.Active)
            {
                return(HttpStatusCode.Unauthorized);
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, userLoginVm.Password, true);

            if (result.Succeeded)
            {
                return(HttpStatusCode.OK);
            }

            return(result.IsLockedOut ? HttpStatusCode.Locked : HttpStatusCode.Unauthorized);
        }
Пример #13
0
        public async Task <string> GenerateToken(UserLoginVm userLoginVm)
        {
            var user = await _userManager.Users.FirstOrDefaultAsync(u => u.UserName == userLoginVm.UserName);

            await _userManager.UpdateAsync(user);

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email)
            };
            var userRoles = await _userManager.GetRolesAsync(user);

            foreach (var userRole in userRoles)
            {
                var role = await _roleManager.FindByNameAsync(userRole);

                claims.Add(new Claim(ClaimTypes.Role, role.Name));
                var userRoleClaims = await _roleManager.GetClaimsAsync(role);

                foreach (var item in userRoleClaims)
                {
                    if (claims.Any(x => x.Value == item.Value))
                    {
                        continue;
                    }
                    claims.Add(new Claim(item.Type, item.Value));
                }
            }
            var secretKey          = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Security:SecretKeyJWT"]));
            var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor    = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddDays(2),
                SigningCredentials = signingCredentials
            };
            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Пример #14
0
        public IActionResult Index(UserLoginVm vm)
        {
            if (ModelState.IsValid)
            {
                vm.Password = GetPasswordHash(vm.Password);

                using (var context = new DegreePlannerContext()) {
                    User user = context.Users.FirstOrDefault(u => u.Username == vm.Username && u.Password == vm.Password);
                    if (user != null)
                    {
                        HttpContext.Session.SetInt32(USERNAME, user.UserID);
                        return(RedirectToAction("Index", "Planner"));
                    }
                    else
                    {
                        vm.Message = "Incorrect username or password";
                    }
                }
            }
            return(View(vm));
        }
Пример #15
0
        public async Task <IActionResult> Login(UserLoginVm userLoginVm)
        {
            _logger.LogInformation(string.Format($"{nameof(Login)} iniciado pelo usuário {userLoginVm.UserName}"));

            var isValidUser = await _accountService.AuthenticateUser(userLoginVm);

            if (isValidUser != HttpStatusCode.OK)
            {
                if (isValidUser.Equals(HttpStatusCode.Locked))
                {
                    _logger.LogWarning(string.Format(Messages.UserInvalidLockedLogin));
                    return(BadRequest(new { error = string.Format(Messages.UserInvalidLockedLogin) }));
                }

                _logger.LogWarning(string.Format(Messages.UserInvalidToLogin, userLoginVm.UserName, userLoginVm.Password));
                return(BadRequest(new { error = string.Format(Messages.UserInvalidToLogin, userLoginVm.UserName, userLoginVm.Password) }));
            }

            var tokenResult = await _accountService.GenerateToken(userLoginVm);

            _logger.LogInformation(string.Format($"{nameof(Login)} finalizado"));
            return(Ok(tokenResult));
        }
Пример #16
0
        public async Task <User> Login(UserLoginVm loginVm)
        {
            try
            {
                new MailAddress(loginVm.Email);
            }
            catch
            {
                throw new ArgumentException("Value has a invalid format.", nameof(loginVm.Email));
            }

            if (string.IsNullOrWhiteSpace(loginVm.Password))
            {
                throw new ArgumentException("Value can't be null or empty.", nameof(loginVm.Password));
            }

            var user = await _userManager.FindByEmailAsync(loginVm.Email);

            if (user == null)
            {
                throw new UnauthorizedAccessException("User doesn't exist.");
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, loginVm.Password, false);

            if (result.Succeeded)
            {
                return(new User()
                {
                    Email = user.Email,
                    Username = user.UserName,
                    Token = _jwtGenerator.CreateToken(user)
                });
            }

            throw new UnauthorizedAccessException("Password is invalid.");
        }
Пример #17
0
 public async Task <ActionResult <User> > Login(UserLoginVm loginVm)
 {
     return(await _userService.Login(loginVm));
 }