Esempio n. 1
0
 public static void AddClaim(
     this IdentityUser user,
     string claimType,
     string claimValue
     )
 {
     user.AddClaim(claimType, claimValue);
 }
        public static IdentityUser UserWithClaimAndRole(Claim claim, string role = "test")
        {
            var user = new IdentityUser();
            user.AddRole(role);
            user.AddClaim(claim);

            return user;
        }
Esempio n. 3
0
        public static IdentityUser UserWithClaimAndRole(Claim claim, string role = "test")
        {
            var user = new IdentityUser();

            user.AddRole(role);
            user.AddClaim(claim);

            return(user);
        }
        public void ReplaceClaim_TypeMatchesButValueDoesNot_DoesNotReplace()
        {
            var user       = new IdentityUser();
            var firstClaim = new Claim("sameType", "value");

            user.AddClaim(firstClaim);
            var newClaim = new Claim("sameType", "newValue");

            user.ReplaceClaim(new Claim("sameType", "wrongValue"), newClaim);

            user.ExpectOnlyHasThisClaim(firstClaim);
        }
        public void ReplaceClaim_ExistingClaim_Replaces()
        {
            var user       = new IdentityUser();
            var firstClaim = new Claim("type", "value");

            user.AddClaim(firstClaim);
            var newClaim = new Claim("newType", "newValue");

            user.ReplaceClaim(firstClaim, newClaim);

            user.ExpectOnlyHasThisClaim(newClaim);
        }
Esempio n. 6
0
        public void UserWithTwoClaims_RemoveOneOfTheClaims_OtherClaimRemains()
        {
            var user = new IdentityUser();

            string claimType1  = "test-claim-1";
            string claimValue1 = "test-value-1";
            var    claim1      = new Claim(claimType1, claimValue1);

            string claimType2  = "test-claim-2";
            string claimValue2 = "test-value-2";
            var    claim2      = new Claim(claimType2, claimValue2);

            user.AddClaim(claim1);
            user.AddClaim(claim2);

            user.RemoveClaim(new Claim(claimType1, claimValue1));

            Assert.Equal(1, user.Claims.Count);
            Assert.Equal(claimType2, user.Claims[0].ClaimType);
            Assert.Equal(claimValue2, user.Claims[0].ClaimValue);
        }
Esempio n. 7
0
        public async Task <IActionResult> Register([FromBody] AccountRegisterModel accountRegisterModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (string.IsNullOrEmpty(accountRegisterModel.Username))
            {
                accountRegisterModel.Username = accountRegisterModel.Email;
            }

            var user = new IdentityUser(accountRegisterModel.Username, accountRegisterModel.Email);

            if (accountRegisterModel.Claims != null)
            {
                foreach (string claim in accountRegisterModel.Claims)
                {
                    user.AddClaim(new UserClaim(JwtClaimTypes.Role, claim));
                }
            }

            var result = await _userManager.CreateAsync(user, accountRegisterModel.Password);

            if (result == null)
            {
                return(StatusCode(500, "Internal Server Error"));
            }

            if (result.Succeeded)
            {
                if (!string.IsNullOrEmpty(accountRegisterModel.Cell))
                {
                    await _userManager.SetPhoneNumberAsync(user, accountRegisterModel.Cell);
                }

                return(Ok(new
                {
                    user.Id,
                    user.CreatedOn
                }));
            }

            AddErrorsToModelState(result);

            if (ModelState.IsValid)
            {
                return(BadRequest());
            }

            return(BadRequest(ModelState));
        }
Esempio n. 8
0
        public void UserWithoutClaims_AddClaim_OneClaimAdded()
        {
            var user = new IdentityUser();

            string claimType  = "test-claim";
            string claimValue = "test-value";

            var claim = new Claim(claimType, claimValue);

            user.AddClaim(claim);

            Assert.Equal(1, user.Claims.Count);
            Assert.Equal(claimType, user.Claims[0].ClaimType);
            Assert.Equal(claimValue, user.Claims[0].ClaimValue);
        }
Esempio n. 9
0
        public void UserWithOneClaim_RemoveTheClaim_NoClaimsRemain()
        {
            var user = new IdentityUser();

            string claimType  = "test-claim";
            string claimValue = "test-value";

            var claim1 = new Claim(claimType, claimValue);
            var claim2 = new Claim(claimType, claimValue);

            user.AddClaim(claim1);
            user.RemoveClaim(claim2);

            Assert.Empty(user.Claims);
        }
Esempio n. 10
0
        private static IdentityUser CreateUser(ExternalLoginInfo externalLogin)
        {
            var mail = externalLogin.Principal.FindFirst(ClaimTypes.Email).Value;

            var user = new IdentityUser {
                Email = mail, UserName = mail
            };

            foreach (var squidexClaim in externalLogin.Principal.Claims.Where(c => c.Type.StartsWith(SquidexClaimTypes.Prefix)))
            {
                user.AddClaim(squidexClaim);
            }

            return(user);
        }
