public async Task LogInPost_ReturnRedirectToActionHomeIndex()
        {
            // Arrange
            LogInViewModel newLogInVM = new LogInViewModel();

            // mocking UserManager
            var mockUserManager = MockHelpers.MockUserManager <ApplicationUser>();

            // mocking SignInManager
            var contextAccessor      = new Mock <IHttpContextAccessor>();
            var userPrincipalFactory = new Mock <IUserClaimsPrincipalFactory <ApplicationUser> >();
            var mockSignInManager    = new Mock <SignInManager <ApplicationUser> >(mockUserManager.Object,
                                                                                   contextAccessor.Object, userPrincipalFactory.Object, null, null, null, null);

            mockSignInManager.Setup(sim => sim.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), false))
            .ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success)
            .Verifiable();

            var controller = new AccountController(mockUserManager.Object, mockSignInManager.Object);

            // Act
            var result = await controller.LogIn(newLogInVM);

            // Assert
            var requestResult = Assert.IsType <RedirectToActionResult>(result);

            Assert.Equal("Index", requestResult.ActionName);
            Assert.Equal("Home", requestResult.ControllerName);
            mockSignInManager.Verify(x => x.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), false), Times.Once);
        }
Exemple #2
0
        //log in a user
        //this is most likely use for api call
        public async Task <UserViewModel> LogIn(LogInViewModel viewModel)
        {
            //check for user
            var user = await _userManager.FindByEmailAsync(viewModel.UserName);

            //user does not exist
            if (user == null)
            {
                throw new NullReferenceException("Invalid user name or password");
            }

            //user exist
            //validate username with password
            var result = await _userManager.CheckPasswordAsync(user, viewModel.Password);

            var tokenGenerator = new JWTTokenGenerator(this._config, user);

            //password match
            if (result)
            {
                return(new UserViewModel
                {
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    UserName = user.Email,
                    IsUserVerify = user.EmailConfirmed,
                    Token = tokenGenerator.Token
                });
            }
            throw new InvalidOperationException("Invalid user name or password");
        }
Exemple #3
0
        public async Task <IActionResult> Login(LogInViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(viewModel.UserName, viewModel.Password, true, false);

                var isInRole = await userManager.IsInRoleAsync(
                    await userManager.FindByNameAsync(
                        viewModel.UserName), "ActiveUser");

                if (result.Succeeded && isInRole)
                {
                    var a = userManager.GetUserId(HttpContext.User);
                    return(RedirectToAction("Index", "Dashboard"));
                }
                if (result.Succeeded && !isInRole)
                {
                    ModelState.AddModelError("", "Jesteś zablokowany!");
                }
                else
                {
                    ModelState.AddModelError("", "Nie można się zalogować!");
                }
            }

            return(View(viewModel));
        }
