Inheritance: System.Web.UI.Page
Ejemplo n.º 1
0
        public virtual async Task<ActionResult> Post(CreateLocalMembership command, string returnUrl, string emailAddress)
        {
            //System.Threading.Thread.Sleep(new Random().Next(5000, 5001));

            if (command == null || string.IsNullOrWhiteSpace(emailAddress))
                return View(MVC.Errors.Views.BadRequest);

            if (!ModelState.IsValid)
            {
                ViewBag.EmailAddress = emailAddress;
                ViewBag.Ticket = command.Ticket;
                ViewBag.Token = command.Token;
                ViewBag.ReturnUrl = returnUrl;
                return View(MVC.Security.Views.SignUp.CreateUser, command);
            }

            await _commands.Execute(command);

            var signIn = new SignIn
            {
                UserNameOrVerifiedEmail = command.UserName,
                Password = command.Password
            };
            await _commands.Execute(signIn);
            Session.VerifyEmailTickets(null);
            Response.ClientCookie(signIn.SignedIn.Id, _queries);
            return this.RedirectToLocal(returnUrl, await MVC.UserName.Index());
        }
Ejemplo n.º 2
0
        public virtual async Task<ActionResult> Post(SignIn command, string returnUrl)
        {
            //System.Threading.Thread.Sleep(new Random().Next(5000, 5001));

            if (command == null) return View(MVC.Errors.Views.BadRequest);
            if (!ModelState.IsValid) return View(MVC.Security.Views.SignIn, command);
            await _commands.Execute(command);
            Response.ClientCookie(command.SignedIn.Id, _queries);
            return this.RedirectToLocal(returnUrl, await MVC.UserName.Index());
        }
Ejemplo n.º 3
0
        public void IsInvalid_WhenPassword_IsEmpty(string password)
        {
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateSignInCommand(queries.Object);
            var command = new SignIn { Password = password };

            var result = validator.Validate(command);

            result.IsValid.ShouldBeFalse();
            Func<ValidationFailure, bool> targetError = x => x.PropertyName == command.PropertyName(y => y.Password);
            result.Errors.Count(targetError).ShouldEqual(1);
            result.Errors.Single(targetError).ErrorMessage
                .ShouldEqual(Resources.notempty_error.Replace("{PropertyName}", LocalMembership.Constraints.PasswordLabel));
            queries.Verify(x => x.Execute(It.IsAny<IsPasswordVerified>()), Times.Never);
        }
Ejemplo n.º 4
0
        public void IsInvalid_WhenUserName_IsEmpty(string userName)
        {
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateSignInCommand(queries.Object);
            var command = new SignIn { UserNameOrVerifiedEmail = userName };

            var result = validator.Validate(command);

            result.IsValid.ShouldBeFalse();
            Func<ValidationFailure, bool> targetError = x => x.PropertyName == command.PropertyName(y => y.UserNameOrVerifiedEmail);
            result.Errors.Count(targetError).ShouldEqual(1);
            result.Errors.Single(targetError).ErrorMessage
                .ShouldEqual(Resources.notempty_error.Replace("{PropertyName}",
                    string.Format("{0} or {1}", User.Constraints.NameLabel, EmailAddress.Constraints.Label)));
            queries.Verify(x => x.Execute(It.IsAny<UserBy>()), Times.Never);
        }
Ejemplo n.º 5
0
        public virtual ActionResult Validate(SignIn command, string fieldName = null)
        {
            //System.Threading.Thread.Sleep(new Random().Next(5000, 5001));
            if (command == null || command.PropertyName(x => x.Password).Equals(fieldName, StringComparison.OrdinalIgnoreCase))
            {
                Response.StatusCode = 400;
                return Json(null);
            }

            var result = new ValidatedFields(ModelState, fieldName);

            //ModelState[command.PropertyName(x => x.UserName)].Errors.Clear();
            //result = new ValidatedFields(ModelState, fieldName);

            return new CamelCaseJsonResult(result);
        }
		public void DidSignIn(SignIn signIn, GoogleUser gUser, Foundation.NSError error)
		{
			Device.BeginInvokeOnMainThread(async () => {

				UIAlertView alert = new UIAlertView("Login", "In DidSignIn", null, "OK", null);
				alert.Show ();
					Debug.WriteLine("DidSignIn");

					if (error != null)
					{
						Debug.WriteLine("In DidSignIn: Failure Google Error: " + error.Description, "Login");
						return;
					}

					if (gUser == null)
					{
						Debug.WriteLine("In DidSignIn: Failure Google User == null", "Login");
						return;
					}

					if (gUser != null)
					{
//						//Azure Login Process:
//						try
//						{
//							var jToken = JObject.FromObject(new {
//								access_token = SignIn.SharedInstance.CurrentUser.Authentication.AccessToken,
//								authorization_code = SignIn.SharedInstance.CurrentUser.ServerAuthCode,
//								id_token = SignIn.SharedInstance.CurrentUser.Authentication.IdToken,
//							});
//							var user = await DependencyService.Get<IMobileClient>().Authenticate(MobileServiceAuthenticationProvider.Google, jToken);
//							if (user == null)
//							{
//								Debug.WriteLine("Azure Google User == null. Logging out.");
//								App.Logout();
//							}
//						}
//						catch (Exception ex)
//						{
//							Debug.WriteLine("Azure Google Signin Exception: " + ex.ToString());
//						}
					}
				});
		}
