public async Task <IActionResult> Login(LoginAccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppIdentityUser userLogin = await _userManager.FindByEmailAsync(model.Email);

                if (userLogin == null)
                {
                    return(NotFound());
                }
                var result = await _signInManager.PasswordSignInAsync(user : userLogin,
                                                                      password : model.Password,
                                                                      isPersistent : model.IsRemember,
                                                                      lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    if (!String.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    return(RedirectToAction(actionName: "Index", controllerName: "Home"));
                }
                ModelState.AddModelError("", "Something was wrong, please check again");
            }
            return(View(model));
        }
Beispiel #2
0
        public async Task <ActionResult> Login(LoginAccountViewModel loginAccount)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(e => e.Errors)));
            }

            var result = await _signInManager.PasswordSignInAsync(loginAccount.Email, loginAccount.Password, false, true);

            if (!result.Succeeded)
            {
                return(BadRequest("Usuário ou senha inválidos"));
            }

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

            var token = await GenerateJwt(loginAccount.Email);

            var userObj = new
            {
                token,
                user = new
                {
                    user.UserName,
                    user.Email,
                    user.Id
                }
            };

            return(Ok(userObj));
        }
        public ActionResult Login(LoginAccountViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var response = _membershipService.LoginUser(model.ConvertToLoginUserRequest());

            if (!response.HasIssues && response.UserLogin.IsAuthenticated)
            {
                var authCookie = SetLoginCookie(response);

                Response.Cookies.Add(authCookie);

                return(RedirectToLocal(returnUrl));
            }

            model.HasIssues = true;

            model.ErrorMessage = !string.IsNullOrEmpty(response.ErrorMessage)
                ? response.ErrorMessage
                : "Sorry we could not authenticate you.  Please try again.";

            return(View(model));
        }
        public async Task <IActionResult> Login([FromBody] LoginAccountViewModel model)
        {
            var targetAccount = accountRepository.GetByUserName(model.Username);

            if (targetAccount == null)
            {
                return(BadRequest("Le compte n'existe pas."));
            }

            var hasher = new PasswordHasher <Account>();
            var result = hasher.VerifyHashedPassword(targetAccount, targetAccount.PasswordHash, model.Password);

            if (result != PasswordVerificationResult.Success)
            {
                return(BadRequest("Mot de passe incorrect."));
            }

            await accountRepository.LogIn(targetAccount);

            LoginAccountViewModel dd = new LoginAccountViewModel();

            dd.Username = model.Username;
            dd.Password = model.Password;

            return(Ok(dd));
        }
Beispiel #5
0
        public async Task <IActionResult> Login(LoginAccountViewModel model)
        {
            HttpClient client = _client.Initiale();

            client.DefaultRequestHeaders.Accept.Clear();
            var response = await client.PostAsJsonAsync("https://comptes-api.azurewebsites.net/api/ComptesAPI/Login", model);



            if (response.IsSuccessStatusCode)
            {
                var claims = new List <Claim>();
                claims.Add(new Claim(ClaimTypes.Name, model.Username));


                var claimsIdentity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                try
                {
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
                }
                catch (Exception ex)
                {
                }
                return(RedirectToAction("Index"));
            }
            return(View());
        }
        public async Task <IActionResult> Login(LoginAccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(model.UserName);

                if (user != null)
                {
                    if (user.IsActive)
                    {
                        var result = await _signInManager.PasswordSignInAsync(user, model.Password, isPersistent : model.IsRemember, lockoutOnFailure : false);

                        if (result.Succeeded)
                        {
                            if (await _userManager.IsInRoleAsync(user, "Lái xe"))
                            {
                                return(RedirectToAction(actionName: "Mobile", controllerName: "Home", new { area = "Driver" }));
                            }
                            return(RedirectToAction(actionName: "Index", controllerName: "Home"));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Tài khoản đã bị khóa");
                        return(View(model));
                    }
                }
            }
            ModelState.AddModelError("", "Đăng nhập không thành công, xin mời kiểm tra lại");
            return(View(model));
        }