Exemple #4
0
        public ActionResult LogIn(LogInViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                using (ApplicationDbContext db = new ApplicationDbContext())
                {
                    String  lPasswordHash    = Security.ByteArrayToHex(Security.SHACngHash(model.Password, 256), true);
                    Account lExistingAccount = db.Account.Where(x => x.Email == model.Email && x.Password == lPasswordHash).FirstOrDefault();
                    if (lExistingAccount != null)
                    {
                        db.Account.Attach(lExistingAccount);
                        lExistingAccount.LastLogin = DateTime.UtcNow;
                        db.SaveChanges();

                        Runtime.Account = lExistingAccount;
                    }
                    else
                    {
                        this.ModelState.AddModelError("", "Email does not exist or password is incorrect.");
                    }
                }

                if (Runtime.Account != null)
                {
                    return(RedirectToAction("Index", "Manage"));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <IActionResult> CheckIn(LogInViewModel model)
        {
            var user = AutheticationService.CheckPassword(model.Email, model.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim("AuthorizedPersonType", user.AuthorizedPersonType.ToString()),
            };

            if (user.AuthorizedPersonType == Data.AuthorizedPersonType.Guest)
            {
                claims.Add(new Claim("RoomNumber", new Random().Next(10, 55).ToString()));
            }

            var identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal
                                          , new AuthenticationProperties { IsPersistent = model.RememberLogin });

            return(LocalRedirect(model.ReturnUrl));
        }
Exemple #6
0
 public IActionResult LogIn(LogInViewModel logIn)
 {
     if (ModelState.IsValid)
     {
         var user = _authRepository.Login(logIn.Email, logIn.Password);
         user.Status = true;
         if (user != null)
         {
             user.Token = Guid.NewGuid().ToString();
             _authRepository.UpdateToken(user.Id, user.Token);
             Response.Cookies.Delete("token");
             Response.Cookies.Append("token", user.Token, new Microsoft.AspNetCore.Http.CookieOptions
             {
                 HttpOnly = true,
                 Expires  = DateTime.Now.AddYears(1)
             });
             Request.Cookies.TryGetValue("token", out string token);
             _basketRepository.UpdateBasketsToken(token, user.Token);
             return(RedirectToAction("Index", "home"));
         }
         ModelState.AddModelError("Login.Password", "Wrong Email or Password");
     }
     return(View("~/Views/Account/LogIn.cshtml", new AccountViewModel {
         LogIn = logIn
     }));
 }
Exemple #7
0
        public ActionResult LogIn(LogInViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    var currentUser = userService.Get(u => u.Email == model.UserName);

                    FormsAuthentication.SetAuthCookie(currentUser.Email, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        if (currentUser is Admin)
                        {
                            return(RedirectToAction("UserList", "Admin"));
                        }

                        return(RedirectToAction("Account", "User"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return(View(model));
        }
Exemple #8
0
 public ActionResult UserLogin([Bind(Include = "UserCodeName,Password")] LogInViewModel logInViewModel)
 {
     if (ModelState.IsValid)
     {
         var Account = db.Users.FirstOrDefault(x => x.UserName == logInViewModel.UserCodeName);
         if (Account == null)
         {
             TempData["Error"] = "登入失敗";
             return(View("UserLogin"));
         }
         string Password = Utility.GenerateHashWithSalt(logInViewModel.Password, Account.PasswordSalt);
         if (Account.Password != Password)
         {
             TempData["Error"] = "登入失敗";
             return(View("UserLogin"));
         }
         Account.NumberOfLogins  = Account.NumberOfLogins + 1;
         db.Entry(Account).State = EntityState.Modified;
         db.SaveChanges();
         string userDate = JsonConvert.SerializeObject(Account);
         Utility.SetAuthenTicket(userDate, Account.UserCodeName);
         return(RedirectToAction("Index", "Home"));
     }
     return(View(logInViewModel));
 }
        public ActionResult Register(LogInViewModel logInViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            if (!this._accountService.IsReaderExist(logInViewModel.Email))
            {
                this._accountService.Create(new Reader {
                    Email = logInViewModel.Email
                });
                var identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.Role, "reader"),
                    new Claim(ClaimTypes.Email, logInViewModel.Email)
                }, "ApplicationCookie");

                var ctx         = Request.GetOwinContext();
                var authManager = ctx.Authentication;

                authManager.SignIn(identity);

                return(Redirect(GetRedirectUrl(logInViewModel.ReturnUrl)));
            }
            else
            {
                ModelState.AddModelError("", "This email already in use.");
                return(View(logInViewModel));
            }
        }
        public async Task<IActionResult> LogInAsync(LogInViewModel logInViewModel)
        {
            if (!ModelState.IsValid)
            {
                return View(nameof(LogIn), logInViewModel);
            }

            var query = new CanUserSignInQuery
            {
                Email = logInViewModel.Email,
                Password = logInViewModel.Password
            };

            var result = await _mediator.Send(query);

            if (result.Failure)
            {
                ModelState.AddModelError(string.Empty, result.Error);

                return View(nameof(LogIn), logInViewModel);
            }

            await SignInUserAsync(result.Value);

            return RedirectToAction("Index", "Home");
        }
Exemple #11
0
        public async Task <Status> LogMeIn(LogInViewModel logInView)
        {
            var responce     = JsonConvert.DeserializeObject <Results <CustomeSignInResult> >(await _requestManger.PostRequest($"{WebSitesUrls.EndPoient}api/Authentication/Login", logInView));
            var returnobject = new Status()
            {
                Error   = new List <string>(),
                Success = true
            };

            if (responce.Success)
            {
                _httpContextAccessor.HttpContext.Response.Cookies.Append(".AspUser",
                                                                         _dataProtectionProvider.CreateProtector(_configuration["dataprotector"]).Protect(responce.Result.Token),
                                                                         new CookieOptions()
                {
                    Expires = DateTime.Now.AddDays(.6)
                });
                return(returnobject);
            }

            foreach (var err in responce.Result.Errors)
            {
                returnobject.Error.Add(err.Description);
            }
            returnobject.Success = false;
            returnobject.Error.Add(responce.Exception);
            return(returnobject);
        }
Exemple #12
0
        public JsonResult LogIn(LogInViewModel model)
        {
            ControlUsuario cu   = new ControlUsuario();
            var            user = cu.GetUsuarioByCuenta(model.User, model.Password);

            string[] array = new string[3];
            if (user != null)
            {
                var accesoApp = ControlAcceso.AccesoAplicacion(Aplicacion.Notificaciones, user);
                if (accesoApp)
                {
                    SessionHelpers.IniciarSession(user.Usuario, user.IdUsuario.ToString());
                    Session["usuario"] = user;
                    array[0]           = "1";
                    array[1]           = user.Nombres;
                    array[2]           = user.ApPaterno;
                }
                else
                {
                    array[0] = "2"; //no tiene acceso a la app
                }
            }
            else
            {
                array[0] = "3"; //las credenciales no están bien
            }
            return(Json(array, JsonRequestBehavior.AllowGet));
        }
Exemple #13
0
        public async Task <ActionResult> LogIn(LogInViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Exemple #14
0
        public LogInPage()
        {
            InitializeComponent();

            viewModel      = new LogInViewModel();
            BindingContext = viewModel;
        }
        public async Task LogInPost_ReturnLoginViewOnModelIsInvalid()
        {
            // Arrange
            LogInViewModel newLogInVM = new LogInViewModel();

            // mocking UserManager
            var mockUserManager = MockHelpers.MockUserManager <ApplicationUser>();

            // mocking SignInManager
            var contextAccessor      = new Mock <IHttpContextAccessor>();
            var userPrincipalFactory = new Mock <IUserClaimsPrincipalFactory <ApplicationUser> >();
            var mockSignInManager    = new Mock <SignInManager <ApplicationUser> >(mockUserManager.Object,
                                                                                   contextAccessor.Object, userPrincipalFactory.Object, null, null, null, null);

            mockSignInManager.Setup(sim => sim.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), false))
            .ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success)
            .Verifiable();

            var controller = new AccountController(mockUserManager.Object, mockSignInManager.Object);

            controller.ModelState.AddModelError("Email", "Required");

            // Act
            var result = await controller.LogIn(newLogInVM);

            // Assert
            var requestResult = Assert.IsType <ViewResult>(result);

            Assert.Equal("LogIn", requestResult.ViewName);
            mockSignInManager.Verify(x => x.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), false), Times.Never);
        }
        public async Task LogInPost_ReturnErrorViewOnSignInThrowError()
        {
            // Arrange
            LogInViewModel newLogInVM = new LogInViewModel();

            // mocking UserManager
            var mockUserManager = MockHelpers.MockUserManager <ApplicationUser>();

            // mocking SignInManager
            var contextAccessor      = new Mock <IHttpContextAccessor>();
            var userPrincipalFactory = new Mock <IUserClaimsPrincipalFactory <ApplicationUser> >();
            var mockSignInManager    = new Mock <SignInManager <ApplicationUser> >(mockUserManager.Object,
                                                                                   contextAccessor.Object, userPrincipalFactory.Object, null, null, null, null);

            mockSignInManager.Setup(sim => sim.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), false))
            .Throws(new Exception())
            .Verifiable();

            var controller = new AccountController(mockUserManager.Object, mockSignInManager.Object);

            // Act
            var result = await controller.LogIn(newLogInVM);

            // Assert
            var requestResult = Assert.IsType <ViewResult>(result);

            Assert.Equal("Error", requestResult.ViewName);
            mockSignInManager.Verify(x => x.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), false), Times.Once);
        }
        public IActionResult CreateNew(LogInViewModel model)
        {
            model.IsUser = (bool)TempData["IsUser"];

            if (model.IsUser)
            {
                int newUserID = _repo.AddUser(model.NewName);
                if (newUserID == -1)
                {
                    TempData.Keep("IsUser");
                    model.ReasonForError = "There was an error processing your request. Please try again.";
                    return(View("DoesNotExist", model));
                }

                UserViewModel userViewModel = new UserViewModel();
                userViewModel.Name = model.NewName;
                userViewModel.ID   = newUserID;

                return(View("NewAdded", userViewModel));
            }
            else
            {
                TempData.Keep("IsUser");
                Console.WriteLine("Someone is attempting to create a store");
                model.ReasonForError = "There was an error processing your request. Please try again later.";
                return(View("DoesNotExist", model));
            }
        }
