Example #1
0
        /// <summary>
        /// Seeding database with admin user and password admin. Also add role 'Admin'
        /// </summary>
        /// <param name="userService">Service to include user</param>
        public static void SeedUsers(IUserService userService)
        {
            User userAdmin = userService.FindByEmailAsync("*****@*****.**").Result;

            if (userAdmin == null)
            {
                User user = new User
                {
                    UserName     = "******",
                    Email        = "*****@*****.**",
                    FirstName    = "system",
                    LastName     = "admin",
                    IsSuperAdmin = true
                };
                userService.CreateAsync(user, "@dm1n1stR4tOr").Wait();
            }
            userAdmin = userService.FindByEmailAsync("*****@*****.**").Result;
            if (userAdmin != null)
            {
                if (!userService.GetRolesAsync(userAdmin).Result.Contains(RoleClaims.ADMIN_GROUP))
                {
                    userService.AddToRoleAsync(userAdmin, RoleClaims.ADMIN_GROUP).Wait();
                }
                IList <Claim> existingClaims = userService.GetClaimsAsync(userAdmin).Result;
                foreach (Claim claim in RoleClaims.GetAllAdminClaims())
                {
                    if (existingClaims.FirstOrDefault(x => claim.Type.Equals(x.Type) && claim.Value.Equals(x.Value)) == null)
                    {
                        userService.AddClaimAsync(userAdmin, claim).Wait();
                    }
                }
            }
        }
Example #2
0
        public async Task <IdentityResult> CreateWithClaimsAsync(RoleDto role)
        {
            Role roleToCreate = new Role()
            {
                Id = 0, Name = role.Name
            };
            IdentityResult result = await CreateAsync(roleToCreate);

            if (result == IdentityResult.Success)
            {
                Role createdRole = await FindRoleByNameAsync(roleToCreate.Name);

                List <Claim> claimsToAdd = new List <Claim>();
                foreach (string claimToInsert in role.Claims)
                {
                    foreach (Claim existingClaim in RoleClaims.GetAllClaims())
                    {
                        if (existingClaim.Value.Equals(claimToInsert))
                        {
                            claimsToAdd.Add(existingClaim);
                        }
                    }
                }
                foreach (Claim newClaim in claimsToAdd)
                {
                    await AddClaimAsync(createdRole, newClaim);
                }
            }
            return(result);
        }
Example #3
0
        /// <summary>
        /// Seeds the default data.
        /// </summary>
        private void Seed()
        {
            SaveChanges();

            // Make sure we have a SysAdmin role
            var role = Roles.FirstOrDefault(r => r.Name == "SysAdmin");

            if (role == null)
            {
                role = new Role
                {
                    Id             = Guid.NewGuid(),
                    Name           = "SysAdmin",
                    NormalizedName = "SYSADMIN"
                };
                Roles.Add(role);
            }

            // Make sure our SysAdmin role has all of the available claims
            //foreach (var claim in Piranha.Security.Permission.All())
            foreach (var permission in App.Permissions.GetPermissions())
            {
                var roleClaim = RoleClaims.FirstOrDefault(c => c.RoleId == role.Id && c.ClaimType == permission.Name && c.ClaimValue == permission.Name);
                if (roleClaim == null)
                {
                    RoleClaims.Add(new IdentityRoleClaim <Guid>
                    {
                        RoleId     = role.Id,
                        ClaimType  = permission.Name,
                        ClaimValue = permission.Name
                    });
                }
            }
            SaveChanges();
        }
Example #4
0
        public async Task <IActionResult> AddRole(AddAndEditRoleViewModels addRoleViewModels)
        {
            var role = Mapper.Map <Role>(addRoleViewModels);

            role.RoleClaims = new List <RoleClaims>();
            var roleNames = new List <string>();

            foreach (var key in Request.Form.Keys)
            {
                if (key.Contains("Permission.") && Request.Form[key].Contains("on"))
                {
                    roleNames.Add(key.Substring(11));
                }
            }
            List <RoleClaims> roleClaims1 = new List <RoleClaims>();

            foreach (var item in roleNames)
            {
                RoleClaims roleClaims2 = new RoleClaims();
                roleClaims2.ClaimType  = "RoleClaims";
                roleClaims2.ClaimValue = item;
                role.RoleClaims.Add(roleClaims2);
            }
            await _roleSever.AddRole(role);

            return(Redirect(nameof(ShowRole)));
        }
