Example #1
0
      public async Task<ActionResult> Create([Bind(Include = "ID,Name,Visibility")] Game game)
      {
         if (ModelState.IsValid)
         {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

            var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

            db.Games.Add(game);

            await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
            await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
            await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));

            var membership = new GameMembership()
            {
               Game = game,
               ApplicationUser = appUser,
               Roles = "Owner",
            };
            db.GameMemberships.Add(membership);
            await db.SaveChangesAsync();

            return RedirectToAction("Index");
         }

         return View(game);
      }
Example #2
0
 public async Task GetUserClaimTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("u1");
     var result = await manager.CreateAsync(user);
     UnitTestHelper.IsSuccess(result);
     Assert.NotNull(user);
     var claims = new[]
     {
         new Claim("c1", "v1"),
         new Claim("c2", "v2"),
         new Claim("c3", "v3")
     };
     foreach (Claim c in claims)
     {
         UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
     }
     var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
     Assert.Equal(3, userClaims.Count);
     foreach (Claim c in claims)
     {
         Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
     }
 }
        public async Task ClaimsIdentityTest()
        {
            var db = UnitTestHelper.CreateDefaultDb();
            var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
            var role = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
            var user = new IdentityUser("Hao");
            UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Admin")));
            UnitTestHelper.IsSuccess(await role.CreateAsync(new IdentityRole("Local")));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Admin"));
            UnitTestHelper.IsSuccess(await manager.AddToRoleAsync(user.Id, "Local"));
            Claim[] userClaims =
            {
                new Claim("Whatever", "Value"),
                new Claim("Whatever2", "Value2")
            };
            foreach (var c in userClaims)
            {
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
            }

            var identity = await manager.CreateIdentityAsync(user, "test");
            var claimsFactory = manager.ClaimsIdentityFactory as ClaimsIdentityFactory<IdentityUser, string>;
            Assert.NotNull(claimsFactory);
            var claims = identity.Claims;
            Assert.NotNull(claims);
            Assert.True(
                claims.Any(c => c.Type == claimsFactory.UserNameClaimType && c.Value == user.UserName));
            Assert.True(claims.Any(c => c.Type == claimsFactory.UserIdClaimType && c.Value == user.Id));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Admin"));
            Assert.True(claims.Any(c => c.Type == claimsFactory.RoleClaimType && c.Value == "Local"));
            Assert.True(
                claims.Any(
                    c =>
                        c.Type == ClaimsIdentityFactory<IdentityUser>.IdentityProviderClaimType &&
                        c.Value == ClaimsIdentityFactory<IdentityUser>.DefaultIdentityProviderClaimValue));
            foreach (var cl in userClaims)
            {
                Assert.True(claims.Any(c => c.Type == cl.Type && c.Value == cl.Value));
            }
        }