Exemple #18
0
 private void SetLogInViewModelLabels(LogInViewModel model)
 {
     ViewBag.Title       = model.LabelTitolo = "Log In";
     model.LabelBottone  = "Accedi";
     model.LabelEmail    = "Email";
     model.LabelPassword = "******";
 }
Exemple #19
0
        public ActionResult Login(LogInViewModel accountViewModel, string redirectUrl)
        {
            if (ModelState.IsValid)
            {
                using (userRepository)
                {
                    bool rememberMe = accountViewModel.rememberMe;
                    if (webFormsAuthentication.LogIn(accountViewModel.userName, accountViewModel.password, rememberMe))
                    {
                        //Set the 'display name' as username in the cookie
                        webFormsAuthentication.SetFormsAuthenticationForLoggedInUser(Resources.DisplayName, accountViewModel.rememberMe);
                        if (string.IsNullOrEmpty(redirectUrl))
                        {
                            Session["UserId"] = accountViewModel.userName;
                            return(RedirectToAction("DashBoard", "UserPermission", routeValues: new { area = "UserPermission" }));
                        }
                        else
                        {
                            return(Redirect(redirectUrl));
                        }
                    }
                    else
                    {
                        accountViewModel.InvalidLogInAttempts++;
                        var logInErrorMessage = Messages.LogInError;
                        logInErrorMessage = accountViewModel.InvalidLogInAttempts > 2 ? string.Format(Messages.LogInErrorWithForgotPassword, Url.Action("ForgotPassword", "Account")) : logInErrorMessage;
                        ModelState.AddModelError("", logInErrorMessage);
                    }
                }
            }

            return(View("LogIn", accountViewModel));
        }
