public ActionResult Login(LoginFormViewModel model)
        {
            Staff staff = new Staff()
            {
                Username = model.Username,
                Password = model.Password
            };

            staff = GetStaff(staff);

            if (staff != null)
            {
                FormsAuthentication.SetAuthCookie(model.Username, false);

                var    authTicket      = new FormsAuthenticationTicket(1, staff.Username, DateTime.Now, DateTime.Now.AddMinutes(30), false, staff.Username);
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var    authCookie      = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpContext.Response.Cookies.Add(authCookie);
                return(RedirectToAction("Admin", "Admin"));
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password, try again.");
                return(View(model));
            }
        }
        public async Task <IActionResult> Login([FromBody] LoginFormViewModel model)
        {
            if (!this.ModelState.IsValid || this.ModelState == null)
            {
                return(BadRequest("Invalid credentials."));
            }

            var result = await this.signInManager.PasswordSignInAsync(model.Username, model.Password, false, false);

            if (!result.Succeeded)
            {
                this.ModelState.AddModelError(string.Empty, "Invalid login attempt.");

                return(BadRequest(this.ModelState.GetFirstError()));
            }

            var user = await userManager.FindByNameAsync(model.Username);

            if (user == null)
            {
                return(BadRequest("Unexisting user."));
            }

            this.logger.LogInformation("User logged in.");

            var securityToken = this.BuildToken(user);

            return(Ok(securityToken));
        }
 public void Initialize()
 {
     this.authentication     = new Mock <IAuthenticationService>();
     this.regionManager      = new Mock <IRegionManager>();
     this.interactionService = new Mock <IInteractionService>();
     this.viewModel          = new LoginFormViewModel(this.regionManager.Object, this.interactionService.Object, this.authentication.Object);
 }
Exemple #4
0
        public ActionResult Login(LoginFormViewModel requestedViewModel)
        {
            if (ModelState.IsValid)
            {
                Domain.Admin admin;
                if (AdminService.Validate(requestedViewModel.UserName, requestedViewModel.Password, out admin))
                {
                    AdminService.SignIn(admin, Response);

                    if (admin.IsSystemUser)
                    {
                        return(RedirectToAction("Index", "Admins", null));
                    }
                    else
                    {
                        return(RedirectToAction("Index"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Brugeren blev ikke fundet");
                }
            }

            return(View(requestedViewModel));
        }
Exemple #5
0
        public ActionResult Login(LoginFormViewModel form, string url)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var token = _loginRepository.Login(form);

                    SessionHelper.AddUserToSession(token);

                    if (!string.IsNullOrEmpty(url))
                    {
                        return(Redirect(url));
                    }

                    return(RedirectToAction("Index", "Dashboard"));
                }
                catch (BadRequestException bre)
                {
                    ModelState.AddModelError("", "Incorrect username and/or password");
                }
            }

            return(View("Index", form));
        }
Exemple #6
0
        public LoginResponse Login(LoginFormViewModel model)
        {
            try
            {
                var user = _userRepository.GetUserBy(x => x.UserEmail == model.UserEmail && x.IsActive == true);
                if (user != null && _hashingService.Compare(user.UserPassword, model.UserPassword))
                {
                    FormsAuthentication.SetAuthCookie(user.UserEmail, createPersistentCookie: false);

                    return(new LoginResponse()
                    {
                        IsError = false,
                        Message = "Login.Submit.Success",
                    });
                }
            }
            catch (Exception exception)
            {
                Log.Error("Error during login", exception);
            }
            return(new LoginResponse()
            {
                IsError = true,
                Message = "Login.Submit.Failure",
            });
        }