Ejemplo n.º 7
0
        public void AuthenticatesUser_UsingCommand_IsPersistent(bool isPersistent)
        {
            var command = new SignIn { UserNameOrVerifiedEmail = "username", Password = "******", IsPersistent = isPersistent };
            var user = new User { Name = command.UserNameOrVerifiedEmail };
            var userResult = Task.FromResult(user);
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var userStore = new Mock<IUserStore<User, int>>();
            var userManager = new Mock<UserManager<User, int>>(userStore.Object);
            var authenticator = new Mock<IAuthenticate>(MockBehavior.Strict);
            var handler = new HandleSignInCommand(queries.Object, userManager.Object, authenticator.Object);
            Expression<Func<UserByNameOrVerifiedEmail, bool>> userByNameOrVerifiedEmail = x => x.NameOrEmail == command.UserNameOrVerifiedEmail;
            queries.Setup(x => x.Execute(It.Is(userByNameOrVerifiedEmail))).Returns(userResult);
            userManager.Setup(x => x.FindAsync(command.UserNameOrVerifiedEmail, command.Password)).Returns(userResult);
            authenticator.Setup(x => x.SignOn(user, isPersistent)).Returns(Task.FromResult(0));

            handler.Handle(command).Wait();

            authenticator.Verify(x => x.SignOn(user, isPersistent), Times.Once);
        }
Ejemplo n.º 8
0
        public void IsInvalid_WhenUserName_MatchesNoUserOrEmail()
        {
            var userName = FakeData.String();
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateSignInCommand(queries.Object);
            var command = new SignIn { UserNameOrVerifiedEmail = userName };
            Expression<Func<UserByNameOrVerifiedEmail, bool>> userById = x => x.NameOrEmail == command.UserNameOrVerifiedEmail;
            queries.Setup(x => x.Execute(It.Is(userById))).Returns(Task.FromResult(null as User));

            var result = validator.Validate(command);

            result.IsValid.ShouldBeFalse();
            Func<ValidationFailure, bool> targetError = x => x.PropertyName == command.PropertyName(y => y.UserNameOrVerifiedEmail);
            result.Errors.Count(targetError).ShouldEqual(1);
            result.Errors.Single(targetError).ErrorMessage
                .ShouldEqual(Resources.Validation_CouldNotFind
                    .Replace("{PropertyName}", string.Format("{0} or {1}", User.Constraints.NameLabel, EmailAddress.Constraints.Label).ToLower())
                    .Replace("{PropertyValue}", command.UserNameOrVerifiedEmail));
            queries.Verify(x => x.Execute(It.Is(userById)), Times.Once);
        }
Ejemplo n.º 9
0
        public void IsInvalid_WhenPassword_IsNotVerified_AndUserExists()
        {
            var userName = FakeData.String();
            var password = FakeData.String();
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateSignInCommand(queries.Object);
            var command = new SignIn { UserNameOrVerifiedEmail = userName, Password = password, };
            Expression<Func<IsPasswordVerified, bool>> expectedQuery = x =>
                x.UserNameOrVerifiedEmail == command.UserNameOrVerifiedEmail && x.Password == command.Password;
            queries.Setup(x => x.Execute(It.Is(expectedQuery))).Returns(Task.FromResult(false));
            Expression<Func<UserByNameOrVerifiedEmail, bool>> userQuery = x => x.NameOrEmail == command.UserNameOrVerifiedEmail;
            queries.Setup(x => x.Execute(It.Is(userQuery))).Returns(Task.FromResult(new User()));

            var result = validator.Validate(command);

            result.IsValid.ShouldBeFalse();
            Func<ValidationFailure, bool> targetError = x => x.PropertyName == command.PropertyName(y => y.Password);
            result.Errors.Count(targetError).ShouldEqual(1);
            result.Errors.Single(targetError).ErrorMessage.ShouldEqual(Resources.Validation_InvalidPassword);
            queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once);
            queries.Verify(x => x.Execute(It.Is(expectedQuery)), Times.Once);
        }
Ejemplo n.º 10
0
        private void SignIn_Click(object sender, EventArgs e)
        {
            kullaniciAdi = KullaniciAdiTxt.Text;
            String sifre = SifreTxt.Text;

            personel = dap.GetSifreYetki(kullaniciAdi);
            String realSifre = personel[0].Sifre;

            //realSifre=personel.Select(x => x.Sifre).ToString();
            if (sifre == realSifre && !String.IsNullOrEmpty(realSifre))
            {
                yetkiSeviyesi = personel[0].Yetki_Seviyesi;
                MessageBox.Show("Giriş Başarılı");
                LogInCheck  = true;
                label3.Text = "Kullanıcı Adı: " + kullaniciAdi;
                SignIn.Hide();
                SignOut.Show();
            }
            else
            {
                MessageBox.Show("Kullanıcı Adı Veya Şifre Yanlış");
            }
        }
Ejemplo n.º 11
0
        public async Task <IHttpActionResult> persons([FromBody] SignIn signInData)
        {
            try
            {
                Person objPerson = new Person();
                var    a         = await objPerson.GetAllSubCategories(4);


                JArray arrayOfUSer = JArray.Parse(File.ReadAllText(HttpContext.Current.Server.MapPath("~/Models/AuthData/UserAuthData.json")));
                string email       = signInData.Email;
                string quarry      = "[?(@.Email == " + "'" + signInData.Email + "'" + "&&" + "@.Password ==" + "'" + signInData.Password + "'" + ")]";

                JToken acme = arrayOfUSer.SelectToken(quarry);


                return(personModel.CachedOk(controller: this, content: a,
                                            cachingTimeSpan: TimeSpan.FromHours(value: 1)));;
            }
            catch (Exception exception)
            {
                return(InternalServerError(exception: exception));
            }
        }
        public async Task <IActionResult> ChangePassword(SignIn obj)
        {
            if (ModelState.IsValid)
            {
                var result = signinManager.PasswordSignInAsync(obj.UserName, obj.Password, obj.RememberMe, false).Result;
                var user   = await userManager.FindByNameAsync(obj.UserName);


                if (result.Succeeded)
                {
                    var newPassword = userManager.PasswordHasher.HashPassword(user, obj.NewPassword);
                    user.PasswordHash = newPassword;
                    await userManager.UpdateAsync(user);

                    return(RedirectToAction("Index", "CMS"));
                }
                else
                {
                    ModelState.AddModelError("", "Invalid user details");
                }
            }
            return(View(obj));
        }
