public async Task CreateUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); // Create and save a user. var user = new TestUser { UserName = "******" }; using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); transaction.Commit(); } // Check the user has an id. Assert.IsNotNull(user.Id); // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(user.Id); transaction.Commit(); } // Check we have the same user. Assert.AreEqual(user.Id, loadUser.Id); Assert.AreEqual(user.UserName, loadUser.UserName); }
public void StoreUserWithOneUniqueConstraint() { var ravenSession = DocumentStore.OpenSession(); var testUser1 = new TestUser { Name = "Test User", Username = "******", EmailAddres = null }; ravenSession.Store(testUser1); ravenSession.SaveChanges(); var testUser2 = new TestUser { Name = "Test User2", Username = "******", EmailAddres = null }; //this line throws a null reference exception var checkResult = ravenSession.CheckForUniqueConstraints(testUser2); Assert.False(checkResult.ConstraintsAreFree()); ravenSession.Dispose(); }
public void ComplexTypeReader() { var user = new TestUser { Contact = new Contact { Address = new Address { City = "Tallinn", Country = "Estonia"}, PhoneNumber = "1234567"}, FirstName = "Max", LastName = "Lego", Id = Guid.NewGuid() }; var emptyUser = new TestUser(); using (var ctx = new TestContext()) { var tableMapping = ctx.Db<TestUser>(); var tableMappings = new Dictionary<Type, IEntityMap> { {typeof (TestUser), tableMapping} }; using (var reader = new MappedDataReader<TestUser>(new[] { user, emptyUser }, tableMappings)) { Assert.AreEqual(9, reader.FieldCount); while (reader.Read()) { for (int i = 0; i < reader.FieldCount; ++i) { Console.WriteLine("{0}: {1}", i, reader.GetValue(i)); } } } } }
public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails() { var user = new TestUser("test"); var userManager = MockHelpers.MockUserManager<TestUser>(); var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>(); var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero }; var options = new Mock<IOptions<IdentityOptions>>(); options.Setup(a => a.Value).Returns(identityOptions); var httpContext = new Mock<HttpContext>(); var contextAccessor = new Mock<IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object); var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object, contextAccessor.Object, claimsManager.Object, options.Object, null); signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(null).Verifiable(); var services = new ServiceCollection(); services.AddSingleton(options.Object); services.AddSingleton(signInManager.Object); services.AddSingleton<ISecurityStampValidator>(new SecurityStampValidator<TestUser>(options.Object, signInManager.Object)); httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); var id = new ClaimsIdentity(identityOptions.Cookies.ApplicationCookieAuthenticationScheme); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow }, identityOptions.Cookies.ApplicationCookieAuthenticationScheme); var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions()); Assert.NotNull(context.Properties); Assert.NotNull(context.Options); Assert.NotNull(context.Principal); await SecurityStampValidator.ValidatePrincipalAsync(context); Assert.Null(context.Principal); signInManager.VerifyAll(); }
public void CT_ET_Validation_OnClient() { var user = new TestUser(); var brokenRules = user.Validate(); Assert.AreEqual(brokenRules.Count, 1); Assert.AreEqual(brokenRules[0].Description, "编码 里没有输入值。"); }
protected void Button1_Click(object sender, EventArgs e) { TestUser user=new TestUser(); WebFormHelper.GetDataFromForm(this, user); FT.DAL.Orm.SimpleOrmOperator.Create(user); WebTools.Alert("添加成功!"); WebTools.CloseSelf(this); }
public void NavigateToUserSettings() { var user = new TestUser(); AcademyLoginProvider.Instance.LoginUser(user); this.LoginPage.WaitForUserName(); this.LoginPage.Validator.ValidateUserName(user.Username); this.SettingsPage.Navigate(); this.SettingsPage.Validator.UsernameLabel(user.Username); }
private static Order PrepareOneOrderData(string orderNumber, TestUser creator) { Order order = new Order(); order.OrderNumber = orderNumber; order.Creator = creator; return order; }
public ActionResult SetTestUser() { TestUser user = new TestUser { Identity = (User as GeneralUser).Identity, Token = (User as GeneralUser).Token }; LoggedinPersonsCache.Current.UpdatePerson(user); return RedirectToAction("Index"); }
public virtual void Init() { store = new TestUserStore(); manager = new TestIdentityRebootUserManager(store, 100); user = new TestUser() { UserName = username }; var result = manager.Create(user, password); Assert.IsTrue(result.Succeeded); }
async public Task ThenItIsAddedToTheList() { var store = new UserStore<TestUser>(); var user = new TestUser() { Id = "1", UserName = "******" }; await store.CreateAsync(user); var output = await store.FindByIdAsync("1"); Assert.IsNotNull(output); Assert.AreEqual("FStallone", output.UserName); }
public async Task ValidateFailsWithTooShortUserNames(string input) { // Setup var manager = MockHelpers.TestUserManager(new NoopUserStore()); var validator = new UserValidator<TestUser>(); var user = new TestUser {UserName = input}; // Act var result = await validator.ValidateAsync(manager, user); // Assert IdentityResultAssert.IsFailure(result, new IdentityErrorDescriber().InvalidUserName(input)); }
public void ET_AutoCollect() { //创建对象 var user = new TestUser(); var list = user.TestTreeTaskList; var taskRoot = list.AddNew(); var task1 = list.AddNew(); var task11 = list.AddNew(); var task111 = list.AddNew(); var task112 = list.AddNew(); var task12 = list.AddNew(); var task2 = list.AddNew(); var taskRoot2 = list.AddNew(); //关系 task1.TreeParent = taskRoot; task11.TreeParent = task1; task111.TreeParent = task11; task112.TreeParent = task11; task12.TreeParent = task1; task2.TreeParent = taskRoot; Assert.AreEqual(taskRoot.AllTimeByAutoCollect, 0); task111.AllTimeByAutoCollect += 1; Assert.AreEqual(task11.AllTimeByAutoCollect, 1); Assert.AreEqual(task1.AllTimeByAutoCollect, 1); Assert.AreEqual(taskRoot.AllTimeByAutoCollect, 1); Assert.AreEqual(user.TasksTimeByAutoCollect, 1); task12.AllTimeByAutoCollect += 1; Assert.AreEqual(task1.AllTimeByAutoCollect, 2); Assert.AreEqual(taskRoot.AllTimeByAutoCollect, 2); Assert.AreEqual(user.TasksTimeByAutoCollect, 2); task2.AllTimeByAutoCollect += 1; Assert.AreEqual(task1.AllTimeByAutoCollect, 2); Assert.AreEqual(taskRoot.AllTimeByAutoCollect, 3); Assert.AreEqual(user.TasksTimeByAutoCollect, 3); taskRoot2.AllTimeByAutoCollect += 1; Assert.AreEqual(user.TasksTimeByAutoCollect, 4); task111.AllTimeByAutoCollect -= 1; Assert.AreEqual(task11.AllTimeByAutoCollect, 0); Assert.AreEqual(task1.AllTimeByAutoCollect, 1); Assert.AreEqual(taskRoot.AllTimeByAutoCollect, 2); Assert.AreEqual(user.TasksTimeByAutoCollect, 3); }
public void TET_Query_DefaultOrderBy_TreeIndex() { var user = new TestUser { TestTreeTaskList = { new TestTreeTask { TreeChildren = { new TestTreeTask { TreeChildren = { new TestTreeTask(), new TestTreeTask(), } }, new TestTreeTask(), } } } }; var repo = RF.Concrete<TestTreeTaskRepository>(); using (RF.TransactionScope(repo)) { RF.Save(user); var list = repo.GetByParentId(user.Id); for (int i = 1, c = list.Count; i < c; i++) { var item1 = list[i - 1]; var item2 = list[i]; Assert.IsTrue(string.Compare(item1.TreeIndex, item2.TreeIndex) == -1, "默认应该按照 TreeIndex 正序排列。"); } //按照 Id 排序的功能应该无效。 var success = false; try { list = repo.GetAndOrderByIdDesc2(); success = true; } catch { } Assert.IsFalse(success, "默认应该按照 TreeIndex 正序排列。"); } }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { HttpRequestBase request = controllerContext.HttpContext.Request; TestUser obj = new TestUser(); obj.UserName = request.Form["UserName"]; obj.Company = request.Form["Company"]; String day = request.Form["day"]; String month = request.Form["month"]; String year = request.Form["year"]; obj.DOB = String.Format("{0}-{1}-{2}", day, month, year); return obj; }
public async Task DefaultAlphaNumericOnlyUserNameValidation(string userName, bool expectSuccess) { // Setup var manager = MockHelpers.TestUserManager(new NoopUserStore()); var validator = new UserValidator<TestUser>(); var user = new TestUser {UserName = userName}; // Act var result = await validator.ValidateAsync(manager, user); // Assert if (expectSuccess) { IdentityResultAssert.IsSuccess(result); } else { IdentityResultAssert.IsFailure(result); } }
public async Task VerifyAccountControllerSignIn(bool isPersistent) { var context = new Mock<HttpContext>(); var auth = new Mock<AuthenticationManager>(); context.Setup(c => c.Authentication).Returns(auth.Object).Verifiable(); auth.Setup(a => a.SignInAsync(new IdentityCookieOptions().ApplicationCookieAuthenticationScheme, It.IsAny<ClaimsPrincipal>(), It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable(); // REVIEW: is persistant mocking broken //It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Returns(Task.FromResult(0)).Verifiable(); var contextAccessor = new Mock<IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(contextAccessor.Object); services.AddIdentity<TestUser, TestRole>(); services.AddSingleton<IUserStore<TestUser>, InMemoryStore<TestUser, TestRole>>(); services.AddSingleton<IRoleStore<TestRole>, InMemoryStore<TestUser, TestRole>>(); var app = new ApplicationBuilder(services.BuildServiceProvider()); app.UseCookieAuthentication(); // Act var user = new TestUser { UserName = "******" }; const string password = "******"; var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>(); var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password)); var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false); // Assert Assert.True(result.Succeeded); context.VerifyAll(); auth.VerifyAll(); contextAccessor.VerifyAll(); }
public async Task CanAllowNonAlphaNumericUserName(string userName, bool expectSuccess) { // Setup var manager = MockHelpers.TestUserManager(new NoopUserStore()); manager.Options.User.AllowedUserNameCharacters = null; var validator = new UserValidator<TestUser>(); var user = new TestUser {UserName = userName}; // Act var result = await validator.ValidateAsync(manager, user); // Assert if (expectSuccess) { IdentityResultAssert.IsSuccess(result); } else { IdentityResultAssert.IsFailure(result); } }
public void TableMapping_ColumnsCount_TableWithComplexType() { using (var ctx = new TestContext()) { var tableMapping = ctx.Db<TestUser>(); var user = new TestUser { FirstName = "fn", LastName = "ln", Contact = new Contact { PhoneNumber = "123456", Address = new Address { City = "Tallinn", Country = "Estonia", County = "Harju", PostalCode = "-" } } }; Console.WriteLine("TestUser table should contain 8 columns"); var mappings = new Dictionary<Type, IEntityMap> { { typeof(TestUser), tableMapping } }; using (var dataTable = DataTableHelper.Create(mappings, new[] {user})) { foreach (DataColumn column in dataTable.Columns) { Console.WriteLine(column.ColumnName); } Assert.AreEqual(8, dataTable.Columns.Count); } } }
public bool BefriendEachOther(TestUser user1, TestUser user2) { if (user1 == null) { throw new ArgumentNullException("user1"); } if (user2 == null) { throw new ArgumentNullException("user2"); } using (WebClient webClient = new WebClient()) { string response1 = webClient.DownloadString(string.Format(APICalls.BeFriendUser, user1.Id, user2.Id, APICalls.Methods.Post, user1.AccessToken)); string response2 = webClient.DownloadString(string.Format(APICalls.BeFriendUser, user2.Id, user1.Id, APICalls.Methods.Post, user2.AccessToken)); bool call1 = Boolean.Parse(response1); bool call2 = Boolean.Parse(response2); return call1 && call2; } }
public async Task AddLoginForUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); // Create and save a user with a login. var user = new TestUser { UserName = "******" }; var login = new UserLoginInfo("TestProviderAdd", "ProviderKeyAdd"); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); await userStore.AddLoginAsync(user, login); transaction.Commit(); } // Check the user has an id and the login. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Logins.Count, 1); }
void Login_CorrectDetails_LoginSuccesful() { var user = new TestUser(); }
public HomePageLocator(TestUser webUser) { Web = webUser.Driver.WebDriver; }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureTestServices(services => { services .AddSingleton <IValueProvider, FakeValueProvider>() .AddSingleton <IPolicyEvaluator>(_ => new FakeUserPolicyEvaluator(() => TestUser?.ToClaims())); }); }
public void should_return_response_200_and_foward_claim_as_query_string() { var user = new TestUser() { Username = "******", Password = "******", SubjectId = "registered|1231231", Claims = new List <Claim> { new Claim("CustomerId", "123"), new Claim("LocationId", "1") } }; var configuration = new FileConfiguration { ReRoutes = new List <FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamHostAndPorts = new List <FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 57876, } }, DownstreamScheme = "http", UpstreamPathTemplate = "/", UpstreamHttpMethod = new List <string> { "Get" }, AuthenticationOptions = new FileAuthenticationOptions { AuthenticationProviderKey = "Test", AllowedScopes = new List <string> { "openid", "offline_access", "api" }, }, AddQueriesToRequest = { { "CustomerId", "Claims[CustomerId] > value" }, { "LocationId", "Claims[LocationId] > value" }, { "UserType", "Claims[sub] > value[0] > |" }, { "UserId", "Claims[sub] > value[1] > |" } } } } }; this.Given(x => x.GivenThereIsAnIdentityServerOn("http://localhost:57888", "api", AccessTokenType.Jwt, user)) .And(x => x.GivenThereIsAServiceRunningOn("http://localhost:57876", 200)) .And(x => _steps.GivenIHaveAToken("http://localhost:57888")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning(_options, "Test")) .And(x => _steps.GivenIHaveAddedATokenToMyRequest()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231")) .BDDfy(); }
public async Task QueryWebHooksAcrossAllUsers_ReturnsExpectedItemsWithPredicate(string action, bool present) { // Arrange await Initialize(); WebHook w1 = CreateWebHook(TestUser, TestId, filter: "nomatch"); await _store.InsertWebHookAsync(TestUser, w1); WebHook w2 = CreateWebHook(OtherUser, TestId + 1, filter: "nomatch"); await _store.InsertWebHookAsync(TestUser, w2); // Act ICollection <WebHook> all = await _store.QueryWebHooksAcrossAllUsersAsync(new[] { action }, (w, u) => u == TestUser.ToLowerInvariant()); ICollection <WebHook> actual = all.Where(w => w.Description == TestUser || w.Description == OtherUser).ToArray(); // Assert int expectedCount = present ? WebHookCount : 0; Assert.Equal(expectedCount, actual.Count); Assert.Equal(expectedCount, actual.Where(h => h.Description == TestUser).Count()); Assert.Equal(0, actual.Where(h => h.Description == OtherUser).Count()); }
public ActionResult GenerateUserReport(string answer, string inp, Subscriber_Table si, Post_Table ai, TestUser u) { if (answer != null) { DbAccessEntity te = new DbAccessEntity(); var testsub = (from p in te.Subscriber_Table join t in te.Test_Table on p.userid equals t.UserId where p.userid == inp select new { ID = p.userid, Domain = t.DomainID, Score = t.Score, Technology = t.TechnologyID, TesTID = t.TestId, }).ToList(); int i = 0; foreach (var p in testsub) { u.Name = p.ID; u.Domain[i] = p.Domain; u.UserId[i] = p.ID; u.Score[i] = p.Score; u.TestId[i] = p.TesTID; if (u.Score[i] <= (0.4) * 10) { u.fail = u.fail + 1; } else { u.pass = u.pass + 1; } i++; } u.counttest = i; var artsubq = (from p in te.Subscriber_Table join e in te.Post_Table on p.userid equals e.userid where p.userid == inp select new { ID = p.userid, Name = p.name, Title = e.title, Rating = e.rating, Technology = e.technology }).ToList(); i = 0; double sum = 0; foreach (var p in artsubq) { u.Title[i] = p.Title; u.Technologylist[i] = p.Technology; i++; } u.countarticle = i; if (u.countarticle > 0) { u.averagerating = (sum / u.countarticle); } else { u.averagerating = 0; } return(View(u)); } return(View()); }
public int AddUser(TestUser user) { return(0); }
public void StartBrowser() { Browser = new TestUser(); }
public async Task QueryWebHooksAcrossAllUsers_FindsWildcardsWithPredicate() { // Arrange await Initialize(); WebHook w1 = CreateWebHook(TestUser, TestId, filter: "nomatch", hasWildcard: true); await _store.InsertWebHookAsync(TestUser, w1); WebHook w2 = CreateWebHook(OtherUser, TestId + 1, filter: "nomatch", hasWildcard: true); await _store.InsertWebHookAsync(OtherUser, w2); // Act ICollection <WebHook> all = await _store.QueryWebHooksAcrossAllUsersAsync(new[] { "a1" }, (w, u) => u == TestUser.ToLowerInvariant()); ICollection <WebHook> actual = all.Where(w => w.Description == TestUser || w.Description == OtherUser).ToArray(); // Assert Assert.Equal(WebHookCount + 1, actual.Count); Assert.Equal(WebHookCount, actual.Where(h => h.Filters.Contains("a1")).Count()); Assert.Equal(1, actual.Where(h => h.Filters.Contains("*")).Count()); }
public async Task QueryWebHooksAcrossAllUsers_SkipsPausedWebHooksWithPredicate() { // Arrange await Initialize(); WebHook w1 = CreateWebHook(TestUser, TestId, isPaused: true); await _store.InsertWebHookAsync(TestUser, w1); WebHook w2 = CreateWebHook(OtherUser, TestId + 1, isPaused: true); await _store.InsertWebHookAsync(TestUser, w2); // Act ICollection <WebHook> all = await _store.QueryWebHooksAcrossAllUsersAsync(new[] { "a1" }, (w, u) => u == TestUser.ToLowerInvariant()); ICollection <WebHook> actual = all.Where(w => w.Description == TestUser || w.Description == OtherUser).ToArray(); // Assert Assert.Equal(WebHookCount, actual.Count); Assert.Equal(WebHookCount, actual.Where(h => h.Description == TestUser).Count()); Assert.Equal(0, actual.Where(h => h.Description == OtherUser).Count()); }
public async Task GetUserByLogin() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); // Create and save a user with a login. var user = new TestUser { UserName = "******" }; var login = new UserLoginInfo("TestProviderGetUser", "ProviderKeyGetUser"); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); await userStore.AddLoginAsync(user, login); transaction.Commit(); } // Check the user has an id and the login. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Logins.Count, 1); // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindAsync(new UserLoginInfo("TestProviderGetUser", "ProviderKeyGetUser")); transaction.Commit(); } // Check we have the same user and it has a single login. Assert.AreEqual(loadUser.Id, user.Id); Assert.AreEqual(loadUser.Logins.Count, 1); }
public override Task <HttpResponseMessage> PostTestUser(TestUser item) { return(base.PostTestUser(item)); }
public ActionResult Register([FromBody] TestUser testUser) { _usersManagers.AddUser(testUser); return(Ok()); }
public UserAction(UserActionTypes actionType, TestUser user) { this.ActionType = actionType; this.User = user; }
public void Setup() { testSupplier = TestSupplier.Create(); testUser = TestClient.Create().Users[0]; supplier = Supplier.Find(testSupplier.Id); }
private void GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user) { _identityServerBuilder = new WebHostBuilder() .UseUrls(url) .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseUrls(url) .ConfigureServices(services => { services.AddLogging(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(new List <ApiResource> { new ApiResource { Name = apiName, Description = "My API", Enabled = true, DisplayName = "test", Scopes = new List <Scope>() { new Scope("api"), new Scope("openid"), new Scope("offline_access") }, ApiSecrets = new List <Secret>() { new Secret { Value = "secret".Sha256() } }, UserClaims = new List <string>() { "CustomerId", "LocationId", "UserType", "UserId" } } }) .AddInMemoryClients(new List <Client> { new Client { ClientId = "client", AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, ClientSecrets = new List <Secret> { new Secret("secret".Sha256()) }, AllowedScopes = new List <string> { apiName, "openid", "offline_access" }, AccessTokenType = tokenType, Enabled = true, RequireClientSecret = false } }) .AddTestUsers(new List <TestUser> { user }); }) .Configure(app => { app.UseIdentityServer(); }) .Build(); _identityServerBuilder.Start(); _steps.VerifyIdentiryServerStarted(url); }
private void CheckRegionMaskByRecipient(string address, RecipientType recipientType, TestRegion region, TestUser user, NullConstraint constraint, string causeMessage) { var recipient = MailRecipient.Parse(address); Assert.That(recipient, Is.Not.Null); Assert.That(recipient.Type, Is.EqualTo(recipientType)); Assert.That(recipient.Status, Is.EqualTo(RecipientStatus.Verified)); var recipientUsers = recipient.GetUsers(region.Id); var findedUser = recipientUsers.FirstOrDefault(u => u.Id == user.Id); Assert.That(findedUser, constraint, causeMessage); }
private static StoredSecurityEntity CreateEntity(string name, string parentName, TestUser owner, Dictionary <int, StoredSecurityEntity> storage) { var entityId = Id(name); var parentEntityId = parentName == null ? default(int) : Id(parentName); StoredSecurityEntity parent = null; storage.TryGetValue(parentEntityId, out parent); var entity = new StoredSecurityEntity { Id = entityId, ParentId = parentEntityId, IsInherited = true, OwnerId = owner.Id, }; storage[entityId] = entity; return(entity); }
//END PROPS AND FIELDS public HomePage EnterPersonalAndEmergencyThenSubmit(TestUser user, TestUser emergencyUser) { FillOutPrimaryForm(user); FillOutEmergencyForm(emergencyUser); return(SubmitInformation()); }
//[Test] //[Category("MemberCreationTests")] //[Order(2)] //public void MemberCreationAcceptFromCart() //{ // TestAction(() => // { // string currentTestName = "MemberCreationAcceptFromCart"; // log.Debug("Starting " + currentTestName + " Test;"); // log.Debug("For user " + user.FirstName + user.LastName + ";"); // if (user.ExpResult == "Accept-FromCart") // { // MemberCreationAccept(user); // } // else // { // //Assume.That(false, "User is not from this test. Test will not run."); // return; // } // }); //} //[Test] //[Category("MemberCreationTests")] //[Order(3)] //public void MemberCreationAcceptFinishLater() //{ // TestAction(() => // { // string currentTestName = "MemberCreationAcceptFinishLater"; // log.Debug("Starting " + currentTestName + " Test;"); // log.Debug("For user " + user.FirstName + user.LastName + ";"); // if (user.ExpResult == "Accept-FinishLater") // { // MemberCreationAccept(user); // } // else // { // //Assume.That(false, "User is not from this test. Test will not run."); // return; // } // }); //} //[Test] //[Category("MemberCreationTests")] //[Order(4)] //public void MemberCreationRejectWrongZipCode() //{ // TestAction(() => // { // string currentTestName = "MemberCreationRejectWrongZipCode"; // log.Debug("Starting " + currentTestName + " Test;"); // log.Debug("For user " + user.FirstName + user.LastName + ";"); // if (user.ExpResult == "Reject-WrongZipCode") // { // MemberCreationReject(user); // } // else // { // //Assume.That(false, "User is not from this test. Test will not run."); // return; // } // }); //} //[Test] //[Category("MemberCreationTests")] //[Order(5)] //public void MemberCreationRejectUnsupportedState() //{ // TestAction(() => // { // string currentTestName = "MemberCreationRejectUnsupportedState"; // log.Debug("Starting " + currentTestName + " Test;"); // log.Debug("For user " + user.FirstName + user.LastName + ";"); // if (user.ExpResult == "Reject-UnsupportedState") // { // MemberCreationReject(user); // } // else // { // //Assume.That(false, "User is not from this test. Test will not run."); // return; // } // }); //} //[Test] //[Category("MemberCreationTests")] //[Order(6)] //public void MemberCreationRejectLowIncome() //{ // TestAction(() => // { // string currentTestName = "MemberCreationRejectLowIncome"; // log.Debug("Starting " + currentTestName + " Test;"); // log.Debug("For user " + user.FirstName + user.LastName + ";"); // if (user.ExpResult == "Reject-LowIncome") // { // MemberCreationReject(user); // } // else // { // //Assume.That(false, "User is not from this test. Test will not run."); // return; // } // }); //} private void MemberCreationAccept(TestUser user) { bool navigate = true; bool letsGetYourRentalCapMessageExpected = true; bool finishLater = false; switch (user.ExpResult) { case "Accept-FromLogIn": log.Debug("How to Invoke: from LogIn"); break; case "Accept-FromCart": log.Debug("How to Invoke: from Cart"); HomePage home = new HomePage(driverForRun); SmallSleep(); ProductHandler handler = new ProductHandler(driverForRun, home); Product product = new Product(ProductCategories.Top_deals, 1, driverForRun); SmallSleep(); handler.AddProductToContainer(ProductContainer.Cart, InterctionControlSet.Product_Details, product); wait = new WebDriverWait(driverForRun, TimeSpan.FromSeconds(10)); string btnBecomeMemberInCartXPath = "//button[text()='become a member']"; wait.Until(ExpectedConditions.ElementExists(By.XPath(btnBecomeMemberInCartXPath))); var btnBecomeMemberInCart = driverForRun.FindElement(By.XPath(btnBecomeMemberInCartXPath)); TestHelper.JSexecutorClick(btnBecomeMemberInCart, driverForRun); navigate = false; letsGetYourRentalCapMessageExpected = false; break; case "Accept-FinishLater": log.Debug("How to Invoke: from Finish Later - Become A Member"); finishLater = true; break; default: Assume.That(false, "User is not from this test. Test will not run."); break; } SignUpPage signUp = new SignUpPage(driverForRun, navigate); Assert.That(signUp.UserSignUp(user), "Sign Up failed"); if (letsGetYourRentalCapMessageExpected) { GetYourRentalCapButtonClick(); } MemberCreationFirstPage pagePersonalInfo = new MemberCreationFirstPage(driverForRun); if (finishLater) { MidSleep(); TestHelper.JSexecutorClick(pagePersonalInfo.btnFinishLater, driverForRun); Assert.IsTrue(ValidateUser(user), "User validation is Failed"); var btnBecomeMemberOnHome = driverForRun.FindElement(By.XPath("//button[text()='BECOME A MEMBER']")); TestHelper.JSexecutorClick(btnBecomeMemberOnHome, driverForRun); } pagePersonalInfo.SetPersonalInfo(user); MemberCreationSecondPage pageIncomeInfo = new MemberCreationSecondPage(driverForRun); pageIncomeInfo.SetIncomeInfo(user); MemberCreationThirdPage pageMembershipAgreement = new MemberCreationThirdPage(driverForRun); pageMembershipAgreement.SetMembershipAgreement(user); MemberCreationFourthPage pageApplicationDisclosure = new MemberCreationFourthPage(driverForRun); pageApplicationDisclosure.SetAgreement(); MemberCreationFifthPage pageCongratulations = new MemberCreationFifthPage(driverForRun); string rentExpectedValue = RentalCapExpected(user); string rentActualValue = pageCongratulations.GetRentalCapValue(); Assert.AreEqual(rentExpectedValue, rentActualValue); TestHelper.JSexecutorClick(pageCongratulations.btnStartShopping, driverForRun); Assert.IsTrue(rentExpectedValue == GetCurrentRentalCap(), "Rental Cap validation is Failed"); Assert.IsTrue(ValidateMember(user), "Member validation is Failed"); switch (user.ExpResult) { case "Accept-FromLogIn": Assert.Pass("User succesfully registered as member from login"); break; case "Accept-FromCart": Assert.Pass("User succesfully registered as member from product cart item"); break; case "Accept-FinishLater": Assert.Pass("User succesfully registered as member, by finishing registration later"); break; } }
public ActionResult Post([FromBody] TestUser newUser) { ISConfig.AddUser(newUser); return(Ok()); }
public ActionResult GenerateCategoryReport(string domlist, TestUser u, String show, string showtech, string technolist) { if (show != null) { DbAccessEntity tec = new DbAccessEntity(); var domainlist = (from p in tec.Post_Table where p.domain == domlist select new { domain = p.domain, Title = p.title, UserID = p.userid }).ToList(); Session["domainlist"] = domlist; u.domainsession = Session["domainlist"].ToString(); List <QuestionBank> li = new List <QuestionBank>(); int i = 0; foreach (var p in domainlist) { u.Domainlist[i] = p.domain; u.Title[i] = p.Title; u.UserId[i] = p.UserID; i++; } u.count = i; var techlist = (from p in tec.Technology_Table join q in tec.Domain_Table on p.did equals q.did where q.domain == domlist select new { Technology = p.technology }).ToList(); i = 0; foreach (var p in techlist) { u.Technologydroplist[i] = p.Technology; i++; } u.techcount = i; i = 0; var domainvar = (from p in tec.Domain_Table select p.domain); var count = (from p in tec.Domain_Table select p.domain).Count(); u.Domaincount = count; foreach (var p in domainvar) { u.Domaindroplist[i] = p; i++; } return(View("GenerateCategoryReport", u)); } else if (showtech != null) { DbAccessEntity tec = new DbAccessEntity(); u.techsession = technolist; var techlist = (from p in tec.Technology_Table join q in tec.Post_Table on p.technology equals q.technology where p.technology == technolist select new { technology = p.technology, UserID = q.userid, Title = q.title, }).ToList(); List <QuestionBank> li = new List <QuestionBank>(); int i = 0; foreach (var p in techlist) { u.Technologylist[i] = p.technology; u.UserId[i] = p.UserID; u.Title[i] = p.Title; i++; } u.count = i; i = 0; var domainvar = (from p in tec.Domain_Table select p.domain); var count = (from p in tec.Domain_Table select p.domain).Count(); u.Domaincount = count; foreach (var p in domainvar) { u.Domaindroplist[i] = p; i++; } u.domainsession = Session["domainlist"].ToString(); var techdropdownlist = (from p in tec.Domain_Table join q in tec.Technology_Table on p.did equals q.did where p.domain == u.domainsession select new { Technology = q.technology }).ToList(); i = 0; foreach (var p in techdropdownlist) { u.Technologydroplist[i] = p.Technology; i++; } u.techcount = i; return(View("GenerateCategoryReport", u)); } else { int i = 0; DbAccessEntity tz = new DbAccessEntity(); var domainvar = (from p in tz.Domain_Table select p.domain); var count = (from p in tz.Domain_Table select p.domain).Count(); u.Domaincount = count; foreach (var p in domainvar) { u.Domaindroplist[i] = p; i++; } ViewBag.domainlistname = u.Domainlist; return(View(u)); } }
public TestUser AddUpdateTestUser(TestUser testUser) { return(TestUserDataAccess.AddUpdateTestUser(testUser)); }
public async Task AddClaimForUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); // Create and save a user with a claim. var user = new TestUser { UserName = "******" }; var claim = new Claim(ClaimTypes.Role, "Admin_AddClaimForUserTest"); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); await userStore.AddClaimAsync(user, claim); transaction.Commit(); } // Check the user has an id and the claim. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Claims.Count, 1); }
public async Task GetClaimsForUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); // Create and save a user with some claims. var user = new TestUser { UserName = "******" }; int numberOfClaims = 5; var claimType = ClaimTypes.Role; var claimValue = "Admin_GetClaimsForUserTest"; var claim = new Claim(claimType, claimValue); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); await userStore.AddClaimAsync(user, claim); for (int i = 0; i < numberOfClaims - 1; i++) { var loopClaim = new Claim(claimType, "Admin_GetClaimsForUserTest_" + i); await userStore.AddClaimAsync(user, loopClaim); } transaction.Commit(); } // Check the user has an id and the claims. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Claims.Count, numberOfClaims); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and it has the claims. Assert.AreEqual(loadUser.Id, user.Id); Assert.AreEqual(loadUser.Claims.Count, numberOfClaims); var userClaims = await userStore.GetClaimsAsync(loadUser); var userClaim = userClaims.SingleOrDefault(c => c.Type == claimType && c.Value == claimValue); Assert.IsNotNull(userClaim); }
public ApiFixture() { FirstUser = new TestUser("123", "*****@*****.**"); }
public async Task RemoveRoleFromUserOnlyRemovesSingleRole() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role and a user and add the role to the user. int numberOfOtherRoles = 3; string roleName = "RemoveRoleFromUserOnlyRemovesSingleRole"; var role = new TestRole(roleName); var user = new TestUser("RemoveRoleFromUserOnlyRemovesSingleRole"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); await userStore.AddToRoleAsync(user, role.Name); for (int i = 0; i < numberOfOtherRoles; i++) { var otherRole = new TestRole(roleName + i); await roleStore.CreateAsync(otherRole); await userStore.AddToRoleAsync(user, otherRole.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNotNull(userRole); // Now remove the role. using (var transaction = session.BeginTransaction()) { await userStore.RemoveFromRoleAsync(loadUser, roleName); transaction.Commit(); } // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user again. using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and the role has been removed. Assert.AreEqual(loadUser.Id, user.Id); userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNull(userRole); }
public async Task GetLoginsForUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); // Create and save a user with a login. var user = new TestUser { UserName = "******" }; int numberOfLogins = 5; using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); for (int i = 0; i < numberOfLogins; i++) { var login = new UserLoginInfo("TestProviderList" + i, "ProviderKeyRemove" + i); await userStore.AddLoginAsync(user, login); } transaction.Commit(); } // Check the user has an id and all the logins have been saved. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Logins.Count, numberOfLogins); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; IList<UserLoginInfo> logins; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); logins = await userStore.GetLoginsAsync(user); transaction.Commit(); } // Check we have the same user and that they have all of the logins. Assert.AreEqual(loadUser.Id, user.Id); Assert.AreEqual(loadUser.Logins.Count, numberOfLogins); Assert.AreEqual(logins.Count, numberOfLogins); }
public async Task IsInRoleReturnsTrueWhenAUserIsInARoleAndFalseWhenTheyAreNot() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role and a user and add the role to the user. int numberOfOtherRoles = 3; string roleName = "IsInRoleTestRole"; var role = new TestRole(roleName); var user = new TestUser("IsInRoleTestUser"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); await userStore.AddToRoleAsync(user, role.Name); for (int i = 0; i < numberOfOtherRoles; i++) { var otherRole = new TestRole(roleName + i); await roleStore.CreateAsync(otherRole); await userStore.AddToRoleAsync(user, otherRole.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and that we get true when testing for the correct role and false for non-existent role. Assert.AreEqual(loadUser.Id, user.Id); bool inRole = await userStore.IsInRoleAsync(loadUser, roleName); bool notInRole = await userStore.IsInRoleAsync(loadUser, "NOTINROLETEST_USERNOTINROLE"); Assert.IsTrue(inRole); Assert.IsFalse(notInRole); }
protected void btnEnter_Click(object sender, EventArgs e) { string _username; string _password; // String Task; _username = tbusername.Text; _password = tbpassword.Text; SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString()); con.Open(); String query = "select count(*) from tbuser where user_name= '" + tbusername.Text + "' and password ='******' "; SqlCommand cmd = new SqlCommand(query, con); String output = cmd.ExecuteScalar().ToString(); string pid = ""; string name = ""; string surname = ""; SqlCommand cmd5 = new SqlCommand("SELECT T.*, P.Name, P.Surname FROM tbuser T INNER JOIN person P ON P.ID=T.person_ID WHERE T.user_name = '" + _username + "' and T.password='******'", con); SqlDataReader r; r = cmd5.ExecuteReader(); while (r.Read()) { pid = r["person_ID"].ToString(); name = r["Name"].ToString(); surname = r["Surname"].ToString(); } r.Close(); if (pid == "") { MessageBox.Show("User name or Password is wrong"); return; } Int64 _person_id = Convert.ToInt64(pid); string _task = ""; SqlCommand cmd6 = new SqlCommand("SELECT * FROM staff WHERE Person_ID = '" + _person_id + "'", con); SqlDataReader reader; reader = cmd6.ExecuteReader(); while (reader.Read()) { _task = reader["Task"].ToString(); } reader.Close(); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(cmd6); da.Fill(dt); if (dt.Rows.Count != 0) { if (output == "1") { TestUser _user = new TestUser(); _user.Username = tbusername.Text; _user.Password = tbpassword.Text; _user.Person_ID = Convert.ToInt32(_person_id); _user.Person = new Person(); _user.Person.ID = _user.Person_ID; _user.Person.Name = name; _user.Person.Surname = surname; Session["_user"] = _user; Session["tbuser"] = tbusername.Text; Session["tbpassword"] = tbpassword.Text; Session["tbpid"] = _person_id; _task = dt.Rows[0][2].ToString().Trim(); if (_task == "admin") { Session["tbuser"] = tbusername.Text; Session["task"] = "admin"; Response.Redirect("Admin.aspx"); } else if (_task == "normal") { Session["task"] = "normal"; Response.Redirect("Default.aspx"); } else { Response.Redirect("Contact.aspx"); } } else { Response.Write("log filed"); } } }
private void MemberCreationReject(TestUser user) { bool validationError = false; string errorText = ""; bool btnBecomeMemberExpected = false; bool popupErrorMessage = false; bool gotoSecondPage = false; switch (user.ExpResult) { case "Reject-WrongZipCode": log.Debug("Fail reason: Wrong ZipCode"); validationError = true; errorText = "Zip code and State do not match!"; break; case "Reject-UnsupportedState": log.Debug("Fail reason: Unsupported State"); btnBecomeMemberExpected = true; popupErrorMessage = true; errorText = "We are not yet available in your state."; break; case "Reject-LowIncome": log.Debug("Fail reason: Low Income"); popupErrorMessage = true; gotoSecondPage = true; errorText = "We are sorry..."; break; default: Assume.That(false, "User is not from this test. Test will not run."); break; } SignUpPage signUp = new SignUpPage(driverForRun); Assert.That(signUp.UserSignUp(user), "Sign Up failed"); GetYourRentalCapButtonClick(); MemberCreationFirstPage pagePersonalInfo = new MemberCreationFirstPage(driverForRun); pagePersonalInfo.SetPersonalInfo(user); string errorTextXPath; IWebElement txtErrorText; if (validationError) { errorTextXPath = "//li[text()='" + " " + errorText + " " + "']"; txtErrorText = driverForRun.FindElement(By.XPath(errorTextXPath)); SmallSleep(); Assert.That(txtErrorText.Displayed, "Error Message '" + errorText + "' is not displayed"); TestHelper.JSexecutorClick(pagePersonalInfo.btnFinishLater, driverForRun); Assert.That(ValidateUser(user), "User validation is Failed"); Assert.Pass("User rejected because of wrong zip code"); } if (gotoSecondPage) { MemberCreationSecondPage pageIncomeInfo = new MemberCreationSecondPage(driverForRun); pageIncomeInfo.SetIncomeInfo(user); } if (popupErrorMessage) { wait = new WebDriverWait(driverForRun, TimeSpan.FromSeconds(10)); errorTextXPath = "//h3[text()='" + errorText + "']"; wait.Until(ExpectedConditions.ElementExists(By.XPath(errorTextXPath))); txtErrorText = driverForRun.FindElement(By.XPath(errorTextXPath)); SmallSleep(); Assert.That(txtErrorText.Displayed, "Error Message '" + errorText + "' is not displayed"); var element = driverForRun.FindElement(By.XPath("//span[text()='Close']/parent::button")); TestHelper.JSexecutorClick(element, driverForRun); Assert.That(ValidateMember(user), "Member validation is Failed"); bool btnBecomeMemberExists = true; try { driverForRun.FindElement(By.XPath("//button[text()='BECOME A MEMBER']")); } catch { btnBecomeMemberExists = false; } Assert.AreEqual(btnBecomeMemberExpected, btnBecomeMemberExists); switch (user.ExpResult) { case "Reject-UnsupportedState": Assert.Pass("User rejected due unsuported state"); break; case "Reject-LowIncome": Assert.Pass("User rejected due low income"); break; } } }
public async Task RemoveClaimForUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); // Create and save a user with a claim. var user = new TestUser { UserName = "******" }; var claimType = ClaimTypes.Role; var claimValue = "Admin_RemoveClaimForUserTest"; var claim = new Claim(claimType, claimValue); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); await userStore.AddClaimAsync(user, claim); transaction.Commit(); } // Check the user has an id and the claim. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Claims.Count, 1); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user and remove the claim. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); await userStore.RemoveClaimAsync(loadUser, claim); transaction.Commit(); } // Check we have the same user and it now has no claims. Assert.AreEqual(loadUser.Id, user.Id); Assert.AreEqual(loadUser.Claims.Count, 0); }
private void OnChangeSpinValueByObj(TestUser testUser1) { }
public async Task AddRoleToUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a role and a user. string roleName = "AddRoleToUserTestRole"; var role = new TestRole(roleName); var user = new TestUser("AddRoleToUserTestUser"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); transaction.Commit(); } // Check the user has an Id and no roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, 0); var userId = user.Id; // Add the user to the role. using (var transaction = session.BeginTransaction()) { await userStore.AddToRoleAsync(user, role.Name); transaction.Commit(); } // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNotNull(userRole); }
public async Task OnValidatePrincipalTestSuccess(bool isPersistent) { var user = new TestUser { UserName = "******" }; var manager = SetupUserManager(user); manager.Setup(m => m.SupportsUserLockout).Returns(true).Verifiable(); manager.Setup(m => m.IsLockedOutAsync(user)).ReturnsAsync(true).Verifiable(); var context = new Mock <HttpContext>(); var contextAccessor = new Mock <IHttpContextAccessor>(); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); var roleManager = MockHelpers.MockRoleManager <TestRole>(); var options = new Mock <IOptions <IdentityOptions> >(); options.Setup(a => a.Value).Returns(new IdentityOptions()); var securityStampOptions = new Mock <IOptions <SecurityStampValidatorOptions> >(); securityStampOptions.Setup(a => a.Value).Returns(new SecurityStampValidatorOptions { ValidationInterval = TimeSpan.Zero }); var claimsFactory = new UserClaimsPrincipalFactory <TestUser, TestRole>(manager.Object, roleManager.Object, options.Object); var loggerFactory = new MockLoggerFactory(); var logger = loggerFactory.CreateLogger <SignInManager <TestUser> >(); var helper = new Mock <SignInManager <TestUser> >(manager.Object, contextAccessor.Object, claimsFactory, options.Object, logger, new Mock <IAuthenticationSchemeProvider>().Object, new Mock <IUserConfirmation <TestUser> >().Object); var properties = new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow.AddSeconds(-1), IsPersistent = isPersistent }; var id = new ClaimsIdentity(IdentityConstants.ApplicationScheme); id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); var principal = new ClaimsPrincipal(id); helper.Setup(s => s.ValidateSecurityStampAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(user).Verifiable(); helper.Setup(s => s.CreateUserPrincipalAsync(user)).ReturnsAsync(principal).Verifiable(); var logFactory = new MockLoggerFactory(); var services = new ServiceCollection(); services.AddSingleton <ILoggerFactory>(loggerFactory); services.AddSingleton(options.Object); services.AddSingleton(helper.Object); services.AddSingleton <ISecurityStampValidator>(new SecurityStampValidator <TestUser>(securityStampOptions.Object, helper.Object, new SystemClock())); context.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider()); contextAccessor.Setup(a => a.HttpContext).Returns(context.Object); var ticket = new AuthenticationTicket(principal, properties, IdentityConstants.ApplicationScheme); var cookieContext = new CookieValidatePrincipalContext(context.Object, new AuthenticationSchemeBuilder(IdentityConstants.ApplicationScheme) { HandlerType = typeof(NoopHandler) }.Build(), new CookieAuthenticationOptions(), ticket); Assert.NotNull(cookieContext.Properties); Assert.NotNull(cookieContext.Options); Assert.NotNull(cookieContext.Principal); await SecurityStampValidator.ValidatePrincipalAsync(cookieContext); Assert.NotNull(cookieContext.Principal); helper.VerifyAll(); }
public async Task GetRolesForAUser() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore<TestUser>(session); var roleStore = new TestRoleStore<TestRole>(session); // Create and save a user and some roles and add the roles to the user. int numberOfRoles = 5; string roleName = "GetRolesForAUserTestRole"; var user = new TestUser("GetRolesForAUser"); using (var transaction = session.BeginTransaction()) { await userStore.CreateAsync(user); for (int i = 0; i < numberOfRoles; i++) { var role = new TestRole(roleName + i); await roleStore.CreateAsync(role); await userStore.AddToRoleAsync(user, role.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfRoles); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore<TestUser>(session); // Load the user. TestUser loadUser; IList<string> roles; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); roles = await userStore.GetRolesAsync(user); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); Assert.AreEqual(roles.Count, numberOfRoles); }
public async Task RemoveRoleFromUserOnlyRemovesSingleRole() { // Create a session and user store for this test. var session = SessionFactory.OpenSession(); var userStore = new TestUserStore(session); var roleStore = new TestRoleStore(session); // Create and save a role and a user and add the role to the user. int numberOfOtherRoles = 3; string roleName = "RemoveRoleFromUserOnlyRemovesSingleRole"; var role = new TestRole(roleName); var user = new TestUser("RemoveRoleFromUserOnlyRemovesSingleRole"); using (var transaction = session.BeginTransaction()) { await roleStore.CreateAsync(role); await userStore.CreateAsync(user); await userStore.AddToRoleAsync(user, role.Name); for (int i = 0; i < numberOfOtherRoles; i++) { var otherRole = new TestRole(roleName + i); await roleStore.CreateAsync(otherRole); await userStore.AddToRoleAsync(user, otherRole.Name); } transaction.Commit(); } // Check the user has an Id and the roles. Assert.IsNotNull(user.Id); Assert.AreEqual(user.Roles.Count, numberOfOtherRoles + 1); var userId = user.Id; // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore(session); // Load the user. TestUser loadUser; using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and it has the role. Assert.AreEqual(loadUser.Id, user.Id); var userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNotNull(userRole); // Now remove the role. using (var transaction = session.BeginTransaction()) { await userStore.RemoveFromRoleAsync(loadUser, roleName); transaction.Commit(); } // Create a new session and user store for this test, so that we actually hit the database and not the cache. userStore.Dispose(); session.Dispose(); session = SessionFactory.OpenSession(); userStore = new TestUserStore(session); // Load the user again. using (var transaction = session.BeginTransaction()) { loadUser = await userStore.FindByIdAsync(userId); transaction.Commit(); } // Check we have the same user and the role has been removed. Assert.AreEqual(loadUser.Id, user.Id); userRole = loadUser.Roles.SingleOrDefault(r => r.Name == roleName); Assert.IsNull(userRole); }
public async Task <IActionResult> Login(LoginInputModel model, string button) { // check if we are in the context of an authorization request var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl); // the user clicked the "cancel" button if (button != "login") { if (context != null) { // if the user cancels, send a result back into IdentityServer as if they // denied the consent (even if this client does not require consent). // this will send back an access denied OIDC error response to the client. await _interaction.GrantConsentAsync(context, ConsentResponse.Denied); // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl })); } return(Redirect(model.ReturnUrl)); } else { // since we don't have a valid context, then we just go back to the home page return(Redirect("~/")); } } if (ModelState.IsValid) { // validate username/password against in-memory store //if (_users.ValidateCredentials(model.Username, model.Password)) if (true) { //var user = _users.FindByUsername(model.Username); var user = new TestUser { SubjectId = model.Username, Username = model.Username }; await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username)); // only set explicit expiration here if user chooses "remember me". // otherwise we rely upon expiration configured in cookie middleware. AuthenticationProperties props = null; if (AccountOptions.AllowRememberLogin && model.RememberLogin) { props = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) }; } ; // issue authentication cookie with subject ID and username await HttpContext.SignInAsync(user.SubjectId, user.Username, props, new Claim(JwtClaimTypes.Role, "admin")); if (context != null) { if (await _clientStore.IsPkceClientAsync(context.ClientId)) { // if the client is PKCE then we assume it's native, so this change in how to // return the response is for better UX for the end user. return(View("Redirect", new RedirectViewModel { RedirectUrl = model.ReturnUrl })); } // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null return(Redirect(model.ReturnUrl)); } // request for a local page if (Url.IsLocalUrl(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } else if (string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect("~/")); } else { // user might have clicked on a malicious link - should be logged throw new Exception("invalid return URL"); } } await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials")); ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage); } // something went wrong, show form with error var vm = await BuildLoginViewModelAsync(model); return(View(vm)); }
public ActionResult DomainSelect(string domlist, TestUser u, String show, string showtech, string technolist) { if (show != null) { DbAccessEntity tec = new DbAccessEntity(); var domainlist = (from p in tec.Domain_Table join q in tec.Test_Table on p.did equals q.DomainID where p.domain == domlist select new { domain = p.domain, UserID = q.UserId, TestID = q.TestId, Score = q.Score }).ToList(); Session["domainlist"] = domlist; u.domainsession = Session["domainlist"].ToString(); List <QuestionBank> li = new List <QuestionBank>(); int i = 0; foreach (var p in domainlist) { u.Domainlist[i] = p.domain; u.UserId[i] = p.UserID; u.TestId[i] = p.TestID; u.Score[i] = p.Score; i++; } u.count = i; var techlist = (from p in tec.Domain_Table join q in tec.Technology_Table on p.did equals q.did where p.domain == domlist select new { Technology = q.technology }).ToList(); i = 0; foreach (var p in techlist) { u.Technologydroplist[i] = p.Technology; i++; } u.techcount = i; i = 0; var domainvar = (from p in tec.Domain_Table select p.domain); var count = (from p in tec.Domain_Table select p.domain).Count(); u.Domaincount = count; foreach (var p in domainvar) { u.Domaindroplist[i] = p; i++; } return(View("GenerateTestReport", u)); } else if (showtech != null) { DbAccessEntity tec = new DbAccessEntity(); u.techsession = technolist; var techlist = (from p in tec.Technology_Table join q in tec.Test_Table on p.tid equals q.TechnologyID where p.technology == technolist select new { technology = p.technology, UserID = q.UserId, TestID = q.TestId, Score = q.Score }).ToList(); List <QuestionBank> li = new List <QuestionBank>(); int i = 0; foreach (var p in techlist) { u.Technologylist[i] = p.technology; u.UserId[i] = p.UserID; u.TestId[i] = p.TestID; u.Score[i] = p.Score; i++; } u.count = i; i = 0; var domainvar = (from p in tec.Domain_Table select p.domain); var count = (from p in tec.Domain_Table select p.domain).Count(); u.Domaincount = count; foreach (var p in domainvar) { u.Domaindroplist[i] = p; i++; } u.domainsession = Session["domainlist"].ToString(); var techdropdownlist = (from p in tec.Domain_Table join q in tec.Technology_Table on p.did equals q.did where p.domain == u.domainsession select new { Technology = q.technology }).ToList(); i = 0; foreach (var p in techdropdownlist) { u.Technologydroplist[i] = p.Technology; i++; } u.techcount = i; return(View("GenerateTestReport", u)); } return(View("GenerateTestReport")); }