Exemple #7
0
        public ActionResult Login(LoginFormViewModel Model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Index", Model));
            }

            AccountModel Account = _AccountService.Login(Model.EmailAddress, Model.Password);

            if (Account != null)
            {
                ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Account.ID.ToString()));
                identity.AddClaim(new Claim(ClaimTypes.Email, Account.EmailAddress));
                identity.AddClaim(new Claim(ClaimTypes.Role, Account.AccountType.ToString()));

                identity.AddClaim(new Claim(ClaimTypes.Name, Account.AccountInformation.FirstName + " " + Account.AccountInformation.LastName));

                AuthenticationManager.SignIn(identity);

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

            return(View("Index", Model));
        }
        private void Logar(IUsuarioApp usuarioApp, ILogApp logApp, LoginFormViewModel model, TipoArea area)
        {
            if (!ModelState.IsValid)
            {
                throw new Exception(Erro);
            }

            var usuario = usuarioApp.ValidarLogin(model, area);

            var log = new Log()
            {
                Action     = "Login",
                Controller = "Login",
                UsuarioId  = usuario.UserId,
                Ip         = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"],
                Area       = area.ToString()
            };

            logApp.SalvarLog(log);
            usuario.LogId = log.Id;

            var userData   = JsonConvert.SerializeObject(usuario);
            var authTicket = new FormsAuthenticationTicket(1, usuario.UserId.ToString(), DateTime.Now,
                                                           DateTime.Now.AddMinutes(30), false, userData);
            var encTicket = FormsAuthentication.Encrypt(authTicket);
            var faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            Response.Cookies.Add(faCookie);
        }
Exemple #9
0
        public ActionResult Index(LoginFormViewModel model)
        {
            if (ModelState.IsValid)
            {
                model = this.Model.Authenticate(model, this.ControllerContext.HttpContext);

                if (!model.IncorrectCredentials && !string.IsNullOrWhiteSpace(model.RedirectUrlAfterLogin))
                {
                    return(this.Redirect(model.RedirectUrlAfterLogin));
                }
                else if (!model.IncorrectCredentials && this.Request.UrlReferrer != null)
                {
                    var returnUrlFromQS = System.Web.HttpUtility.ParseQueryString(this.Request.UrlReferrer.Query)["ReturnUrl"];

                    if (!string.IsNullOrEmpty(returnUrlFromQS))
                    {
                        //validates whether the returnUrl is allowed in the relying parties.
                        SWTIssuer.GetRelyingPartyKey(returnUrlFromQS);

                        return(this.Redirect(returnUrlFromQS));
                    }
                }
            }

            this.Model.InitializeLoginViewModel(model);

            var fullTemplateName = this.loginFormTemplatePrefix + this.LoginFormTemplate;

            return(this.View(fullTemplateName, model));
        }
Exemple #10
0
        public void SetUp()
        {
            //            testScheduler = new TestScheduler();
            //            origSched = RxApp.DeferredScheduler;
            //            RxApp.DeferredScheduler = testScheduler;

            lockObject          = new ManualResetEvent(false);
            requestExecutor     = new RequestExecutorStub();
            audioPlayerStub     = new AudioPlayerStub();
            playbackController  = new PlaybackController(audioPlayerStub, requestExecutor);
            authenticator       = new Authenticator(requestExecutor, new SettingsStub());
            mediaLibraryBrowser = new MediaLibraryBrowser(requestExecutor);


            requestExecutor.Responses.Add(new LoginResponse()
            {
                LoggedIn           = false,
                CurrentUserElement = new CurrentUserElement()
                {
                    Login = "******",
                    Slug  = "userSlug"
                }
            });

            loginFormViewModel = new LoginFormViewModel(authenticator);

            mediaBrowserViewModel = new MediaBrowserViewModel(mediaLibraryBrowser,
                                                              new SettingsStub(),
                                                              loginFormViewModel,
                                                              new MixViewModelFactory(playbackController, mediaLibraryBrowser, loginFormViewModel.UserLoggedInObservable));
        }