Ejemplo n.º 13
0
        public void Inititalize()
        {
            Console.WriteLine("BeforeScenario");
            scenario = featureName.CreateNode <AventStack.ExtentReports.Gherkin.Model.Scenario>(ScenarioContext.Current.ScenarioInfo.Title);
            //initialize browser
            driver = new ChromeDriver();
            //InitializeBrowser(paths.Browser);
            objectContainer.RegisterInstanceAs(driver);
            driver.Navigate().GoToUrl(paths.BaseUrl);

            //go to sign in or signup
            if (MarsResource.IsLogin == "true")
            {
                SignIn loginobj = new SignIn(driver);

                loginobj.LoginSteps();
            }
            else
            {
                SignUp signUpobj = new SignUp(driver);
                signUpobj.register();
            }
        }
Ejemplo n.º 14
0
        private async void GoogleAuthenticatorCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Enter GoogleAuthenticatorCompleted");
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= GoogleAuthenticatorCompleted;
                authenticator.Error     -= GoogleAuthenticatorError;
            }

            if (e.IsAuthenticated)
            {
                MainPage.account.isCalendarActive = true;
                MainPage.account.accessToken      = e.Account.Properties["access_token"];
                MainPage.account.refreshToken     = e.Account.Properties["refresh_token"];
                SignIn.SaveUser(MainPage.account);
            }
            else
            {
                await DisplayAlert("Error", "Google was not able to autheticate your account", "OK");
            }
        }
Ejemplo n.º 15
0
        void CalendarToggle(System.Object sender, Xamarin.Forms.ToggledEventArgs e)
        {
            if (e.Value == false)
            {
                MainPage.account.isCalendarActive = false;
            }
            else
            {
                if (MainPage.account.platform != "GOOGLE")
                {
                    if (!MainPage.account.isCalendarActive)
                    {
                        GoogleLogInClick();
                    }
                }
                else
                {
                    MainPage.account.isCalendarActive = true;
                }
            }

            SignIn.SaveUser(MainPage.account);
        }
      public async Task <ActionResult> SignIn(SignIn model, string ReturnUrl)
      {
          if (!ModelState.IsValid)
          {
              return(View(model));
          }

          var result = await frameworkSignInManager.PasswordSignInAsync(model.Email, model.Password, model.rememberMe, shouldLockout : true);

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

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

          case SignInStatus.Failure:
          default:
              ModelState.AddModelError("", "Invalid sign in  attempt. ");
              return(View(model));
          }
      }
Ejemplo n.º 17
0
        public async Task signin_request_fails_when_password_is_incorrect()
        {
            var id            = Guid.NewGuid();
            var email         = "*****@*****.**";
            var fullname      = "fullname";
            var password      = "******";
            var wrongPassword = "******";
            var role          = Role.User;
            var securityStamp = new Guid().ToString();

            // Add user
            var user = new User(id, email, fullname, "test.nl/image", _passwordService.Hash(password), role,
                                securityStamp, 0, DateTime.MinValue, DateTime.UtcNow, new string[] { });
            await _mongoDbFixture.InsertAsync(user.AsDocument());

            var request = new SignIn(email, wrongPassword);

            // Check if exception is thrown
            var requestResult = _requestHandler
                                .Awaiting(c => c.HandleAsync(request));

            requestResult.Should().Throw <InvalidCredentialsException>();
        }