Example #5
0
        public async Task <IActionResult> UpdateRole(AddAndEditRoleViewModels role)
        {
            var role1 = Mapper.Map <Role>(role);
            await _roleSever.UpdateRole(role1);

            var roleNames = new List <string>();

            foreach (var key in Request.Form.Keys)
            {
                if (key.Contains("Permission.") && Request.Form[key].Contains("on"))
                {
                    roleNames.Add(key.Substring(11));
                }
            }
            var roleClaims = _roleClaimsSever.GetRoleClaims(new List <int>()
            {
                role1.Id
            });
            await _roleClaimsSever.Removes(roleClaims);

            List <RoleClaims> roleClaims1 = new List <RoleClaims>();

            foreach (var item in roleNames)
            {
                RoleClaims roleClaims2 = new RoleClaims();
                roleClaims2.RoleId     = role1.Id;
                roleClaims2.ClaimType  = "RoleClaims";
                roleClaims2.ClaimValue = item;
                roleClaims1.Add(roleClaims2);
            }
            await _roleClaimsSever.AddRoleClaims(roleClaims1);

            return(Redirect(nameof(ShowRole)));
        }
Example #6
0
 /// <summary>
 /// Erzeugen aller standart rollen (Admin und Datenschutzbeauftragter mit den jeweiligen rechten)
 /// </summary>
 /// <param name="roleService">rollen service</param>
 public static void SeedRoles(IRoleService roleService)
 {
     foreach (string roleToCreate in RoleClaims.DEFAULT_GROUPS)
     {
         Role role = roleService.FindRoleByNameAsync(roleToCreate).Result;
         if (role == null)
         {
             roleService.CreateAsync(new Role()
             {
                 Name = roleToCreate
             }).Wait();
         }
         role = roleService.FindRoleByNameAsync(roleToCreate).Result;
         if (role != null)
         {
             IList <Claim> existingClaims = roleService.GetClaimsAsync(role).Result;
             List <Claim>  claimsToCheck  = new List <Claim>();
             if (role.Name.Equals(RoleClaims.ADMIN_GROUP))
             {
                 claimsToCheck = RoleClaims.GetAllAdminClaims();
             }
             else if (role.Name.Equals(RoleClaims.DATA_SECURITY_ENGINEER_GROUP))
             {
                 claimsToCheck = RoleClaims.GetAllDsgvoClaims();
             }
             foreach (Claim claim in claimsToCheck)
             {
                 if (existingClaims.FirstOrDefault(x => x.Type.Equals(claim.Type) && x.Value.Equals(claim.Value)) == null)
                 {
                     roleService.AddClaimAsync(role, claim).Wait();
                 }
             }
         }
     }
 }
Example #7
0
 public virtual async Task <IList <Claim> > GetClaimsAsync(IdentityRoleNav <TKey> role, CancellationToken cancellationToken = default)
 {
     ThrowIfDisposed();
     if (role == null)
     {
         throw new ArgumentNullException(nameof(role));
     }
     return(await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id)).Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToListAsync(cancellationToken));
 }
Example #8
0
        public override async Task AddClaimAsync(IdentityRole <TKey> role, Claim claim, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            role.ThrowIfNull(nameof(role));
            claim.ThrowIfNull(nameof(claim));

            RoleClaims ??= (await RoleClaimsTable.GetClaimsAsync(role.Id)).ToList();
            RoleClaims.Add(CreateRoleClaim(role, claim));
        }
Example #9
0
        public async override Task <IList <Claim> > GetClaimsAsync(Role role, CancellationToken cancellationToken = default(CancellationToken))
        {
            ThrowIfDisposed();
            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }

            return(await RoleClaims.Where(rc => rc.RoleId == role.Id).Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToListAsync(cancellationToken));
        }
Example #10
0
        public async Task <IActionResult> GetAllClaims(long id)
        {
            List <string> list = new List <string>();

            foreach (Claim claim in await Task.FromResult(RoleClaims.GetAllClaims()))
            {
                list.Add(claim.Value);
            }
            return(Ok(list));
        }
Example #11
0
 public async Task <IdentityResult> RemoveClaimAsync(Role role, Claim claim)
 {
     if ((role.Id == 1 && RoleClaims.GetAllAdminClaims().FirstOrDefault(x => x.Type.Equals(claim.Type)) != null &&
          RoleClaims.GetAllAdminClaims().FirstOrDefault(x => x.Value.Equals(claim.Value)) != null) ||
         role.Id == 2 && RoleClaims.GetAllDsgvoClaims().FirstOrDefault(x => x.Type.Equals(claim.Type)) != null &&
         RoleClaims.GetAllDsgvoClaims().FirstOrDefault(x => x.Value.Equals(claim.Value)) != null)
     {
         return(IdentityResult.Success);
     }
     return(await manager.RemoveClaimAsync(role, claim));
 }