Beispiel #7
0
        public async Task <IActionResult> Find([FromBody] LoginAccountViewModel model)
        {
            IActionResult res  = Unauthorized();
            var           user = await _accountService.FindUser(model);

            return(Ok(user));
        }
        public async Task AutologinUserAsync(RegisterAccountViewModel model)
        {
            var loginModel = new LoginAccountViewModel();

            loginModel.Email    = model.Email;
            loginModel.Password = model.Password;
            await GetUserAsync(loginModel);
        }
 public LoginPage(User CurrentUser = null)
 {
     InitializeComponent();
     BindingContext = viewModel = new LoginAccountViewModel();
     userManager    = UserManager.DefaultManager;
     if (CurrentUser != null)
     {
         viewModel.MailAdress = CurrentUser.MailAdress;
     }
 }
        public async Task GetUserAsync(LoginAccountViewModel model)
        {
            var url         = "/Account/login";
            var json        = JsonConvert.SerializeObject(model);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            var response    = await _httpService.ExecuteQuery(url, HttpOperationMode.POST, httpContent);

            var testToken = await _httpService.ProcessToken(response);

            CrossSecureStorage.Current.SetValue("securityToken", testToken);
        }
Beispiel #11
0
        public async Task <IActionResult> Login([FromBody] LoginAccountViewModel model)
        {
            IActionResult res   = Unauthorized();
            var           token = await _accountService.SignIn(model);

            if (token != null)
            {
                return(Ok(token));
            }
            return(res);
        }
        public async Task <EditAccountViewModel> GetUserInfo(LoginAccountViewModel model)
        {
            var url         = "/Account/getInfo";
            var json        = JsonConvert.SerializeObject(model);
            var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
            var response    = await _httpService.ExecuteQuery(url, HttpOperationMode.POST, httpContent);

            var parsedResult = await _httpService.ProcessJson <EditAccountViewModel>(response);

            return(parsedResult);
        }
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;

            var model = new LoginAccountViewModel
            {
                HasIssues    = false,
                ErrorMessage = string.Empty
            };

            return(View(model));
        }
Beispiel #14
0
        public async Task<TokenResult> GetAccessToken(LoginAccountViewModel userInfo)
        {
            var user = await GetUserByUserNameOrEmail(userInfo);
            if (user == null)
            {
                return new TokenResult(null);
            }

            UpdateUserStatus(user, UserAvailabilityStatus.Online);
            var userRole = await GetFirstUserRole(user);
            var identity = GetIdentity(user, userRole);
            var token = TokenGenerator.GenerateSecurityToken(identity);
            return new TokenResult(user, userRole, token);
        }
Beispiel #15
0
        public async Task <EditAccountViewModel> FindUser(LoginAccountViewModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            var editUser = new EditAccountViewModel();

            editUser.Email     = user.Email;
            editUser.FirstName = user.FirstName;
            editUser.LastName  = user.LastName;
            editUser.UserImage = user.UserImage;
            if (user == null)
            {
                throw new ApplicationException("User is not found.");
            }
            return(editUser);
        }
Beispiel #16
0
        public async void Task_Login_BadRequestResult()
        {
            //Arrange
            var    controller = new ComptesAPIController(repository);
            string username   = RandomString(7);
            var    account    = new LoginAccountViewModel()
            {
                Username = "******",
                Password = "******",
            };

            //Act
            var data = await controller.Login(account);

            //Assert
            Assert.IsType <BadRequestObjectResult>(data);
        }
        public async Task <IActionResult> Login([FromBody] LoginAccountViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

            if (!result.Succeeded)
            {
                return(BadRequest(Errors.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState)));
            }
            User user = await _userManager.FindByEmailAsync(model.Email);

            var isAdmin = await _userManager.IsInRoleAsync(user, Roles.Admin.ToString().ToLower());

            return(Ok(isAdmin));
        }