Example #4
0
        public async Task DupeUserClaimTest()
        {
            var db = UnitTestHelper.CreateDefaultDb();
            var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
            var user = new IdentityUser("u1");
            var result = await manager.CreateAsync(user);
            Assert.NotNull(user);
            var claims = new[]
            {
                new Claim("c1", "v1"),
                new Claim("c2", "v2"),
                new Claim("c3", "v3")
            };
            foreach (Claim c in claims)
            {
                // Add dupes
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
                UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
            }

            var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
            Assert.Equal(6, userClaims.Count);
            var currentExpected = 6;
            foreach (Claim c in claims)
            {
                Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
                UnitTestHelper.IsSuccess(await manager.RemoveClaimAsync(user.Id, c));
                var cs = await manager.GetClaimsAsync(user.Id);
                currentExpected -= 2;
                Assert.Equal(currentExpected, cs.Count());
                Assert.Equal(currentExpected, db.Set<IdentityUserClaim>().Count());
            }
        }
      public async Task<int> SyncMembershipsAndClaims([FromBody]Fixit fixit)
      {
         var userName = fixit.UserName;

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var query = db.GameMemberships.Include(mem => mem.Game).Include(mem => mem.ApplicationUser);

         if (!string.IsNullOrEmpty(userName) && !userName.Equals("$all", StringComparison.InvariantCultureIgnoreCase))
         {
            query = query.Where(mem => mem.ApplicationUser.DisplayName == userName);
         }

         var memberships = await query.ToListAsync();
         int membershipsFixed = 0;
         foreach (var membershipGroup in memberships.GroupBy(m => m.ApplicationUser))
         {
            var user = membershipGroup.Key;
            var claims = await manager.GetClaimsAsync(user.Id);

            foreach (var membership in membershipGroup)
            {
               bool wasFixed = false;
               if (!claims.Where(c => c.Type == "GameMembership").Any(c => c.Value == membership.GameID.ToString()))
               {
                  var result = await manager.AddClaimAsync(user.Id, new Claim("GameMembership", membership.GameID.ToString()));
                  if (!result.Succeeded)
                  {
                     Trace.WriteLine(string.Format("Error creating GameMembership claim for user {0} for game {1}: errors {2}", user.Id, membership.GameID, 
                        string.Join(", ", result.Errors)));
                  }
                  else
                  {
                     wasFixed = true;
                  }
               }
               if (membership.Roles.Contains("Owner"))
               {
                  if (!claims.Where(c => c.Type == "GameOwnership").Any(c => c.Value == membership.GameID.ToString()))
                  {
                     var result = await manager.AddClaimAsync(user.Id, new Claim("GameOwnership", membership.GameID.ToString()));
                     if (!result.Succeeded)
                     {
                        Trace.WriteLine(string.Format("Error creating GameOwnership claim for user {0} for game {1}: errors {2}", user.Id, membership.GameID,
                           string.Join(", ", result.Errors)));
                     }
                     else
                     {
                        wasFixed = true;
                     }
                  }
               }
               if (membership.Roles.Contains("Gamemaster"))
               {
                  if (!claims.Where(c => c.Type == "GameMaster").Any(c => c.Value == membership.GameID.ToString()))
                  {
                     var result = await manager.AddClaimAsync(user.Id, new Claim("GameMaster", membership.GameID.ToString()));
                     if (!result.Succeeded)
                     {
                        Trace.WriteLine(string.Format("Error creating GameMaster claim for user {0} for game {1}: errors {2}", user.Id, membership.GameID,
                           string.Join(", ", result.Errors)));
                     }
                     else
                     {
                        wasFixed = true;
                     }
                  }
               }

               if (wasFixed)
               {
                  membershipsFixed++;
               }
            }
         }

         return membershipsFixed;
      }
      public async Task<GameResult> Create([FromBody]GameResult result)
      {
         if (result == null)
         {
            throw new ArgumentNullException("game");
         }

         GameVisibility visibility;
         if (!Enum.TryParse(result.Visibility, out visibility))
         {
            throw new ArgumentException("game.Visibility is not valid");
         }

         var game = new Game()
         {
            Name = result.Name,
            Visibility = visibility,
         };

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

         db.Games.Add(game);

         await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
         await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
         await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));

         var membership = new GameMembership()
         {
            Game = game,
            ApplicationUser = appUser,
            Roles = "Owner",
         };
         db.GameMemberships.Add(membership);
         await db.SaveChangesAsync();


         result.GameId = game.ID;

         return result;
      }
Example #7
0
		public static async void ConfigureUsers(IEnumerable<InMemoryUser> users, EntityFrameworkServiceOptions options, UserManager userManager) {
			using(var db = new Contexto(options.ConnectionString)) {
				
				if(!db.Users.Any()) {
					
					foreach(var u in users) {
						var entity = new Usuario { Email = u.Claims.First(x=>x.Type==Constants.ClaimTypes.Email).Value , UserName = u.Username };
						var response = await userManager.CreateAsync(entity, u.Password);
						
						if(!response.Succeeded) {
							throw new Exception("Não foi possível criar o usuario" + u.Username + response.Errors.ToString());
						}
						else {
							
							var user = await userManager.FindAsync(u.Username,u.Password);
							foreach(var c in u.Claims) {

								await userManager.AddClaimAsync(user.Id,c);
							}
														
							await userManager.UpdateAsync(user);
						}
					}
					db.SaveChanges();
				}
			}
		}