Ejemplo n.º 1
0
        public void HomePageWithComplexReport()
        {
            string reportPath = Path.Combine(LoggingConfig.GetLogDirectory(), "HomePageWithComplexReport.html");
            string rawResults = Path.Combine(LoggingConfig.GetLogDirectory(), "HomePageWithComplexReport.json");

            // Get to home page
            LoginPageModel page = new LoginPageModel(this.TestObject);

            page.OpenLoginPage();
            page.LoginWithValidCredentials(Config.GetGeneralValue("User"), Config.GetGeneralValue("Pass"));

            // Setup custom rules
            AxeBuilder builder = new AxeBuilder(WebDriver)
                                 .Exclude("#HomePage")
                                 .WithOutputFile(rawResults)
                                 .DisableRules("landmark-one-main", "page-has-heading-one");

            // Reprot
            WebDriver.CreateAxeHtmlReport(builder.Analyze(), reportPath);

            // Check if there were any violations
            if (!File.ReadAllText(reportPath).Contains("Violation: 0"))
            {
                TestObject.AddAssociatedFile(reportPath);
                TestObject.AddAssociatedFile(rawResults);
                Assert.Fail($"Failed violation check see {reportPath} for more details.");
            }
        }
Ejemplo n.º 2
0
        public void TooMuchWaiting()
        {
            LoginPageModel page = new LoginPageModel(this.TestObject);

            page.OpenLoginPage();
            Stopwatch stopwatch = new Stopwatch();

            WebDriverWait wait = new WebDriverWait(new SystemClock(), WebDriver, TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(.5));

            WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3);

            stopwatch.Start();

            try
            {
                // Will timeout in 6.5+ seconds
                wait.Until(x => x.FindElement(By.CssSelector("#missing")));
            }
            catch
            {
                // We expect this to throw an exception
            }

            stopwatch.Stop();

            double seconds = stopwatch.Elapsed.TotalSeconds;

            Assert.IsTrue(seconds > 6 && seconds < 7, $"Took {seconds}, but expected 6-7 seconds");
            Console.WriteLine(stopwatch.Elapsed);
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Register(LoginPageModel loginModel)
        {
            RegisterDetails registerDetails = loginModel.RegisterDetails;

            try
            {
                AppUser user = await _userManager.FindByNameAsync(registerDetails.Username);

                if (user == null)
                {
                    user = new AppUser()
                    {
                        UserName    = registerDetails.Username,
                        FirstName   = registerDetails.FirstName,
                        LastName    = registerDetails.LastName,
                        Email       = registerDetails.Email,
                        DateOfBirth = registerDetails.DateOfBirth
                    };


                    var accountCreation = _userManager.CreateAsync(user, registerDetails.Password);

                    Task.WaitAll(accountCreation);
                    if (accountCreation.Result.Succeeded)
                    {
                        var accountStatsCreation = CreateAccountStats(user);
                        var emailConfirmation    = SendEmailConfirmation(user);

                        Task.WaitAll(accountStatsCreation, emailConfirmation);
                        if (accountStatsCreation.Result && emailConfirmation.Result)
                        {
                            loginModel.Notification = new AlertNotification(NotificationType.Success, "User-Registration Complete! An email has been sent to your email please confirm the verification.");
                            return(View("Index", loginModel));
                        }
                        //TODO: Add somekind of log just in-case the AccountStats somehow fail.
                        else
                        {
                            loginModel.Notification = new AlertNotification(NotificationType.Error, $"Failed to Create Account Relations: Please Contact Support!");
                            return(View("Index", loginModel));
                        }
                    }
                    else
                    {
                        loginModel.Notification = new AlertNotification(NotificationType.Error, $"Failed to Create Account: Please Contact Support!");
                        return(View("Index", loginModel));
                    }
                }
                else
                {
                    loginModel.Notification = new AlertNotification(NotificationType.Error, $"An account has already been registered with those details.");
                    return(View("Index", loginModel));
                }
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message;
            }

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 4
0
        public IActionResult AuthorizationPage(LoginPageModel model)
        {
            var userClaims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, model.UserName)
            };

            var userIdentities = new ClaimsIdentity(userClaims, "ApplicationUserIdentity");

            var userPricipal = new ClaimsPrincipal(new[] { userIdentities });

            using (var context = new ProductsDatabaseContext())
            {
                var user = context.SalesPeoples.FirstOrDefault(x => x.Login == model.UserName && x.Password == model.Password);

                if (user != null)
                {
                    HttpContext.SignInAsync(userPricipal);

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

            return(RedirectToAction("NotAuthorized"));
        }
Ejemplo n.º 5
0
        public ActionResult Login()
        {
            if (HttpContext.User.Identity.Name != "")
            {
                int userId = Convert.ToInt32(HttpContext.User.Identity.Name);


                UserTypeResponse userTypeResponse = TheDataStore.getUserType(userId);

                if (userTypeResponse.response.isOk)
                {
                    switch (userTypeResponse.type)
                    {
                    case UserType.teacher:
                        return(RedirectToAction("Teacher"));

                    case UserType.student:
                        return(RedirectToAction("Student"));
                    }
                    ;
                }
            }


            LoginPageModelResponse pageModelResponse = TheDataStore.FetchLoginPageModel();

            LoginPageModel pageModel = pageModelResponse.pageModel;

            return(View(pageModel));
        }
Ejemplo n.º 6
0
 public LoginPage()
 {
     InitializeComponent();
     PinEnteredByUser.Focus();
     LoginPageModel = new LoginPageModel();
     BindingContext = LoginPageModel;
 }
Ejemplo n.º 7
0
        public ActionResult Login(LoginPageModel model) //TODO: Move all of this to a UserService class
        {
            if (model is null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            //We want to wait a specified amount of time for the response regardless of the results, to avoid
            //Exposing any information to the client
            StaticLogger.Log($"{model.Login}: Login attempt", StaticLogger.LoggingLevel.Call);
            DateTime startLogin = DateTime.Now;

            void WaitForRedirect()
            {
                const double LoginTime = 3000;

                double toWait = LoginTime - (DateTime.Now - startLogin).TotalMilliseconds;

                StaticLogger.Log($"{model.Login}: Waiting for {toWait}", StaticLogger.LoggingLevel.Call);
                if (toWait > 0)
                {
                    System.Threading.Thread.Sleep((int)toWait);
                }
            }

            StaticLogger.Log($"{model.Login}: Calling user service...", StaticLogger.LoggingLevel.Call);
            User?user = this.UserService.Login(model.Login, model.Password);

            if (user != null)
            {
                StaticLogger.Log($"{model.Login}: User not null", StaticLogger.LoggingLevel.Call);
                if (this.ConfigurationService.GetBool(ConfigurationNames.REQUIRE_EMAIL_VALIDATION))
                {
                    if (!this.EmailValidationRepository.IsValidated(user))
                    {
                        return(this.RedirectToAction(nameof(EmailValidationRequired), new { Id = user.Guid.ToString(), area = "" }));
                    }
                }

                if (!string.IsNullOrWhiteSpace(model.ReturnUrl) && model.ReturnUrl != this.Request.Path.Value)
                {
                    WaitForRedirect();
                    StaticLogger.Log($"{model.Login}: Returning to {model.ReturnUrl}", StaticLogger.LoggingLevel.Call);
                    return(this.Redirect(model.ReturnUrl));
                }
                else
                {
                    WaitForRedirect();
                    StaticLogger.Log($"{model.Login}: Returning Home", StaticLogger.LoggingLevel.Call);
                    return(this.Redirect("/Home/Index"));
                }
            }
            else
            {
                StaticLogger.Log($"{model.Login}: User is null", StaticLogger.LoggingLevel.Call);
                this.ModelState.AddModelError(string.Empty, "Invalid Login or Password" + System.Environment.NewLine);
                WaitForRedirect();
                return(this.View(model));
            }
        }
Ejemplo n.º 8
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     if (((AccountsManager)User.AccountsManager.Instance).listFiles().Length == 0)
     {
         this.NavigationService.Navigate(new Uri("/AppPages/NewAccountPage.xaml", UriKind.Relative));
     }
     else
     {
         if (Helpers.AppSettings.DefaultUserfile != "" && Helpers.AppSettings.DefaultPassword != "")
         {
             LoginPageModel Model = new LoginPageModel();
             if (Model.LoginButtonClick())
             {
                 this.NavigationService.Navigate(new Uri("/AppPages/HubPage.xaml", UriKind.Relative));
             }
             else
             {
                 this.NavigationService.Navigate(new Uri("/AppPages/LoginPage.xaml", UriKind.Relative));
             }
         }
         else
         {
             this.NavigationService.Navigate(new Uri("/AppPages/LoginPage.xaml", UriKind.Relative));
         }
     }
 }
Ejemplo n.º 9
0
        private void Login()
        {
            var loginPage = new LoginPageModel(_webDriver, _settings.BaseUrl);

            loginPage.NavigateTo();
            loginPage.Login(_settings.Username, _settings.Password);
        }
Ejemplo n.º 10
0
        public async Task <TokenVm> Login(LoginPageModel login)
        {
            var loginInformation = new Dictionary <string, string>
            {
                { "grant_type", "password" },
                { "client_id", Constants.ClientId },
                { "client_secret", Constants.ClientSecret },
                { "username", login.UserName },
                { "password", login.Password }
            };

            if (!CrossConnectivity.Current.IsConnected)
            {
                throw new WithOutInternetConnectionException();
            }

            var response = await _httpClient.PostAsync("security/token", new FormUrlEncodedContent(loginInformation));

            if (response.IsSuccessStatusCode && response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();

                return(JsonConvert.DeserializeObject <TokenVm>(content));
            }

            await BaseRest.GenerateError(response);

            return(null);
        }
        public void SetUp()
        {
            browser   = new Browser();
            webDriver = browser.WebDriver();

            loginPageModel = new LoginPageModel(webDriver);
        }
Ejemplo n.º 12
0
        /* Constructor
         * Loads all DelegateCommand objects for button clicks.
         */
        public LoginPageViewModel()
        {
            loginCommand     = new DelegateCommand(LoginHelper.LoginOrRegisterAsync);
            LoadingIndicator = false;
            model            = new LoginPageModel();
            navService       = NavigationService.getNavigationServiceInstance();

            LoginHelper.LoginInitiated += (s, args) =>
            {
                LoadingIndicator = true;
            };

            LoginHelper.UserLoggedIn += async(s, user) =>
            {
                App.User = user;
                await App.notificationManager.InitNotificationsAsync(App.User.id);

                LoadingIndicator = false;
                navService.Navigate(typeof(MainPage));
            };

            LoginHelper.AuthError += async(s, errorMsg) =>
            {
                LoadingIndicator = false;
                ContentDialog loginFailDialog = new ContentDialog()
                {
                    Title             = "Could not Log in :(",
                    Content           = errorMsg,
                    PrimaryButtonText = "Ok"
                };

                await ContentDialogHelper.CreateContentDialogAsync(loginFailDialog, true);
            };
        }
        public async Task <bool> Authenticate(LoginPageModel login)
        {
            ValidateLogin(login);
            var tokenService = new TokenRest();
            var token        = await tokenService.Login(login);

            if (token == null)
            {
                throw new Exception("Usuário ou Senha incorreta");
            }

            var userService = new UserRest();
            var userVm      = await userService.GetInformationAsync(token.AccessToken);

            if (userVm == null)
            {
                throw new Exception("Usuário ou Senha incorreta");
            }

            var userToken = new UserTokenVm
            {
                Token = token,
                User  = userVm.Value
            };

            Login(userToken);
            return(true);
        }
 public void Check
 (
     LoginPageModel expectedPage,
     LoginPage actualPage
 )
 {
     Assert.AreEqual(expectedPage.TitleText, actualPage.Title, "LoginPage title bad");
 }
Ejemplo n.º 15
0
        public LoginPageView()
        {
            Content = CreateLayout();

            SetBindings();
            _viewModel     = new LoginPageModel(this);
            BindingContext = _viewModel;
        }
Ejemplo n.º 16
0
        public ActionResult Index()
        {
            var loginPageModel = new LoginPageModel();

            _log.Info(WebConstants.INFOMSG_SHOWDATA);

            return(View(loginPageModel));
        }
Ejemplo n.º 17
0
        public void EnterInvalidCredentials()
        {
            string         username = "******";
            string         password = "******";
            LoginPageModel page     = new LoginPageModel(this.TestObject);

            page.OpenLoginPage();
            Assert.IsTrue(page.LoginWithInvalidCredentials(username, password));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// ویوو مدل صفحه لاگین برنامه
        /// </summary>
        /// <param name="appContextService">اطلاعات سراسری برنامه در مورد کاربر جاری را فراهم می‌کند</param>
        /// <param name="configSetGet">دسترسی به اطلاعات فایل کانفیگ برنامه</param>
        public LoginPageViewModel(IAppContextService appContextService, IConfigSetGet configSetGet)
        {
            _appContextService = appContextService;
            _configSetGet      = configSetGet;

            LoginPageData = new LoginPageModel();
            DoLogin       = new RelayCommand(doLogin, canDoLogin);

            initUserFromConfig();
        }
Ejemplo n.º 19
0
        public void BasicLoginTest()
        {
            // Get to home page
            LoginPageModel page = new LoginPageModel(this.TestObject);

            page.OpenLoginPage();
            HomePageModel home = page.LoginWithValidCredentials(Config.GetGeneralValue("User"), Config.GetGeneralValue("Pass"));

            Assert.IsTrue(home.IsPageLoaded(), "Failed to load homepage");
        }
Ejemplo n.º 20
0
 public void ReadDataFromJson()
 {
     LogUtil.CreateLogFile("CommonLogAppender", pathLog);
     loginModel = JsonDeserealization.GetJsonResult <LoginPageModel>(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JsonConfigs/LoginJsonFile.json"));
     LogUtil.WriteDebug("Read all data from Json file LoginJsonFile.json");
     userProfileModel = JsonDeserealization.GetJsonResult <UserProfileModel>(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JsonConfigs/UserProfileJsonFile.json"));
     LogUtil.WriteDebug("Read all data from Json file UserProfileJsonFile.json");
     leaveRequesrTabModel = JsonDeserealization.GetJsonResult <LeaveRequestTabModel>(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JsonConfigs/LeaveRequestTabJsonFile.json"));
     LogUtil.WriteDebug("Read all data from Json file LeaveRequestTabJsonFile.json");
 }
Ejemplo n.º 21
0
        public void EnterValidCredentialsTest()
        {
            string         username = "******";
            string         password = "******";
            LoginPageModel page     = new LoginPageModel(this.TestObject);

            page.OpenLoginPage();
            HomePageModel homepage = page.LoginWithValidCredentials(username, password);

            Assert.IsTrue(homepage.IsPageLoaded());
        }
Ejemplo n.º 22
0
        public IActionResult Index()
        {
            LoginPageModel viewModel = new LoginPageModel
            {
                LoginDetails    = new LoginDetails(),
                RegisterDetails = new RegisterDetails(),
                Notification    = null
            };

            return(View(viewModel));
        }
 public void ValidateLogin(LoginPageModel login)
 {
     if (string.IsNullOrWhiteSpace(login.UserName))
     {
         throw new Exception("- O Login é obrigatório");
     }
     if (string.IsNullOrWhiteSpace(login.Password))
     {
         throw new Exception("- A Senha é obrigatória");
     }
 }
Ejemplo n.º 24
0
        public async Task <IActionResult> EmailVerify(string token, string Id)
        {
            try
            {
                //Create a view model to be returned to the user
                LoginPageModel viewModel = new LoginPageModel
                {
                    LoginDetails    = new LoginDetails(),
                    RegisterDetails = new RegisterDetails(),
                    Notification    = new AlertNotification()
                };

                AppUser user = await _userManager.FindByIdAsync(Id);

                if (user != null)
                {
                    if (user.EmailConfirmed)
                    {
                        viewModel.Notification.SetNotification(NotificationType.Error, "You have already confirmed your email!");
                        return(View("Index", viewModel));
                    }

                    IdentityResult result = await _userManager.ConfirmEmailAsync(user, token);

                    //TODO: Add a notification model to the dashboard model
                    if (result.Succeeded)
                    {
                        viewModel.Notification.SetNotification(NotificationType.Success, "Email Confirmation Success! You can now login.");
                        return(View("Index", viewModel));
                    }
                    else
                    {
                        viewModel.Notification.SetNotification(NotificationType.Error, "Token Error: Please Contact Support!");
                        return(View("Index", viewModel));
                    }
                }

                viewModel.Notification.SetNotification(NotificationType.Error, "Email Confirmation Failed: User doesn't exist!");
                return(View("Index", viewModel));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

                LoginPageModel failureViewModel = new LoginPageModel
                {
                    LoginDetails    = new LoginDetails(),
                    RegisterDetails = new RegisterDetails(),
                    Notification    = new AlertNotification(NotificationType.Error, "Email Confirmation Failed! Please contact support!")
                };
                return(View("Index", failureViewModel));
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// ویوو مدل تغییر اطلاعات کاربر جاری وارد شده به سیستم
        /// </summary>
        /// <param name="uow">وهله‌ای از زمینه و واحد کاری ایی اف</param>
        /// <param name="appContextService">اطلاعات سراسری برنامه در مورد کاربر جاری را فراهم می‌کند</param>
        /// <param name="usersService">سرویس اطلاعات کاربران</param>
        public ChangeProfileViewModel(IUnitOfWork uow, IAppContextService appContextService, IUsersService usersService)
        {
            _uow               = uow;
            _usersService      = usersService;
            _appContextService = appContextService;

            ChangeProfileData = new LoginPageModel();
            DoSave            = new RelayCommand(doSave, canDoSave);

            ChangeProfileData.UserName = _appContextService.CurrentUser.UserName;
            ChangeProfileData.Password = _appContextService.CurrentUser.Password;
        }
Ejemplo n.º 26
0
 public App()
 {
     InitializeComponent();
     if (LoginPageModel.ExisteToken())
     {
         MainPage = new MainPage();
     }
     else
     {
         MainPage = new LoginPage(); //new MainPage();
     }
 }
Ejemplo n.º 27
0
        public void LoginPageBasic()
        {
            LoginPageModel page = new LoginPageModel(this.TestObject);

            page.OpenLoginPage();

            AxeResult result = WebDriver.Analyze();

            var resultJson = JsonConvert.SerializeObject(result, Formatting.Indented);

            Assert.IsTrue(string.IsNullOrEmpty(result.Error) && result.Violations.Length == 0, "Failures:" + resultJson);
        }
Ejemplo n.º 28
0
        public IActionResult Login(LoginPageModel model)
        {
            var response = _page.Process(model);

            if (response.Type == StoreFront.Model.Enum.Response.DataResponseType.SUCCESS)
            {
                return(Redirect(Request.Query["ReturnURL"].ToString()));
            }

            model.LoginError = "User not valid, please check your details and try again.";
            return(View("Index", new LoginPageViewModel(model)));
        }
        public LabPatternResultsAppModel(Func <DbContext> getModelContext)
        {
            _getModelContext = getModelContext;

            ExpectedLoginPage = new LoginPageModel("Login");
            ExpectedMainPage  = new MainPageModel("Home");

            NavCount   = 0;
            ModalCount = 0;

            NavState   = NavState.Empty;
            ModalState = ModalState.Empty;
        }
Ejemplo n.º 30
0
        public IActionResult Login(string email)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "App"));
            }

            LoginPageModel pageModel = new LoginPageModel();

            pageModel.SetMessage(email);

            return(View(pageModel));
        }
        public ActionResult Login(string id)
        {
            if (!string.IsNullOrEmpty(this.EcommerceContext.LoggedUserId))
            {
                return RedirectToAction("MinhaConta");
            }

            LoginPageModel model = new LoginPageModel();
            this.BindBasePageModel(model);

            //if (HttpContext.Request.IsSecureConnection.Equals(false))
            //{
            //    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Request.RawUrl, true);
            //    Response.End();
            //}

            return View("../CustomCode/VICommerce/" + EcommerceContext.AccountDomain + "/Login", model);
        }
        public ActionResult LoginPost()
        {
            if (!string.IsNullOrEmpty(this.EcommerceContext.LoggedUserId))
            {
                return RedirectToAction("MinhaConta");
            }

            LoginPageModel model = new LoginPageModel();
            this.BindBasePageModel(model);

            var user = new VIKomet.SDK.Entities.UserManagement.User();
            user.Email = Request.Form["Username"];
            user.Username = Request.Form["Username"];
            user.Password = Request.Form["Password"];

            try
            {
                string access_token = base.authorizationClient.GetPasswordToken(user, EcommerceContext.AccountId, EcommerceContext.AccountToken);
                this.AccessTokenInContext = access_token;

                this.LoggedUserAccessTokenInContext = access_token;
                //FormsAuthentication.SetAuthCookie(access_token, true);
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message;
                return View("../CustomCode/VICommerce/" + EcommerceContext.AccountDomain + "/Login", model);
            }

            return RedirectToAction("Index");
        }