Example #12
0
        public async virtual Task RemoveClaimAsync(Role role, Claim claim, CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            role.CheakArgument();
            claim.CheakArgument();
            var claims = await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id) && rc.ClaimValue == claim.Value && rc.ClaimType == claim.Type).ToListAsync(cancellationToken);

            foreach (var c in claims)
            {
                RoleClaims.Remove(c);
            }
        }
        /// <summary>
        /// Adds the <paramref name="claim"/> given to the specified <paramref name="role"/>.
        /// </summary>
        /// <param name="role">The role to add the claim to.</param>
        /// <param name="claim">The claim to add to the role.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
        public virtual Task AddClaimAsync(Role role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
        {
            ThrowIfDisposed();
            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }
            if (claim == null)
            {
                throw new ArgumentNullException(nameof(claim));
            }

            RoleClaims.Add(CreateRoleClaim(role, claim));
            return(Task.FromResult(false));
        }
Example #14
0
        public override async Task RemoveClaimAsync(IdentityRole <TKey> role, Claim claim, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            role.ThrowIfNull(nameof(role));
            claim.ThrowIfNull(nameof(claim));

            RoleClaims ??= (await RoleClaimsTable.GetClaimsAsync(role.Id)).ToList();
            var roleClaims = RoleClaims.Where(x => x.RoleId.Equals(role.Id) && x.ClaimType == claim.Type && x.ClaimValue == claim.Value);

            foreach (var roleCalim in roleClaims)
            {
                RoleClaims.Remove(roleCalim);
            }
        }
        public async Task <IActionResult> Login([FromBody] CredentialsDto credentials)
        {
            var user = await _userService.FindByNameAsync(credentials.UserNameOrEmail);

            if (user == null)
            {
                user = await _userService.FindByEmailAsync(credentials.UserNameOrEmail);

                if (user == null)
                {
                    return(BadRequest("Login fehlgeschlagen!"));
                }
            }
            user.LastLoginDate = DateTime.Now;
            await _userService.UpdateUserAsync(user);

            await userLoginService.CreateAsync(new UserLogin()
            {
                DateTimeOfLastLogin = DateTime.Now, UserId = user.Id
            });

            if (user.UserLockEnabled)
            {
                return(BadRequest("Benutzer ist gesperrt! Bitte den Administrator kontaktieren"));
            }

            var signInAsync = await _signInService.CheckPasswordSignInAsync(user, credentials.Password);

            if (signInAsync.Succeeded)
            {
                var userDto = _mapper.Map <UserDto>(user);
                var roles   = await _userService.GetRolesAsync(user);

                List <Claim> claims;
                if (!user.IsSuperAdmin)
                {
                    claims = await GetAllClaimsOfUser(roles);
                }
                else
                {
                    claims = RoleClaims.GetAllClaims();
                }
                userDto.AccessToken = _signInService.CreateToken(user, roles, claims);
                return(Ok(userDto));
            }

            return(BadRequest("Login fehlgeschlagen!"));
        }
Example #16
0
        public IEnumerable <RoleClaims> GetAllRoleClaims()
        {
            var roleClaims = (from role in _context.Roles
                              join claim in _context.RoleClaims on role.Id equals claim.RoleId into RoleClaims
                              from rc in RoleClaims.DefaultIfEmpty()
                              select new { Role = role, RoleClaims = rc }
                              ).ToLookup(x => x.Role)
                             .Select(x => new { Role = x.Key, Claims = x.Select(c => c.RoleClaims).Where(c => c != null).ToList() });

            var convertedRoleClaims = roleClaims.Select(x =>
                                                        new RoleClaims {
                Role = _mapper.Map <Role>(x.Role), Claims = x.Claims != null ? x.Claims.Select(c => c.ClaimValue) : new List <string>()
            });

            return(convertedRoleClaims);
        }