Ejemplo n.º 18
0
        public ActionResult LoginVerify(SignIn user)
        {
            if (ModelState.IsValid)
            {
                User datauser = new User {
                    UserName = user.NameOfUser, Password = user.PassKey
                };


                if (ur.LoginVerification(datauser.UserName, datauser.Password))
                {
                    mycookie["UserName"] = user.NameOfUser;
                    mycookie.Expires     = DateTime.Now.AddDays(1);
                    Response.Cookies.Add(mycookie);
                }
                else
                {
                    ViewBag.ErrorLogin = "******";
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 19
0
        private void SignInThread(object credentialsObj)
        {
            // Try to Sign In
            try
            {
                var credentials = (UserCredentials)credentialsObj;

                // Send Signin Package to Server
                SignInResponse response = SignIn.AttemptSignIn(credentials.Username, credentials.Password);
                if (response == null || !response.Successful)
                {
                    Dispatcher.Invoke(new Action(delegate { MetroMessageBox.Show("Unable to Sign In", response.ErrorMessage); }));
                    return;
                }

                // Set the UI to show that we have signed in successfully
                Dispatcher.Invoke(new Action(delegate
                {
                    gridNetworkType.Visibility = gridSignedIn.Visibility = Visibility.Visible;
                    gridSignIn.Visibility      = Visibility.Collapsed;
                    lblSignedInWelcome.Text    = response.DisplayName.ToLower();
                    lblSignedInPosts.Text      = string.Format("posts: {0:##,###}", response.PostCount);

                    // Validate Avatar
                    if (!string.IsNullOrEmpty(response.AvatarUrl) && response.AvatarUrl != "http://uploads.xbchaos.netdna-cdn.com/")
                    {
                        ImageLoader.LoadImageAndFade(imgSignedInAvatar, new Uri(response.AvatarUrl), new AnimationHelper(this));
                    }

                    MetroMessageBox.Show("welcome", "Welcome to network poking, " + response.DisplayName);
                }));
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(new Action(delegate { MetroException.Show(ex); }));
            }
        }
Ejemplo n.º 20
0
        public void Inititalize()
        {
            // advisasble to read this documentation before proceeding http://extentreports.relevantcodes.com/net/

            //Choosing and defining the Browser
            switch (Browser)
            {
            case 1:
                GlobalDefinitions.driver = new FirefoxDriver();
                break;

            case 2:
                GlobalDefinitions.driver = new ChromeDriver();
                GlobalDefinitions.driver.Manage().Window.Maximize();
                break;
            }


            #region Initialise Reports

            //extent = new ExtentReports(ReportPath, false, DisplayOrder.NewestFirst);
            extent = new ExtentReports(@"MarsFramework\TestReports\TestRunReport.html", false, DisplayOrder.NewestFirst);
            extent.LoadConfig(MarsResource.ReportXMLPath);

            #endregion

            if (MarsResource.IsLogin == "true")
            {
                SignIn loginobj = new SignIn();
                loginobj.LoginSteps();
            }
            else
            {
                SignUp obj = new SignUp();
                obj.register();
            }
        }
Ejemplo n.º 21
0
        public void Inititalize()
        {
            // advisasble to read this documentation before proceeding http://extentreports.relevantcodes.com/net/
            switch (Browser)
            {
            case 1:
                GlobalDefinitions.driver = new FirefoxDriver();
                break;

            case 2:
                GlobalDefinitions.driver = new ChromeDriver();
                GlobalDefinitions.driver.Manage().Window.Maximize();
                break;
            }
            ExcelLib.PopulateInCollection(Base.ExcelPath, "SignIn");

            driver.Navigate().GoToUrl(ExcelLib.ReadData(2, "Url"));

            #region Initialise Reports

            extent = new ExtentReports(ReportPath, false, DisplayOrder.NewestFirst);
            extent.LoadConfig(MarsResource.ReportXMLPath);
            test = extent.StartTest("Tests");

            #endregion

            if (MarsResource.IsLogin == "true")
            {
                SignIn loginobj = new SignIn();
                loginobj.LoginSteps();
            }
            else
            {
                SignUp obj = new SignUp();
                obj.register();
            }
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> SignIn(SignIn model)
        {
            AppUser usr = client.CreateDocumentQuery <AppUser>(userCollectionUri).Where(u => u.UserName == model.UserName && u.Password == model.Password).AsEnumerable().SingleOrDefault();

            bool isUserValid = (usr == null ? false : true);

            if (ModelState.IsValid && isUserValid)
            {
                var claims = new List <Claim>();

                claims.Add(new Claim(ClaimTypes.Name, usr.UserName));

                claims.Add(new Claim(ClaimTypes.Role, usr.Role));

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

                var principal = new ClaimsPrincipal(identity);

                var props = new AuthenticationProperties();
                props.IsPersistent = model.RememberMe;

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.
                    AuthenticationScheme,
                    principal, props);

                return(RedirectToAction("List", "EmployeeManager"));
            }
            else
            {
                ModelState.AddModelError("", "Invalid UserName         or Password!");
            }

            return(View());
        }
Ejemplo n.º 23
0
        ///// <summary>
        ///// 元宝兑换e币
        ///// </summary>
        ///// <param name="元宝数">ybnum</param>
        ///// <returns></returns>
        //public string ybToeb(int ybnum)
        //{
        //    using (var db = new shhouseEntities())
        //    {
        //        try
        //        {
        //            var user_details = db.user_details.Find(User.userid);
        //            var user_member = db.user_member.Find(User.userid);
        //            if (ybnum > user_details.silvertotal)
        //            {
        //                return JsonConvert.SerializeObject(new repmsg { state = 2, msg = "兑换元宝大于已拥有的数量!" , data =null});
        //                }
        //            user_details.silvertotal = user_details.silvertotal - ybnum;
        //            user_member.ebtotalnum = user_member.ebtotalnum + (ybnum / 100);
        //            db.SaveChanges();

        //            return JsonConvert.SerializeObject(new repmsg { state = 1, msg = "兑换成功!", data = null });
        //        }
        //        catch
        //        {
        //            return JsonConvert.SerializeObject(new repmsg { state = 1, msg = "兑换失败!", data = null });
        //        }
        //    }

        //}

        /// <summary>
        /// 签到 http://192.168.1.223/GR_User/SignIn
        /// </summary>
        /// <returns></returns>
        public string SignIn()
        {
            using (var db = new shhouseEntities())
            {
                DateTime sdt = DateTime.Now.Date;
                DateTime dt  = DateTime.Now.Date.AddDays(1);

                var SignIn = db.SignIn.Where(x => x.UserID == User.userid && x.exe_date >= sdt && x.exe_date < dt).FirstOrDefault();
                if (SignIn != null)
                {
                    return(JsonConvert.SerializeObject(new repmsg {
                        state = 2, msg = "今日已签过!", data = null
                    }));
                }
                else
                {
                    var stephen = new SignIn
                    {
                        UserID   = User.userid,
                        exe_date = DateTime.Now
                    };
                    var user_score_wuxi = new user_score_wuxi
                    {
                        userid           = User.userid,
                        addtime          = DateTime.Now,
                        score            = 2,
                        obtaindirections = "签到积分"
                    };
                    db.user_score_wuxi.Add(user_score_wuxi);
                    db.SignIn.Add(stephen);
                    db.SaveChanges();
                    return(JsonConvert.SerializeObject(new repmsg {
                        state = 1, msg = "签到成功!", data = null
                    }));
                }
            }
        }
Ejemplo n.º 24
0
        public void Inititalize()
        {
            GlobalDefinitions.ExcelLib.PopulateInCollection(@"C:\Users\Neelam\Desktop\Mars project\MarsFramework-master\MarsFramework\ExcelData\TestDataShareSkill.xlsx", "SignIn");

            // advisasble to read this documentation before proceeding http://extentreports.relevantcodes.com/net/
            switch (Browser)
            {
            case 1:
                GlobalDefinitions.driver = new FirefoxDriver();
                driver.Navigate().GoToUrl(GlobalDefinitions.ExcelLib.ReadData(2, "Url"));
                break;

            case 2:
                GlobalDefinitions.driver = new ChromeDriver();
                GlobalDefinitions.driver.Manage().Window.Maximize();
                driver.Navigate().GoToUrl(GlobalDefinitions.ExcelLib.ReadData(2, "Url"));
                break;
            }

            #region Initialise Reports

            extent = new ExtentReports(ReportPath, false, DisplayOrder.NewestFirst);
            extent.LoadConfig(MarsResource.ReportXMLPath);

            #endregion

            if (MarsResource.IsLogin == "true")
            {
                SignIn loginobj = new SignIn();
                loginobj.LoginSteps();
            }
            else
            {
                SignUp obj = new SignUp();
                obj.register();
            }
        }
Ejemplo n.º 25
0
        public async Task <AuthDto> SignInAsync(SignIn command)
        {
            if (!EmailRegex.IsMatch(command.Email))
            {
                _logger.LogError($"Invalid email: {command.Email}");
                throw new InvalidEmailException(command.Email);
            }

            var user = await _userRepository.GetAsync(command.Email);

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                _logger.LogError($"User with email: {command.Email} was not found.");
                throw new InvalidCredentialsException(command.Email);
            }

            if (!_passwordService.IsValid(user.Password, command.Password))
            {
                _logger.LogError($"Invalid password for user with id: {user.Id.Value}");
                throw new InvalidCredentialsException(command.Email);
            }

            var claims = user.Permissions.Any()
                ? new Dictionary <string, IEnumerable <string> >
            {
                ["permissions"] = user.Permissions
            }
                : null;
            var auth = _jwtProvider.Create(user.Id, user.Role, claims: claims);

            auth.RefreshToken = await _refreshTokenService.CreateAsync(user.Id);

            _logger.LogInformation($"User with id: {user.Id} has been authenticated.");
            await _messageBroker.PublishAsync(new SignedIn(user.Id, user.Role));

            return(auth);
        }
        public IActionResult SignIn(SignIn model)
        {
            AppUser obj = this.users.Find(u => u.UserName == model.UserName && u.Password == model.Password).FirstOrDefault();

            bool isUserValid = (obj == null ? false : true);

            if (ModelState.IsValid && isUserValid)
            {
                var claims = new List <Claim>();

                claims.Add(new Claim(ClaimTypes.Name, obj.UserName));

                claims.Add(new Claim(ClaimTypes.Role, obj.Role));

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

                var principal = new ClaimsPrincipal(identity);

                var props = new AuthenticationProperties();
                props.IsPersistent = model.RememberMe;

                HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.
                    AuthenticationScheme,
                    principal, props).Wait();

                return(RedirectToAction("List", "EmployeeManager"));
            }
            else
            {
                ModelState.AddModelError("", "Invalid UserName         or Password!");
            }

            return(View());
        }
        public void InititalizeTest()
        {
            // advisasble to read this documentation before proceeding http://extentreports.relevantcodes.com/net/

            ChooseBrowser(_BrowserType);


            void ChooseBrowser(BrowserType browserType)
            {
                if (browserType == BrowserType.Firefox)
                {
                    _driver = new FirefoxDriver();
                }
                else if (browserType == BrowserType.Chrome)
                {
                    _driver = new ChromeDriver();
                }
            }

            #region Initialise Reports

            extent = new ExtentReports(ReportPath, false, DisplayOrder.NewestFirst);
            extent.LoadConfig(ReportXMLPath);

            #endregion

            if (MarsResource.IsLogin == "true")
            {
                SignIn loginobj = new SignIn(_driver);
                loginobj.LoginSteps();
            }
            else
            {
                SignUp obj = new SignUp(_driver);
                obj.register();
            }
        }
        public async Task signin_endpoint_runs_performantly()
        {
            const int duration    = 3;
            const int expectedRps = 50;

            var id            = Guid.NewGuid();
            var email         = "*****@*****.**";
            var fullname      = "fullname";
            var password      = "******";
            var role          = Role.User;
            var securityStamp = new Guid().ToString();

            // Add user
            var user = new User(id, email, fullname, "test.nl/image", _passwordService.Hash(password), role,
                                securityStamp, 0, DateTime.MinValue, DateTime.UtcNow, new string[] { });
            await _mongoDbFixture.InsertAsync(user.AsDocument());

            var step = Step.Create("sendPost", async context =>
            {
                var request  = new SignIn(email, password);
                var response = await Act(request);
                return(response.IsSuccessStatusCode ? Response.Ok() : Response.Fail());
            });


            var scenario = ScenarioBuilder.CreateScenario("GET resources", step)
                           .WithLoadSimulations(new[]
            {
                Simulation.InjectPerSec(rate: expectedRps, during: TimeSpan.FromSeconds(duration))
            });

            var result = NBomberRunner
                         .RegisterScenarios(scenario)
                         .Run().ScenarioStats.First();

            result.OkCount.Should().BeGreaterOrEqualTo(expectedRps * duration);
        }
Ejemplo n.º 29
0
        public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
        {
            // Perform any operations on signed in user here.
            if (user != null && error == null)
            {
                // VERY IMPORTANT: We create an OAuth2Authentication instance here
                // to use later with the google plus API since it expects this old
                // type of object
                currentAuth = new Google.OpenSource.OAuth2Authentication {
                    ClientId       = signIn.ClientID,
                    AccessToken    = user.Authentication.AccessToken,
                    ExpirationDate = user.Authentication.AccessTokenExpirationDate,
                    RefreshToken   = user.Authentication.RefreshToken,
                    TokenURL       = new NSUrl("https://accounts.google.com/o/oauth2/token")
                };

                // Start fetching the signed in user's info
                GetUserInfo();

                status.Caption = string.Format("{0} (Tap to Sign Out)", user.Profile.Name);

                ToggleAuthUI();
            }
        }
Ejemplo n.º 30
0
        public async Task ChangePassword_ShouldReturnNoContent_WhenUserIsAuthorized()
        {
            var signUp = new SignUp
            {
                Username = "******",
                Email    = "*****@*****.**",
                Password = "******"
            };

            await _client.PostAsJsonAsync("api/account/signup", signUp);

            var signIn = new SignIn
            {
                Username = "******",
                Password = "******"
            };

            var signInResponse = await _client.PostAsJsonAsync("/api/account/signin", signIn);

            var signInResult = await signInResponse.Content.ReadAsStringAsync();

            var jwt = JsonConvert.DeserializeObject <JwtDto>(signInResult);

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwt.AccessToken);

            var changePassword = new ChangePassword
            {
                OldPassword = "******",
                NewPassword = "******"
            };

            var response = await _client.PatchAsJsonAsync("api/account/changepassword", changePassword);

            response.EnsureSuccessStatusCode();
            response.StatusCode.ShouldBe(HttpStatusCode.NoContent);
        }