Esempio n. 11
0
        public void UserWithOneClaim_RemoveNonExistingClaim_DoesNothing()
        {
            var user = new IdentityUser();

            string claimType  = "test-claim";
            string claimValue = "test-value";

            var claim = new Claim(claimType, claimValue);

            user.AddClaim(claim);

            user.RemoveClaim(new Claim("non-existing-type", "non-existing-value"));

            Assert.Equal(1, user.Claims.Count);
            Assert.Equal(claimType, user.Claims[0].ClaimType);
            Assert.Equal(claimValue, user.Claims[0].ClaimValue);
        }
Esempio n. 12
0
        public async Task AddClaimAsync(IdentityUser user, Models.UserClaim claim)
        {
            using (var db = new SqlDbContext(_options))
            {
                try
                {
                    var dbUser = db.IdentityUser.FirstOrDefault(tbl => tbl.Id == user.Id);

                    if (dbUser == null)
                    {
                        user.AddClaim(claim);
                        db.Update(user);
                    }
                    await db.SaveChangesAsync();
                }
                catch (Exception exc)
                {
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Populate MongoDB with a List of Dummy users to enable tests - e.g. Alice, Bob
        ///   see Config.GetSampleUsers() for details.
        /// </summary>
        /// <param name="userManager"></param>
        private static void  AddSampleUsersToMongo(UserManager <IdentityUser> userManager)
        {
            var dummyUsers = Config.GetSampleUsers();

            foreach (var usrDummy in dummyUsers)
            {
                var userDummyEmail = usrDummy.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Email);

                if (userDummyEmail == null)
                {
                    throw new Exception("Could not locate user email from  claims!");
                }


                var user = new IdentityUser()
                {
                    UserName        = usrDummy.Username,
                    LockoutEnabled  = false,
                    EmailConfirmed  = true,
                    Email           = userDummyEmail.Value,
                    NormalizedEmail = userDummyEmail.Value
                };



                foreach (var claim in usrDummy.Claims)
                {
                    user.AddClaim(claim);
                }
                var result = userManager.CreateAsync(user, usrDummy.Password);
                if (!result.Result.Succeeded)
                {
                    // If we got an error, Make sure to drop all collections from Mongo before trying again. Otherwise sample users will NOT be populated
                    var errorList = result.Result.Errors.ToArray();
                    throw new Exception($"Error Adding sample users to MongoDB! Make sure to drop all collections from Mongo before trying again!");
                }
            }
            return;
        }
 public UserStoreTests(MongoHelper mongoHelper)
 {
     testUser = new IdentityUser
     {
         Id              = Guid.NewGuid().ToString(),
         Name            = "name",
         NormalizedName  = "normalizedName",
         PasswordHash    = "hashypash",
         Email           = "*****@*****.**",
         NormalizedEmail = "*****@*****.**",
         EmailConfirmed  = true,
         SecurityStamp   = "stampy",
         LockoutEndDate  = new DateTimeOffset(DateTime.Now),
         PhoneNumber     = "222222222222"
     };
     testUser.AddLogin(new PersistedUserLoginInfo("gwar", "123"));
     testUser.AddClaim(new PersistedClaim("test", "data"));
     testUser.SetToken(new AuthToken("goog.goo", "garbage", "data"));
     testUser.AddToRole("blarg");
     db = mongoHelper.Database;
     usersCollection = mongoHelper.Users;
     userStore       = new MongoUserStore <IdentityUser>(usersCollection);
 }
Esempio n. 15
0
    private async Task AddUsers()
    {
        var adminUser = new IdentityUser(_guidGenerator.Create(), "administrator", "*****@*****.**");

        adminUser.AddRole(_adminRole.Id);
        adminUser.AddClaim(_guidGenerator, new Claim("TestClaimType", "42"));
        await _userRepository.InsertAsync(adminUser);

        var john = new IdentityUser(_testData.UserJohnId, "john.nash", "*****@*****.**");

        john.AddRole(_moderatorRole.Id);
        john.AddRole(_supporterRole.Id);
        john.AddOrganizationUnit(_ou111.Id);
        john.AddOrganizationUnit(_ou112.Id);
        john.AddLogin(new UserLoginInfo("github", "john", "John Nash"));
        john.AddLogin(new UserLoginInfo("twitter", "johnx", "John Nash"));
        john.AddClaim(_guidGenerator, new Claim("TestClaimType", "42"));
        john.SetToken("test-provider", "test-name", "test-value");
        await _userRepository.InsertAsync(john);

        var david = new IdentityUser(_testData.UserDavidId, "david", "*****@*****.**");

        david.AddOrganizationUnit(_ou112.Id);
        await _userRepository.InsertAsync(david);

        var neo = new IdentityUser(_testData.UserNeoId, "neo", "*****@*****.**");

        neo.AddRole(_supporterRole.Id);
        neo.AddClaim(_guidGenerator, new Claim("TestClaimType", "43"));
        neo.AddOrganizationUnit(_ou111.Id);
        await _userRepository.InsertAsync(neo);

        var bob = new IdentityUser(_testData.UserBobId, "bob", "*****@*****.**");

        bob.SetIsActive(false);
        await _userManager.CreateAsync(bob, "1q2w3E*");
    }