Example #17
0
        public IEnumerable <Claim> GetClaimsForUser(Guid userId)
        {
            var user = Users.Get(userId);

            if (user == null)
            {
                throw new ArgumentException(nameof(userId) + "does not belong to any user");
            }
            var roleId = user.RoleId;

            if (!roleId.HasValue)
            {
                throw new ArgumentException("user with given " + nameof(userId) + " does not belong to any role, and therefore has no claims.");
            }
            var claims = RoleClaims.GetClaimsForRole(roleId.Value);

            return(claims);
        }
        /// <summary>
        /// Removes the <paramref name="claim"/> given from the specified <paramref name="role"/>.
        /// </summary>
        /// <param name="role">The role to remove the claim from.</param>
        /// <param name="claim">The claim to remove from the role.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns>
        public async virtual Task RemoveClaimAsync(Role role, Claim claim, CancellationToken cancellationToken = default(CancellationToken))
        {
            ThrowIfDisposed();
            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }
            if (claim == null)
            {
                throw new ArgumentNullException(nameof(claim));
            }
            var claims = await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id) && rc.ClaimValue == claim.Value && rc.ClaimType == claim.Type).ToListAsync(cancellationToken);

            foreach (var c in claims)
            {
                RoleClaims.Remove(c);
            }
        }
Example #19
0
        public virtual async Task RemoveClaimAsync(IdentityRoleNav <TKey> role, Claim claim, CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            if (role == null)
            {
                throw new ArgumentNullException(nameof(role));
            }
            if (claim == null)
            {
                throw new ArgumentNullException(nameof(claim));
            }
            var claims = await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id) && rc.ClaimValue == claim.Value && rc.ClaimType == claim.Type).ToListAsync(cancellationToken);

            foreach (var c in claims)
            {
                RoleClaims.DataContext.Delete(c);
            }
        }
Example #20
0
        private async Task <IdentityResult> UpdateClaimsAsync(LondonTravelUser user, ExternalLoginInfo info)
        {
            bool commitUpdate = false;

            if (user.RoleClaims == null)
            {
                user.RoleClaims = new List <LondonTravelRole>();
                commitUpdate    = true;
            }

            foreach (var claim in info.Principal.Claims)
            {
                bool hasClaim = user?.RoleClaims
                                .Where((p) => p.ClaimType == claim.Type)
                                .Where((p) => p.Issuer == claim.Issuer)
                                .Where((p) => p.Value == claim.Value)
                                .Where((p) => p.ValueType == claim.ValueType)
                                .Any() == true;

                if (!hasClaim)
                {
                    user !.RoleClaims.Add(LondonTravelRole.FromClaim(claim));
                    commitUpdate = true;
                }
            }

            if (commitUpdate)
            {
                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    _telemetry.TrackClaimsUpdated(user.Id !);
                }

                return(result);
            }
            else
            {
                return(IdentityResult.Success);
            }
        }
Example #21
0
        public RoleClaims GetRoleClaims(string roleId)
        {
            var roleClaims = (from role in _context.Roles
                              join claim in _context.RoleClaims on role.Id equals claim.RoleId into RoleClaims
                              from rc in RoleClaims.DefaultIfEmpty()
                              select new
            {
                Role = role,
                RoleClaims = rc
            }).ToLookup(x => x.Role)
                             .Select(x => new { Role = x.Key, Claims = x.Select(x => x.RoleClaims).Where(c => c != null).ToList() })
                             .FirstOrDefault(x => x.Role.Id == roleId);

            var model = new RoleClaims();

            model.Role   = _mapper.Map <Role>(roleClaims.Role);
            model.Claims = roleClaims.Claims != null?roleClaims.Claims.Select(x => x.ClaimValue) : new List <string>();

            return(model);
        }
Example #22
0
        public virtual async Task <IdentityResult> AddClaimAsync(IdentityRole role, Claim claim, CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            role.CheakArgument();
            claim.CheakArgument();
            var f2 = await DbEntitySet.AnyAsync(d => d.Id.Equals(role.Id));

            if (f2)
            {
                var flag = await RoleClaims.AnyAsync(a => a.ClaimType.Equals(claim.Type) &&
                                                     a.ClaimValue.Equals(claim.Value) && a.RoleId.Equals(role.Id));

                if (!flag)
                {
                    RoleClaims.Add(CreateRoleClaim(role, claim));
                    return(await SaveChangesAsync(cancellationToken));
                }
            }
            return(IdentityResult.Failed("已经存在该权限"));
        }