Ejemplo n.º 31
0
        public void Inititalize()
        {
            switch (Browser)
            {
            case 1:
                GlobalDefinitions.driver = new FirefoxDriver();
                break;

            case 2:
                GlobalDefinitions.driver = new ChromeDriver(@"D:\MVP Env\marsframework\MarsFramework");
                GlobalDefinitions.driver.Manage().Window.Maximize();
                GlobalDefinitions.driver.Navigate().GoToUrl("http://localhost:5000/Account/Profile");

                break;
            }

            #region Initialise Reports

            extent = new ExtentReports(ReportPath, false, DisplayOrder.NewestFirst);
            extent.LoadConfig(MarsResource.ReportXMLPath);



            #endregion

            if (MarsResource.IsLogin == "true")
            {
                SignIn loginobj = new SignIn();
                loginobj.LoginSteps();
            }
            else
            {
                SignUp obj = new SignUp();
                obj.Register();
            }
        }
Ejemplo n.º 32
0
        public async Task <IActionResult> Login(SignIn user)
        {
            var clientView = this.user.Users.FirstOrDefault(x => x.Login == user.Login);

            if (clientView == null || !string.IsNullOrEmpty(clientView.Password) && clientView.Password != user.Password)
            {
                ModelState.AddModelError("", "Вы ввели неверный пароль, либо пользователь не найден");
                return(View(user));
            }
            if (clientView.BlockStatus == true)
            {
                ModelState.AddModelError("", "Пользователь заблокирован");
                return(View(user));
            }
            var usr = new User();

            usr.Login       = clientView.Login;
            usr.BlockStatus = clientView.BlockStatus;
            if (usr.Login == "Admin")
            {
                usr.Role = "admin";
            }
            else
            {
                usr.Role = "user";
            }
            if (string.IsNullOrEmpty(clientView.Password))
            {
                clientView.Password = user.Password;
                this.user.AddUser(clientView);
            }

            await Authenticate(usr);

            return(RedirectToAction("Profile", "Account"));
        }
        public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
        {
            // Perform any operations on signed in user here.
            if (user != null && error == null) {

                // VERY IMPORTANT: We create an OAuth2Authentication instance here
                // to use later with the google plus API since it expects this old
                // type of object
                currentAuth = new Google.OpenSource.OAuth2Authentication {
                    ClientId = signIn.ClientID,
                    AccessToken = user.Authentication.AccessToken,
                    ExpirationDate = user.Authentication.AccessTokenExpirationDate,
                    RefreshToken = user.Authentication.RefreshToken,
                    TokenURL = new NSUrl ("https://accounts.google.com/o/oauth2/token")
                };

                // Start fetching the signed in user's info
                GetUserInfo ();

                status.Caption = string.Format ("{0} (Tap to Sign Out)", user.Profile.Name);

                ToggleAuthUI ();
            }
        }