Exemple #20
0
        public async Task <ActionResult> Login(LogInViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Wachtwoord, model.RememberMe, shouldLockout : false);//hiervoor aparte service maken, die dan enkel

            //signinasinc nog doorgeeft
            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View(model));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("Index", "Home"));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Foutief e-mail / wachtwoord.");
                return(View(model));
            }
        }
Exemple #21
0
        public async Task <IActionResult> ExternalLogInCallback(string returnUrl = null, string remoteError = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            LogInViewModel loginViewModel = new LogInViewModel
            {
                ReturnUrl      = returnUrl,
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
            };

            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Error from external provider {remoteError}");

                return(View("LogIn", loginViewModel));
            }

            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState.AddModelError(string.Empty, $"Error loading external information");

                return(View("LogIn", loginViewModel));
            }
            else
            {
                // to do sign in!
            }
            return(View("LogIn", loginViewModel));
        }
Exemple #22
0
        public async Task <IActionResult> LogInAsync(LogInViewModel logIn)
        {
            // Check required fields, if any empty return to login page
            if (!ModelState.IsValid)
            {
                logIn.Message = "Required data missing";
                ModelState.AddModelError("BadUserPassword", logIn.Message);
                return(await Task.Run(() => View(logIn)));
            }

            if (logIn.UserName == _siteUserName)
            {
                var passwordHasher = new PasswordHasher <string>();
                if (passwordHasher.VerifyHashedPassword(null, _siteUserPassword, logIn.Password) == PasswordVerificationResult.Success)
                {
                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, logIn.UserName)
                    };
                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

                    return(await Task.Run(() => RedirectToAction("Index", "Barebone")));
                }
            }
            logIn.Message = "Invalid attempt";
            return(await Task.Run(() => View(logIn)));
        }