Exemple #11
0
        public async Task <IActionResult> Login(LoginFormViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("", "Email e/ou senha inválido(s)");
            }

            PasswordHasher <User> passwordHasher = new PasswordHasher <User>();
            var user = await _userManager.FindByEmailAsync(viewModel.Email);

            if (user != null && user.EmailConfirmed)
            {
                if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, viewModel.Password) != PasswordVerificationResult.Failed)
                {
                    await _signInManager.SignInAsync(user, false);

                    return(RedirectToAction(nameof(IndexTotalMonthly), new { id = user.Id }));
                }

                ModelState.AddModelError("", "Email e/ou senha inválido(s)");
            }

            ModelState.AddModelError("", "Email ainda não confirmado, por favor, verificar na sua caixa de entrada");
            return(View(viewModel));
        }
        public ActionResult SignIn(LoginFormViewModel requestedViewModel, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                Credential credential;
                if (CredentialService.Validate(requestedViewModel.UserName, requestedViewModel.Password, out credential))
                {
                    CredentialService.SignIn(credential, Response);

                    if (!String.IsNullOrWhiteSpace(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }

                    var profile = ProfileService.GetById(credential.CredentialsId);
                    ProfileService.AddActivity(profile.ProfileId, "LoggedIn");

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

            TempData["LoginHeader"]  = "Der skete en fejl da du prøvede at logge ind";
            TempData["LoginMessage"] = "Brugeren og kodeordet passer ikke sammen,";
            TempData["UserName"]     = requestedViewModel.UserName;

            return(RedirectToAction("Create"));
        }
Exemple #13
0
    public ActionResult SubmitForm(LoginFormViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return(CurrentUmbracoPage());
        }

        var contentService = Services.ContentService;
        var user           = contentService.GetChildrenByName(registerUsersOverviewNodeId, model.UserName).FirstOrDefault();

        if (user != null && user.Status == ContentStatus.Published && user.GetValue <string>("password") == CommonUtility.MD5Hash(model.Password))
        {
            SessionManager.UserLogin = new UserViewModel
            {
                UserId         = user.Id,
                UserName       = user.GetValue <string>("userName"),
                FullName       = user.GetValue <string>("fullName"),
                Email          = user.GetValue <string>("email"),
                CompanyName    = user.GetValue <string>("company"),
                CompanyAddress = user.GetValue <string>("address")
            };
            return(RedirectToUmbracoPage(1373));
        }
        else
        {
            ModelState.AddModelError("", "Invalid username or password or user is not published.");
            //TempData["LoginFail"] = true;
        }

        return(CurrentUmbracoPage());
    }
 public ActionResult Login(LoginFormViewModel user)
 {
     try
     {
         HttpResponseMessage responseGet = GlobalVariables.WebApiClient.GetAsync("User").Result;
         var userList  = responseGet.Content.ReadAsAsync <IEnumerable <User> >().Result;
         var loginUser = userList.Where(u => u.Email == user.Email).FirstOrDefault();
         if (loginUser == null)
         {
             ModelState.AddModelError("Email", "User Does not exist");
             return(View());
         }
         else
         {
             if (loginUser.Password != user.Password)
             {
                 ModelState.AddModelError("Password", "Incorrect Password");
                 return(View());
             }
             else
             {
                 Session["username"] = loginUser.Username;
                 MyLogger.GetInstance().Info("User Logged in by username : "******"successfull login");
                 return(RedirectToAction("Index"));
             }
         }
     }
     catch (Exception ex)
     {
         MyLogger.GetInstance().Error("Exception at user Login : "******"Index"));
     }
 }
Exemple #15
0
        public LoginForm()
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;

            InitializeComponent();

            DataContext = ViewModel = App.Container.Resolve <LoginFormViewModel>();
        }
 public ActionResult AdminLogin(LoginFormViewModel myModel)
 {
     if (DBConnectionHandler.ValidateLogIn(myModel) == true)
     {
         return(RedirectToAction("AdminPortal"));
     }
     else
     {
         return(RedirectToAction("AdminLogInError"));
     }
 }
Exemple #17
0
        public LoginFormViewModel GetLoginFormView(int currentPageId, LoginFormViewModel model)
        {
            model.CurrentUmbracoPageId = currentPageId;
            model.CurrentPageCulture   = Thread.CurrentThread.CurrentCulture;

            if (model.Response != null && !string.IsNullOrEmpty(model.Response.Message))
            {
                model.Response.Message = _umbracoHelper.GetDictionaryValue(model.Response.Message);
            }

            return(model);
        }