Ejemplo n.º 34
0
        public void DidSignIn(SignIn signIn, GoogleUser user, NSError error)
        {
            if (error == null && user != null)
            {
                // Perform any operations on signed in user here.
                var userId      = user.UserID;                 // For client-side use only!
                var idToken     = user.Authentication.IdToken; // Safe to send to the server
                var accessToken = user.Authentication.AccessToken;
                var serverAuth  = user.ServerAuthCode;
                var fullName    = user.Profile.Name;
                var givenName   = user.Profile.GivenName;
                var familyName  = user.Profile.FamilyName;
                var email       = user.Profile.Email;
                var imageUrl    = user.Profile.GetImageUrl(64);
                // ...;
                Log.Debug($"\n\tuserId: {userId},\n\tidToken: {idToken},\n\taccessToken: {accessToken},\n\tserverAuth: {serverAuth},\n\tfullName: {fullName},\n\tgivenName: {givenName},\n\tfamilyName: {familyName},\n\temail: {email},\n\timageUrl: {imageUrl},\n\t");

                var details = new ClientAuthDetails
                {
                    ClientAuthProvider = ClientAuthProviders.Google,
                    Username           = user.Profile?.Name,
                    Email     = user.Profile?.Email,
                    Token     = user.Authentication?.IdToken,
                    AuthCode  = user.ServerAuthCode,
                    AvatarUrl = user.Profile.GetImageUrl(AvatarSize * (nuint)UIScreen.MainScreen.Scale)?.ToString()
                };

                ClientAuthManager.Shared.SetClientAuthDetails(details);

                DismissViewController(true, null);
            }
            else
            {
                Log.Error(error?.LocalizedDescription);
            }
        }