Exemple #23
0
        public IActionResult LogIn(LogInViewModel model)
        {
            SetLogInViewModelLabels(model);
            if (!ModelState.IsValid)
            {
                model.Messaggio  = "Completa correttamente tutti i campi!";
                model.IsSuccesso = false;
                foreach (var value in ModelState.Values)
                {
                    foreach (var error in value.Errors)
                    {
                        model.Messaggio += "<br>" + error.ErrorMessage;
                    }
                }
                return(View(model));
            }

            Utente utente = DatabaseHelper.GetUtenteByEmail(model.Email);

            if (utente == null || CryptoHelper.HashSHA256(model.Password + utente.Id) != utente.Password)
            {
                model.Messaggio  = "Email o password incoretti.";
                model.IsSuccesso = false;
                return(View(model));
            }

            model.Messaggio  = $"Accesso effettuato!.";
            model.IsSuccesso = true;

            HttpContext.Session.Set <Utente>("utente", utente);

            return(View(model)); //redirect quando sarà pronta l'action
        }
Exemple #24
0
        public async Task <IActionResult> Login(LogInViewModel loginModel)
        {
            if (ModelState.IsValid)
            {
                var result = await SignInManager.PasswordSignInAsync(loginModel.Email, loginModel.Password, false, false);

                if (result.Succeeded)
                {
                    return(RedirectToAction("Index", "Dashboard"));
                }
                //if (result.IsLockedOut)
                //{
                //    ModelState.AddModelError("", "Uzytkownik jest zablokowany");
                //   // return View(loginModel);
                //}

                if (result.IsLockedOut)
                {
                    ModelState.AddModelError("", "Uzytkownik jest zablokowany");
                }
                else
                {
                    ModelState.AddModelError("", "Błąd logowania");
                }
            }
            return(View(loginModel));
        }
Exemple #25
0
        public async Task <IActionResult> LogIn(LogInViewModel model)
        {
            if (ModelState.IsValid)
            {
                var employee = await _service.GetEmployee(model.EmailAddress);

                if (employee == null)
                {
                    throw new Exception("No such employee");
                }

                if (model.Password != employee.Password.Trim())
                {
                    return(RedirectToAction("Index"));
                }

                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, "EmployeeAuthClaim"),
                    new Claim(ClaimTypes.Email, model.EmailAddress),
                    new Claim(ClaimTypes.Role, employee.UserRole)
                };

                var principal = new ClaimsPrincipal(
                    new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme));

                await HttpContext.Authentication.SignInAsync("EmployeeAuthCookieMiddleware", principal);

                return(RedirectToAction("Index"));
            }

            // Something went wrong, redisplay form.
            return(RedirectToAction("Index"));
        }
Exemple #26
0
 public void SetUp()
 {
     _fakeNavigation         = Substitute.For <INavigation>();
     _fakeUserRepository     = Substitute.For <IUserRepository>();
     _nameAndPasswordService = Substitute.For <INameAndPasswordService>();
     _logInViewModel         = new LogInViewModel(_fakeNavigation, _fakeUserRepository, _nameAndPasswordService);
 }
Exemple #27
0
        // GET: Admin/Account
        public ActionResult Login(string ReturnUrl)
        {
            LogInViewModel viewModel = new LogInViewModel();

            ViewBag.ReturnUrl = ReturnUrl;
            return(View(viewModel));
        }
Exemple #28
0
        public IHttpResponse Login(LogInViewModel model)
        {
            var hashedPassword = this.hashService.Hash(model.Password);
            var user           = this.db.Users.FirstOrDefault(x =>
                                                              x.Username == model.Username.Trim() &&
                                                              x.Password == hashedPassword);

            if (user == null)
            {
                return(this.BadRequestError("Invalid username or password."));
            }

            var mvcUser = new MvcUserInfo {
                Username = user.Username, Role = user.Role.ToString(), Info = user.Email
            };
            var cookieContent = this.UserCookieService.GetUserCookie(mvcUser);

            var cookie = new HttpCookie(".auth-cakes", cookieContent, 7)
            {
                HttpOnly = true
            };

            this.Response.Cookies.Add(cookie);

            return(this.Redirect("/"));
        }
Exemple #29
0
        public IActionResult LogIn()
        {
            var model = new LogInViewModel();

            SetLogInViewModelLabels(model);
            return(View(model));
        }