Exemple #18
0
 public LoginFormPage()
 {
     InitializeComponent();
     this.BindingContext = _viewModel = new LoginFormViewModel();
     MessagingCenter.Subscribe <LoginFormPage, string>(this, "ErroLogin", async(sender, arg) =>
     {
         Device.BeginInvokeOnMainThread(async() =>
         {
             await DisplayAlert("Deu ruim", arg, "OK");
         });
     });
 }
Exemple #19
0
        public HttpResponse Login(LoginFormViewModel model)
        {
            var(errors, userId) = UserService.Login(model);

            if (errors.Any())
            {
                return(Error(errors));
            }

            this.SignIn(userId);

            return(Redirect("/Home/IndexLoggedIn"));
        }
Exemple #20
0
        public (List <string>, string) Login(LoginFormViewModel model)
        {
            var hashedPassword = this.PasswordHasher.GeneratePassword(model.Password);

            var user = this.Data
                       .Users
                       .Where(u => u.Username == model.Username)
                       .FirstOrDefault();

            var modelErrors = this.Validator.ValidateLoginUser(user, hashedPassword);

            return(modelErrors.ToList(), user.Id);
        }
        public HttpResponse Login(LoginFormViewModel model)
        {
            (string userId, string error) = UserService.Login(model);

            if (string.IsNullOrEmpty(userId) || string.IsNullOrWhiteSpace(userId))
            {
                return(Error(error));
            }

            this.SignIn(userId);

            return(Redirect("/"));
        }
Exemple #22
0
        public ActionResult Index(LoginFormViewModel model)
        {
            if (ModelState.IsValid)
            {
                model = this.Model.Authenticate(model, this.ControllerContext.HttpContext);
            }

            this.Model.InitializeLoginViewModel(model);

            var fullTemplateName = this.loginFormTemplatePrefix + this.LoginFormTemplate;

            return(this.View(fullTemplateName, model));
        }
Exemple #23
0
        public void ifLoginNotCheckedThenResultIsAbort()
        {
            //Arrange
            Mock <CheckPasswordDelegate> checkMock = new Mock <CheckPasswordDelegate>();

            checkMock.Setup(x => x(It.IsAny <string>(), It.IsAny <string>())).Returns(false);
            viewModel = new LoginFormViewModel(new CheckPasswordDelegate(checkMock.Object));

            //Act
            //viewModel.enter(new ProjectKernel.Forms.View.LoginForm(viewModel));

            //Assert
            Assert.AreEqual(ProjectKernel.Forms.ViewModel.ActionResult.OK, viewModel.Result);
        }
        public LoginForm(IViewManager viewManager, IUserService userService)
        {
            InitializeComponent();

            LoginFormViewModel vm = (LoginFormViewModel)this.DataContext; // this creates an instance of the ViewModel

            if (vm.CloseAction == null)
            {
                vm.CloseAction = new Action(() => this.Close());
            }

            vm.ViewManager = viewManager;
            vm.UserService = userService;
        }
Exemple #25
0
        public ActionResult SubmitLoginForm(LoginFormViewModel model)
        {
            SetCulture(model.CurrentPageCulture);
            if (ModelState.IsValid)
            {
                model.Response = _accountService.Login(model);
                if (!model.Response.IsError)
                {
                    CookiesExtensions.CreateCookie(CookieVariables.TempMessageCookie, model.Response.Message);
                }
            }

            model = _accountService.GetLoginFormView(model.CurrentUmbracoPageId, model);
            return(PartialView("LoginFormPartial", model));
        }
Exemple #26
0
        public ActionResult Login(LoginFormViewModel user)
        {
            //Compare if incoming data is valid
            if (!ModelState.IsValid)
            {
                var form = new LoginFormViewModel();

                form.errorMessage = "";

                return(View(form));
            }

            try
            {
                var authPlayer = m.PlayerGetByEmail(user.Email);

                if (authPlayer == null)
                {
                    var form = new LoginFormViewModel();
                    form.errorMessage = "The following email doesn't seem to have an account with us. Please try again.";

                    return(View(form));
                }
                else
                {
                    if (Crypto.VerifyHashedPassword(authPlayer.PLAYER_PASSWORD, user.Password))
                    {
                        AuthenticateUser(authPlayer);
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        var form = new LoginFormViewModel();
                        form.errorMessage = "The password entered doesn't match the password that's associated with this account. Please try again.";

                        return(View(form));
                    }
                }
            }
            catch (Exception)
            {
                var form = new LoginFormViewModel();

                form.errorMessage = "Please make sure to fill in all values before clicking the submit button.";

                return(View(form));
            }
        }