Ejemplo n.º 35
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world");
            IWebDriver driver = new ChromeDriver();

            //IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://www.automationpractice.com");

            //driver.FindElement(By.XPath("//*[@class='login']")).Click();


            IndexPage ip = new IndexPage(driver);

            ip.clickSignInLink();


            SignIn si = new SignIn(driver);

            si.enterRegisteredEmailAddress("*****@*****.**");
            si.enterPassword("Automation123");
            si.clickSignIn();

            Assert.IsTrue(si.isAuthenticationFailedDisplayed());

            MyAccount myacc = new MyAccount(driver);

            Assert.IsFalse(myacc.isAuthenticationSuccessful());

            myacc.hoverShoppingCart();
            myacc.openCart();


            Thread.Sleep(5000);
            driver.Close();
            driver.Quit();
        }
Ejemplo n.º 36
0
        //Validate the password is changed
        internal void ValidateChangedPassword()
        {
            try
            {
                SignIn loginobj = new SignIn();
                loginobj.SignOutSteps();

                //Click on Sign In button
                SignIntab.Click();

                //Enter UserName
                Email.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Username"));

                //Enter the changed Password
                Password.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "New Password"));

                //Click Login Button
                LoginBtn.Click();
                Thread.Sleep(5000);

                GlobalDefinitions.ValidateBoolean(ChangePasswordDropDownLink.Displayed, "Password Changed");
            }
            catch (Exception e)
            {
                Base.test.Log(LogStatus.Fail, "Caught Exception For Change Password", e.Message);
            }

            //Resetting the password
            ChangePasswordDropDownLink.Click();
            Extension.WaitForElementDisplayed(GlobalDefinitions.Driver, By.XPath("//a[text()='Change Password']"), 5);
            ChangePasswordLink.Click();
            CurrentPassword.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "New Password"));
            NewPassword.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Password"));
            ConfirmPassword.SendKeys(GlobalDefinitions.ExcelLib.ReadData(2, "Password"));
            SaveChangedPassword.Click();
        }
Ejemplo n.º 37
0
        public void LogIn()
        {
            if (Int32.TryParse(PersonalNum, out var id))
            {
                using (GasStationModel db = new GasStationModel())
                {
                    if (db.Personal.Count(x => x.Personal_Num == id && x.Password == Password) == 1)
                    {
                        Connecting = "Вхід";
                        var personal = db.Personal.Single(x => x.Personal_Num == id && x.Password == Password);

                        SignIn?.Invoke(this, new PersonalEventArgs()
                        {
                            Personal = personal
                        });
                    }
                    else
                    {
                        MessageBox.Show("Помилка входу! \nПрацівника не існує або невірний пароль", "Помилка входу",
                                        MessageBoxButton.OK);
                    }
                }
            }
        }
Ejemplo n.º 38
0
        public async Task <IActionResult> Login([FromBody] SignIn signIn)
        {
            if (ModelState.IsValid)
            {
                UserDTO userDto = _mapper.Map <SignIn, UserDTO>(signIn);
                User    user    = await _userManager.FindByNameAsync(userDto.Login);

                if (user != null)
                {
                    if (!await _userManager.IsEmailConfirmedAsync(user))
                    {
                        return(Unauthorized());
                    }
                    else
                    {
                        Identity.SignInResult result = await _userService.SignIn(userDto);

                        return(Ok(result.Succeeded));
                    }
                }
                return(NotFound());
            }
            return(BadRequest(ModelState));
        }
Ejemplo n.º 39
0
        public void Inititalize()
        {
            //initialize browser
            InitializeBrowser(Browser);
            driver.Navigate().GoToUrl(BaseUrl);

            #region Initialise Reports

            extent = new ExtentReports(ReportPath, false, DisplayOrder.NewestFirst);
            extent.LoadConfig(MarsResource.ReportXMLPath);

            #endregion

            if (MarsResource.IsLogin == "true")
            {
                SignIn loginobj = new SignIn();
                loginobj.LoginSteps();
            }
            else
            {
                SignUp obj = new SignUp();
                obj.register();
            }
        }