Exemple #30
0
        public async Task <IActionResult> LogIn(LogInViewModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new Exception("Información de usuario invalida.");
            }

            var targetUser = _dbContext.User.SingleOrDefault(u => u.Name.Equals(model.Name,
                                                                                StringComparison.CurrentCultureIgnoreCase));

            if (targetUser == null)
            {
                throw new Exception("El usuario no existe.");
            }

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

            if (result != PasswordVerificationResult.Success)
            {
                throw new Exception("La contraseña es erronea.");
            }

            await LogInUserAsync(targetUser);

            return(RedirectToAction("Index", "Home"));
        }
Exemple #31
0
		public LogInView (LogInViewModel viewModel)
		{
			BindingContext = viewModel;

			entryUser.SetBinding (Entry.TextProperty, "email");
			entryPassword.SetBinding (Entry.TextProperty, "senha");
			buttonLogin.Command = viewModel.LogInCommand;
			buttonSignin.Command = viewModel.SignInCommand;
			LabelMensagem.SetBinding (Label.TextProperty, "mensagem", BindingMode.TwoWay);

			buttonLogin.SetBinding (IsEnabledProperty, "enviarEnabled", BindingMode.TwoWay);
			buttonSignin.SetBinding (IsEnabledProperty, "enviarEnabled", BindingMode.TwoWay);
			Title = "MySafety";

			ToolbarItems.Add (new ToolbarItem {
				Icon = Images.Options,
				Order = ToolbarItemOrder.Primary,
				Command = new Command (OpAction)
			});

			StackLayout stack = new StackLayout {
				Padding = new Thickness (0, 60, 0, 0),
				Spacing = 40,
				VerticalOptions = LayoutOptions.FillAndExpand,
				Children = {
					entryUser,
					entryPassword,
					buttonLogin,
					buttonSignin,
					LabelMensagem,
				},
			};

			var absoluteLayout = new AbsoluteLayout ();
			var background = new Image {
				Style = Styles.BackgroundImage
			};

			absoluteLayout.Children.Add (background, new Rectangle (0, 0, 1, 1), AbsoluteLayoutFlags.All);
			absoluteLayout.Children.Add (stack, new Rectangle (0, 0, 1, 1), AbsoluteLayoutFlags.All);


			Content = absoluteLayout;

			entryUser.Completed += (s, e) => entryPassword.Focus ();

			//		entryPassword.Completed += (s, e) => buttonLogin.Command.Execute(viewModel);
			//        entryPassword.Completed += (s, e) => buttonSignin.Command.Execute(viewModel);

			//            buttonSignin.Clicked += (object sender, EventArgs e) =>
			//         {
			//          Navigation.PushAsync(new SignInView(new SignInViewModel(this.Navigation)));
			//   };

		}
        public void SetUp()
        {
            _logIn = Substitute.For<ILogIn>();
            _autocomplete = Substitute.For<IAutocomplete>();
            _storemanager = Substitute.For<IStoremanager>();
            _admin = Substitute.For<IAdmin>();
            _databaseFunctions = Substitute.For<IDatabaseFunctions>();

            _databaseFunctions.ConnectToDb().Returns(true);
            _uut = new LogInViewModel(_autocomplete, _logIn, _databaseFunctions, _storemanager, _admin);
        }
        //        Repository<Mysafety_user> mySafetyUserRepository;
        //        LogInViewModel login;
        public SignInViewModel(INavigation navigation, LogInViewModel login)
        {
            //            this.login = login;

            enviarEnabled = true;
            _navigation = navigation;

            //            mySafetyUserRepository = new Repository<Mysafety_user>();

            SignInCommand = new Command (async (key) => {
                enviarEnabled = false;
                notificator.HideAll ();

                try {
                    Console.WriteLine (" **Entrando em SignInCommand");

                    if (!Settings.email.Equals (email) || !Settings.password.Equals (password)) {
                        login.cadastroEcommerce = string.Empty;
                        login.comLicenca = false;
                        login.userMySafetyExistente = false;
                    }

                    Settings.cadastrando = false;
                    Settings.nome = nome;
                    Settings.email = email;
                    Settings.password = password;
                    Settings.confirmaSenha = confirmaSenha;
                    mensagem = testeDadosCadastro ();
                    if (mensagem.Length > 0) {
                        await notificator.Notify (ToastNotificationType.Error, "MySafety", mensagem, TimeSpan.FromSeconds (3));
                        return;
                    }

                    var x = await login.consultaTodosCadastros (false);
                    if (x.Equals (false)) //Erro na consulta...
                        return;

                    if (login.cadastroEcommerce == "S4" || login.userMySafetyExistente) {
                        var answer = await UserDialogs.Instance.ConfirmAsync ("Conta MySafety já  existe\nFazer Login?", null, "Sim", "Não");
                        if (answer) {
                            login.cadastroEcommerce = string.Empty; //forca nova consulta para conferir senha digitada
                            ((App)Application.Current).MainPage = new NavigationPage (new LogInView (new LogInViewModel (_navigation)));
                        }
                        return;
                    }

                    Settings.cadastrando = true;

                    /*
                     *S0 – Usuário não consta no banco de dados do ecommerce
                     *S1 – Usuário AINDA NÃO COMPLETOU O CADASTRO, PAROU NA TELA DO APLICATIVO
                     *S2 – Usuário ESCOLHEU UM PLANO, MAS AINDA NÃO VERIFICOU O SEU EMAIL
                     *S3 - Usuário ESCOLHEU O PLANO E JÁ VERIFICOU O SEU EMAIL
                     *S4 - Usuário já cadastrado e senha nao confere com digitacao
                     *S5 - Usuário já cadastrado e senha confere com digitacao
                     */
                    if (login.cadastroEcommerce == "S0" || login.cadastroEcommerce == "S1") {
                        var answer = await UserDialogs.Instance.ConfirmAsync ("Deseja fazer opcao de uso?\nReceberá um e-mail com o link para confirmar", null, "Ok", "Cancelar");
                        if (answer)
                            login.linkCadastroEcommerce (true); //Joga usuario para o site Ecommerce
                    } else if (login.cadastroEcommerce == "S2") {
                        var answer = await UserDialogs.Instance.ConfirmAsync ("Acesse seu email e click no link de confirmação", null, "Ok", "Receber novo e-mail");
                        if (!answer)
                            login.linkCadastroEcommerce (false);  //Apenas faz site enviar novo email
                    } else if (login.cadastroEcommerce == "S4") {
                        await UserDialogs.Instance.AlertAsync ("Cadastro existente\nFaça login", null, "Ok");
                    } else if (login.cadastroEcommerce == "S3")
                        login.loginUserMySafety ();//Cria o usuario
                } catch (Exception ex) {
                    Console.WriteLine (" **Exception Erro 2:" + ex);
                    enviarEnabled = true;
                    await UserDialogs.Instance.AlertAsync ("Erro 2 ao criar conta\nTente mais tarde", null, "Ok");
                }

            });
        }
 /// <summary>
 ///     Sets the datacontext, to the LogInViewModel with all the needed parameters; AutomComplete, Login, DatabaseFunctions, Storemanager, Admin
 /// </summary>
 public LogIn()
 {
     InitializeComponent();
     IUnitOfWork unit = new UnitOfWork(new DataContext());
     DataContext = new LogInViewModel(new Autocomplete(unit), new Administration.LogIn(unit), new DatabaseFunctions(unit), new Storemanager(unit, new Store()), new Administration.Admin(unit));
 }
Exemple #35
0
		public App ()
		{
			MobileService.SerializerSettings.CamelCasePropertyNames = true;

			InitLocalStoreAsync ();

			mysafetyDll = new MySafetyDll.MySafety ();
			mysafetyDll.Events += mysafetyDll_Events;

			Licenses = new ObservableCollection<Licenses> ();
			Gates = new ObservableCollection<Gates> ();
			PortoesNaogerenciados = new ObservableCollection<GateDevices> ();
			Perfis = new ObservableCollection<AccessProfiles> ();
			HorariosDisponiveis = new ObservableCollection<AccessTimes> ();
			Holidays = new ObservableCollection<Holidays> ();

			//Para envio de coordenada de panico
			PanicGps = new Repository<PanicGps> ();
			locator = CrossGeolocator.Current;
			locator.DesiredAccuracy = 60;
			locator.PositionChanged += locator_PositionChanged;

			if (Settings.user_Id.Length > 0) {
				Console.WriteLine ("....User MySafety:" + Settings.user_Id + "  " + meuSkey);
				MainPage = new HomeView ();
			} else {
				LogInViewModel x = new LogInViewModel (null);
				MainPage = new NavigationPage (new LogInView (x));
				x._navigation = MainPage.Navigation;
			}
		}