Example #23
0
        public async virtual Task <IdentityResult> RemoveClaimAsync(IdentityRole role, Claim claim, CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            role.CheakArgument();
            claim.CheakArgument();
            var rolecasims = RoleClaims.Where(rc =>
                                              rc.RoleId.Equals(role.Id) &&
                                              rc.ClaimValue == claim.Value &&
                                              rc.ClaimType == claim.Type).Select(s => new IdentityRole()
            {
                Id = s.Id, EditedTime = s.EditedTime
            });

            AutoSaveChanges = false;
            foreach (var item in rolecasims)
            {
                item.IsDeleted = true;
                var delte = await DeleteAsync(item, default);
            }
            AutoSaveChanges = true;
            return(await SaveChangesAsync(cancellationToken));
        }
        private UserRolesClaims GetProfile(BlogUser user)
        {
            var profile   = new UserRolesClaims();
            var userRoles = _context.UserRoles.Where(x => x.UserId == user.Id).Select(x => x.RoleId);
            var roles     = (from role in _context.Roles
                             where userRoles.Contains(role.Id)
                             join claim in _context.RoleClaims on role.Id equals claim.RoleId into RoleClaims
                             from rc in RoleClaims.DefaultIfEmpty()
                             select new
            {
                Role = role,
                Claims = rc
            }).ToLookup(x => x.Role)
                            .Select(x => new { Role = x.Key, Claims = x.Select(c => c.Claims).Where(c => c != null).ToList() });

            var userClaims      = _context.UserClaims.Where(x => x.UserId == user.Id);
            var groupUserEmails = _context.Users.Where(x =>
                                                       user.SupervisorId == null ?
                                                       x.SupervisorId == user.Id :
                                                       (x.SupervisorId == user.SupervisorId || x.Id == user.SupervisorId) && x.Id != user.Id).Select(x => x.Email);
            var roleClaims = new List <RoleClaims>();

            foreach (var r in roles)
            {
                var roleClaim = new RoleClaims();
                roleClaim.Role   = _mapper.Map <Role>(r.Role);
                roleClaim.Claims = r.Claims.Select(x => x.ClaimValue);
                roleClaims.Add(roleClaim);
            }

            profile.User        = _mapper.Map <User>(user);
            profile.UserClaims  = _mapper.Map <IEnumerable <UserClaim> >(userClaims);
            profile.Roles       = roleClaims;
            profile.GroupEmails = groupUserEmails;

            return(profile);
        }
Example #25
0
        public async Task <IdentityResult> UpdateRoleWithClaimsAsync(RoleDto role)
        {
            Role roleToUpdate = await FindRoleByIdAsync(role.Id);

            if (roleToUpdate == null)
            {
                return(IdentityResult.Failed(new IdentityError()
                {
                    Code = "301", Description = "Role not found!"
                }));
            }
            if (!roleToUpdate.Name.Equals(role.Name) && role.Id > 2)
            {
                if (!await CheckIfRoleNameAlreadyExistsAsync(role.Name))
                {
                    roleToUpdate.Name = role.Name;
                    await UpdateAsync(roleToUpdate);
                }
            }

            List <Claim>  claimsToDelete = new List <Claim>();
            IList <Claim> existingClaims = await GetClaimsAsync(roleToUpdate);

            foreach (Claim existingClaim in existingClaims)
            {
                if (role.Claims.FirstOrDefault(x => x.Equals(existingClaim.Value)) == null)
                {
                    claimsToDelete.Add(existingClaim);
                }
            }
            foreach (Claim claimToDelete in claimsToDelete)
            {
                await RemoveClaimAsync(roleToUpdate, claimToDelete);
            }
            List <Claim> claimsToAdd = new List <Claim>();
            bool         error       = false;

            foreach (string claimToAdd in role.Claims)
            {
                if (existingClaims.FirstOrDefault(x => x.Value.Equals(claimToAdd)) == null)
                {
                    Claim existingClaimToAdd = RoleClaims.GetAllClaims().FirstOrDefault(x => x.Value.Equals(claimToAdd));
                    if (existingClaimToAdd != null)
                    {
                        claimsToAdd.Add(existingClaimToAdd);
                    }
                    else
                    {
                        error = true;
                    }
                }
            }
            foreach (Claim claimToAdd in claimsToAdd)
            {
                await AddClaimAsync(roleToUpdate, claimToAdd);
            }
            if (!error)
            {
                return(IdentityResult.Success);
            }
            else
            {
                return(IdentityResult.Failed(new IdentityError()
                {
                    Code = "201", Description = "Claim not found!"
                }));
            }
        }
Example #26
0
 public async virtual Task <IList <Claim> > GetClaimsAsync(Role role, CancellationToken cancellationToken = default)
 {
     ThrowIfDisposed();
     role.CheakArgument();
     return(await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id)).Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToListAsync(cancellationToken));
 }