Ejemplo n.º 40
0
        public void skillProfile()
        {   //using Chrome
            using (GlobalDefinitions.driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)))
            //Using Firefox
            //using (GlobalDefinitions.driver = new FirefoxDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)))
            {
                string ProfileMenuOption = "Profile";
                string addNewOption      = "Skills";

                //sign in
                SignIn newSignIn = new SignIn();
                newSignIn.LoginSteps();

                //MenuOption to Click
                ClickMenu clickMenu = new ClickMenu();
                clickMenu.clickMenuOptions(ProfileMenuOption);

                //click on options Language, Skills, Education, Certifications
                clickMenu.clickSubMenuOptions(addNewOption);

                //click on Add New button
                ProfileOptions addNewButton = new ProfileOptions();
                addNewButton.clickAddNew(addNewOption);

                //add and verify Skill
                ProfileSkill addSkill = new ProfileSkill();
                addSkill.addNewSkill();
                addSkill.rowSkillPresent();
            }

            //[AssemblyCleanup]
            //public static void TearDown()
            //{
            //    GlobalDefinitions.driver.Quit();
            //}
        }
Ejemplo n.º 41
0
        private void InitSunVoteDll()
        {
            try
            {
                this.baseConn = new BaseConnection();
                this.signIn = new SignIn();
                this.number = new Number();
                this.choices = new Choices();

                signIn.BaseConnection = baseConn;
                number.BaseConnection = baseConn;
                choices.BaseConnection = baseConn;

                this.baseConn.BaseOnLine += new IBaseConnectionEvents_BaseOnLineEventHandler(this.baseConn_BaseOnLine);

                this.signIn.KeyStatus += new ISignInEvents_KeyStatusEventHandler(this.signIn_KeyStatus);
                this.number.KeyStatus += new INumberEvents_KeyStatusEventHandler(this.number_KeyStatus);
                this.choices.KeyStatus += new IChoicesEvents_KeyStatusEventHandler(this.choices_KeyStatus);
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 42
0
        private void ShowSignIn()
        {
            if (_SignIn == null)
            {
                _SignIn = new SignIn(this, _UserModel);
            }
            ShowView(_SignIn);
            _SignAc = _SignIn;

            MiOpen.Visible = true;
            MiSep0.Visible = true;
            MiPcSignUp.Visible = true;
            MiSignFk.Visible = true;
            MiSep1.Visible = true;
            MiUpgrade.Visible = true;
            MiSep2.Visible = true;

            Text = "用户登录";
            BtOk.Text = "登录(&O)";
        }
Ejemplo n.º 43
0
        public void IsValid_WhenAllRulesPass()
        {
            var userName = FakeData.String();
            var password = FakeData.String();
            var queries = new Mock<IProcessQueries>(MockBehavior.Strict);
            var validator = new ValidateSignInCommand(queries.Object);
            var command = new SignIn { UserNameOrVerifiedEmail = userName, Password = password, };
            Expression<Func<IsPasswordVerified, bool>> passwordQuery = x =>
                x.UserNameOrVerifiedEmail == command.UserNameOrVerifiedEmail && x.Password == command.Password;
            queries.Setup(x => x.Execute(It.Is(passwordQuery))).Returns(Task.FromResult(true));
            Expression<Func<UserByNameOrVerifiedEmail, bool>> userQuery = x => x.NameOrEmail == command.UserNameOrVerifiedEmail;
            queries.Setup(x => x.Execute(It.Is(userQuery))).Returns(Task.FromResult(new User()));

            var result = validator.Validate(command);

            result.IsValid.ShouldBeTrue();
            queries.Verify(x => x.Execute(It.Is(passwordQuery)), Times.Once);
            queries.Verify(x => x.Execute(It.Is(userQuery)), Times.AtLeastOnce);
        }
Ejemplo n.º 44
0
 public void DidSignIn (SignIn signIn, GoogleUser user, Foundation.NSError error)
 {
     InvokeOnMainThread (async delegate {
         await AuthWithGoogleTokenAsync (signIn, user, error);
     });
 }
Ejemplo n.º 45
0
 public ActionResult SignIn(SignIn command, string returnUrl)
 {
     return Handle(command, () => GetRedirectResult(returnUrl), () => RedirectToAction("SignIn", "Account"));
 }
		public ActionResult SignIn(SignIn command, string returnUrl)
		{
			return Form(command, GetRedirectResult(returnUrl));
		}
 public virtual void DidDisconnect(SignIn signIn, GoogleUser user, NSError error)
 {
     currentAuth = null;
     Root [1].Clear ();
     ToggleAuthUI ();
 }
Ejemplo n.º 48
0
 public async Task AuthWithGoogleTokenAsync (SignIn signIn, GoogleUser user, Foundation.NSError error)
 {
     try {
         if (error == null) {
             IsAuthenticating = true;
             var token = user.Authentication.AccessToken;
             var authManager = ServiceContainer.Resolve<AuthManager> ();
             var authRes = await authManager.AuthenticateWithGoogleAsync (token);
             // No need to keep the users Google account access around anymore
             signIn.DisconnectUser ();
             if (authRes != AuthResult.Success) {
                 var email = user.Profile.Email;
                 AuthErrorAlert.Show (this, email, authRes, AuthErrorAlert.Mode.Login, true);
             } else {
                 // Start the initial sync for the user
                 ServiceContainer.Resolve<ISyncManager> ().Run ();
             }
         } else if (error.Code != -5) { // Cancel error code.
             new UIAlertView ("WelcomeGoogleErrorTitle".Tr (), "WelcomeGoogleErrorMessage".Tr (), null, "WelcomeGoogleErrorOk".Tr (), null).Show ();
         }
     } catch (InvalidOperationException ex) {
         var log = ServiceContainer.Resolve<ILogger> ();
         log.Info (Tag, ex, "Failed to authenticate (G+) the user.");
     } finally {
         IsAuthenticating = false;
     }
 }