Beispiel #18
0
        public async Task <IActionResult> Login([FromBody] LoginAccountViewModel model)
        {
            try
            {
                var result = await _accountServise.Login(model);

                return(Ok(result));
            }
            catch (BusinessLogicException exception)
            {
                return(BadRequest(exception.Message));
            }
            catch (Exception exception)
            {
                _logger.LogInformation(exception.Message);
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
Beispiel #19
0
        public async Task <ResponseLoginAccount> Login(LoginAccountViewModel model)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

            if (!result.Succeeded)
            {
                throw new BusinessLogicException("Wrong login or password");
            }

            User user  = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
            var  token = GenerateJwtToken(model.Email, user);

            var roleToken = new ResponseLoginAccount()
            {
                Role  = user.Role,
                Token = token
            };

            return(roleToken);
        }
Beispiel #20
0
        public async Task <string> SignIn(LoginAccountViewModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                throw new ApplicationException("User is not found.");
            }

            var isEmailConfirm = await _userManager.IsEmailConfirmedAsync(user);

            if (!isEmailConfirm)
            {
                throw new ApplicationException("Email is not confirmed");
            }

            var token = await GetToken(user);

            return(token);
        }
Beispiel #21
0
        public async Task <IActionResult> Create(RegisterAccountViewModel model)
        {
            HttpClient client = _client.Initiale();

            client.DefaultRequestHeaders.Accept.Clear();
            var response = await client.PostAsJsonAsync("https://comptes-api.azurewebsites.net/api/ComptesAPI/AddAccount", model);

            if (response.IsSuccessStatusCode)
            {
                LoginAccountViewModel loginModel = new LoginAccountViewModel();
                loginModel.Username = model.Username;
                loginModel.Password = model.Password;
                response            = await client.PostAsJsonAsync("https://comptes-api.azurewebsites.net/api/ComptesAPI/Login", loginModel);

                if (response.IsSuccessStatusCode)
                {
                    return(RedirectToAction("Index"));
                }
            }

            return(BadRequest());
        }
 public static LoginUserRequest ConvertToLoginUserRequest(this LoginAccountViewModel model)
 {
     return(Mapper.Map <LoginAccountViewModel, LoginUserRequest>(model));
 }
Beispiel #23
0
        public ActionResult Login(LoginAccountViewModel account)
        {
            IAuthenticated authenticated = null;

            if (ModelState.IsValid)
            {
                RestClient client = RemoteConfig.Client;

                RestRequest request = RemoteConfig.AUTHENTICATE.Request;
                request.AddParameter("email", account.Email);
                request.AddParameter("password", account.Password);

                IRestResponse response = client.Execute(request);

                try
                {
                    JObject jObject = JObject.Parse(response.Content);
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        String token = (String)jObject["token"];

                        request = RemoteConfig.USER.Request;
                        request.AddHeader("Authorization", $"JWT {token}");
                        response = client.Execute(request);

                        try
                        {
                            jObject = JObject.Parse(response.Content);

                            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                JToken jToken = jObject["user"];
                                authenticated = new AuthUser(new User
                                {
                                    Id        = (String)jToken["_id"],
                                    FirstName = (String)jToken["firstName"],
                                    LastName  = (String)jToken["lastName"],
                                    Email     = (String)jToken["email"],
                                    // TODO createdAt, convert string to date
                                }, token);
                            }
                        }
                        catch
                        {
                            Debug.WriteLine("exception");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("password", (String)jObject["message"]);
                    }
                }
                catch
                {
                    ModelState.AddModelError("password", "Unable issue the server for authentication");
                }
            }

            if (authenticated != null)
            {
                Session[Reference.KEY_USER_SESSION] = authenticated as IAuthenticated;

                return(RedirectToAction("Index", "Default"));
            }

            return(View());
        }
Beispiel #24
0
 public async Task <TokenResult> GetAccessToken([FromBody] LoginAccountViewModel model)
 {
     return(await userService.GetAccessToken(model));
 }
Beispiel #25
0
 private async Task<User> GetUserByUserNameOrEmail(LoginAccountViewModel userInfo)
 {
     var user = await userManager.FindByEmailAsync(userInfo.Login);
     return user ?? await userManager.FindByNameAsync(userInfo.Login);
 }