Exemple #27
0
        public ActionResult Login()
        {
            var viewModel = new LoginFormViewModel();

            viewModel.UserLogin = new UserLogin();

            if (Request.Cookies["LoginEmail"] != null)
            {
                // populate data from cookie
                viewModel.UserLogin.Email    = Request.Cookies["LoginEmail"].Value;
                viewModel.UserLogin.Password = Request.Cookies["LoginPassword"].Value;
                viewModel.RememberMe         = true;
            }

            return(View(viewModel));
        }
        public void SetUp()
        {
            //testScheduler = new TestScheduler();
            //origSched = RxApp.DeferredScheduler;
            //RxApp.DeferredScheduler = testScheduler;

            lockObject      = new ManualResetEvent(false);
            requestExecutor = new RequestExecutorStub();
            // because it'll try to invoke it in the beginning, while loading the credentials from the registry
            requestExecutor.Responses.Add(unsucessfulLoginResponse);

            authenticator      = new Authenticator(requestExecutor, new SettingsStub());
            loginFormViewModel = new LoginFormViewModel(authenticator);
            loginFormViewModel.UsernameField = "username";
            loginFormViewModel.PasswordField = "password";
        }
        //IBusinessLogicsConnector _blConnector;
        //public CustomLoginFormModel(IBusinessLogicsConnector blConnector) : base()
        //{
        //    _blConnector = blConnector;
        //}
        public override LoginFormViewModel Authenticate(LoginFormViewModel input, HttpContextBase context)
        {
            input.LoginError = false;

            var cmsUser = JXTNext.Sitefinity.Common.Helpers.SitefinityHelper.GetUserByEmail(input.UserName);

            if (cmsUser != null)
            {
                IEnumerable <IJobListingMapper> jobListingMappers = new List <IJobListingMapper> {
                    new JXTNext_JobListingMapper()
                };
                IEnumerable <IMemberMapper> memberMappers = new List <IMemberMapper> {
                    new JXTNext_MemberMapper()
                };
                IRequestSession requestSession = new SFEventRequestSession {
                    UserEmail = input.UserName
                };

                IBusinessLogicsConnector connector = new JXTNextBusinessLogicsConnector(jobListingMappers, memberMappers, requestSession);

                var memberResponse = connector.GetMemberByEmail(input.UserName);
                if (memberResponse.Member == null)
                {
                    UserProfileManager userProfileManager = UserProfileManager.GetManager();
                    UserProfile        profile            = userProfileManager.GetUserProfile(cmsUser.Id, typeof(SitefinityProfile).FullName);
                    var fName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "FirstName");
                    var lName = Telerik.Sitefinity.Model.DataExtensions.GetValue(profile, "LastName");
                    JXTNext_MemberRegister memberReg = new JXTNext_MemberRegister
                    {
                        Email     = input.UserName,
                        FirstName = fName.ToString(),
                        LastName  = lName.ToString(),
                        Password  = input.UserName
                    };

                    if (connector.MemberRegister(memberReg, out string errorMessage))
                    {
                        Log.Write($"User created in the JXT DB ", ConfigurationPolicy.ErrorLog);
                    }
                }
            }


            var result = base.Authenticate(input, context);

            return(input);
        }
Exemple #30
0
        public (string userId, string error) Login(LoginFormViewModel model)
        {
            var    hashedPassword = this.passwordHasher.GeneratePassword(model.Password);
            string modelErrors    = string.Empty;

            string userId = this.Data.Users
                            .Where(x => x.Username == model.Username || x.Email == model.Username)
                            .Where(x => x.Password == hashedPassword).Select(x => x.Id)
                            .FirstOrDefault();

            if (userId == null)
            {
                return(null, modelErrors = "Wrong Login Information, UserName or Password are incorect");
            }

            return(userId, modelErrors);
        }