public async Task <bool> Execute(AddUserParameter addUserParameter)
        {
            if (addUserParameter == null)
            {
                throw new ArgumentNullException(nameof(addUserParameter));
            }

            if (string.IsNullOrEmpty(addUserParameter.Login))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Login));
            }

            if (string.IsNullOrWhiteSpace(addUserParameter.Password))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Password));
            }

            if (await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(addUserParameter.Login,
                                                                                       addUserParameter.Password) != null)
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheRoWithCredentialsAlreadyExists);
            }

            var newClaims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()),
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login)
            };
            var newResourceOwner = new ResourceOwner
            {
                Id     = addUserParameter.Login,
                Claims = newClaims,
                TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                IsLocalAccount          = true,
                Password = _authenticateResourceOwnerService.GetHashedPassword(addUserParameter.Password)
            };
            var claims = (await _claimRepository.GetAllAsync()).Select(c => c.Code);

            if (addUserParameter.Claims != null)
            {
                foreach (var claim in addUserParameter.Claims.Where(c => claims.Contains(c.Type)))
                {
                    newResourceOwner.Claims.Add(claim);
                }
            }

            if (!newResourceOwner.Claims.Any(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject))
            {
                newResourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login));
            }

            await _resourceOwnerRepository.InsertAsync(newResourceOwner);

            return(true);
        }
        public async Task <bool> Execute(UpdateUserParameter updateUserParameter)
        {
            if (updateUserParameter == null)
            {
                throw new ArgumentNullException(nameof(updateUserParameter));
            }

            if (string.IsNullOrWhiteSpace(updateUserParameter.Login))
            {
                throw new ArgumentNullException(nameof(updateUserParameter.Login));
            }

            var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(updateUserParameter.Login);

            if (resourceOwner == null)
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.InternalError,
                          Errors.ErrorDescriptions.TheRoDoesntExist);
            }

            resourceOwner.TwoFactorAuthentication = updateUserParameter.TwoFactorAuthentication;
            if (!string.IsNullOrWhiteSpace(updateUserParameter.Password))
            {
                resourceOwner.Password = _authenticateResourceOwnerService.GetHashedPassword(updateUserParameter.Password);
            }

            resourceOwner.Claims = updateUserParameter.Claims;
            if (resourceOwner.Claims != null)
            {
                Claim updatedClaim;
                if (((updatedClaim = resourceOwner.Claims.FirstOrDefault(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt)) != null))
                {
                    resourceOwner.Claims.Remove(updatedClaim);
                }

                resourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()));
            }

            return(await _resourceOwnerRepository.UpdateAsync(resourceOwner));
        }
        public async Task Execute(AddUserParameter addUserParameter)
        {
            if (addUserParameter == null)
            {
                throw new ArgumentNullException(nameof(addUserParameter));
            }

            if (string.IsNullOrEmpty(addUserParameter.Login))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Login));
            }

            if (string.IsNullOrWhiteSpace(addUserParameter.Password))
            {
                throw new ArgumentNullException(nameof(addUserParameter.Password));
            }

            if (await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(addUserParameter.Login,
                                                                                       addUserParameter.Password) != null)
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheRoWithCredentialsAlreadyExists);
            }

            var claims = new List <Claim>
            {
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()),
                new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, addUserParameter.Login)
            };
            var newResourceOwner = new ResourceOwner
            {
                Id     = addUserParameter.Login,
                Claims = claims,
                TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                IsLocalAccount          = true,
                Password = _authenticateResourceOwnerService.GetHashedPassword(addUserParameter.Password)
            };
            await _resourceOwnerRepository.InsertAsync(newResourceOwner);
        }
Beispiel #4
0
        [HttpPut] // User Authentication enabled.
        public async Task <IActionResult> Update([FromBody] JObject json)
        {
            if (json == null)
            {
                throw new ArgumentNullException(nameof(json));
            }

            // 1. Get the subject.
            var subjectResult = await GetSubject();

            if (!subjectResult.IsValid)
            {
                return(subjectResult.Error);
            }

            // 2. Check the user exists.
            var user = await _resourceOwnerRepository.GetAsync(subjectResult.Subject);

            if (user == null)
            {
                return(this.BuildError(ErrorCodes.InvalidRequestCode, ErrorDescriptions.TheRoDoesntExist, HttpStatusCode.NotFound));
            }

            // 4. Construct the request and update user information.
            var updateParameter = _requestBuilder.GetUpdateUserParameter(json);

            updateParameter.Login = subjectResult.Subject;
            var claims         = updateParameter.Claims;
            var assignedClaims = claims.Where(c => c.Type != SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Picture && c.Type != Constants.Claims.BannerImage && c.Type != SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject).ToList();

            assignedClaims.Add(new Claim(SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subjectResult.Subject));
            var pictureClaim = claims.FirstOrDefault(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Picture);
            var bannerClaim  = claims.FirstOrDefault(c => c.Type == Constants.Claims.BannerImage);

            if (pictureClaim != null)
            {
                string path;
                if (AddImage(pictureClaim.Value, subjectResult.Subject, true, out path))
                {
                    assignedClaims.Add(new Claim(SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Picture, path));
                }
                else
                {
                    assignedClaims.Add(pictureClaim);
                }
            }

            if (bannerClaim != null)
            {
                string path;
                if (AddImage(bannerClaim.Value, subjectResult.Subject, false, out path))
                {
                    assignedClaims.Add(new Claim(Constants.Claims.BannerImage, path));
                }
                else
                {
                    assignedClaims.Add(bannerClaim);
                }
            }


            user.TwoFactorAuthentication = updateParameter.TwoFactorAuthentication;
            if (!string.IsNullOrWhiteSpace(updateParameter.Password) && user.IsLocalAccount)
            {
                if (!Regex.IsMatch(updateParameter.Password, @"^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$"))
                {
                    return(this.BuildError(ErrorCodes.InvalidRequestCode, "the password is not correct", HttpStatusCode.InternalServerError));
                }

                user.Password = _authenticateResourceOwnerService.GetHashedPassword(updateParameter.Password);
            }

            user.Claims = assignedClaims;
            if (user.Claims != null)
            {
                Claim updatedClaim;
                if (((updatedClaim = user.Claims.FirstOrDefault(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt)) != null))
                {
                    user.Claims.Remove(updatedClaim);
                }

                user.Claims.Add(new Claim(SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.UpdatedAt, DateTime.UtcNow.ToString()));
            }

            // 5. Update the information.
            if (!await _resourceOwnerRepository.UpdateAsync(user))
            {
                return(this.BuildError(ErrorCodes.UnhandledExceptionCode, Constants.ErrorMessages.ErrorOccuredWhileTryingToUpdateTheUser));
            }

            return(new OkResult());
        }
        public async Task <IEnumerable <Claim> > Execute(ClaimsPrincipal claimsPrincipal)
        {
            // 1. Check parameters.
            if (claimsPrincipal == null)
            {
                throw new ArgumentNullException(nameof(claimsPrincipal));
            }

            // 2. Check the user is authenticated.
            if (claimsPrincipal.Identity == null ||
                !claimsPrincipal.Identity.IsAuthenticated ||
                !(claimsPrincipal.Identity is ClaimsIdentity))
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheUserNeedsToBeAuthenticated);
            }

            // 3. Check the subject exists.
            var subject = claimsPrincipal.GetSubject();

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new IdentityServerException(
                          Errors.ErrorCodes.UnhandledExceptionCode,
                          Errors.ErrorDescriptions.TheRoCannotBeCreated);
            }

            // 4. If a user already exists with the same subject then ignore.
            var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(subject);

            if (resourceOwner != null)
            {
                return(resourceOwner.Claims);
            }

            // 5. Insert the resource owner.
            var clearPassword = Guid.NewGuid().ToString();

            resourceOwner = new ResourceOwner
            {
                Id                      = subject,
                IsLocalAccount          = false,
                TwoFactorAuthentication = TwoFactorAuthentications.NONE,
                Claims                  = new List <Claim>(),
                Password                = _authenticateResourceOwnerService.GetHashedPassword(clearPassword)
            };
            var claims = await _claimRepository.GetAllAsync();

            foreach (var claim in claimsPrincipal.Claims.Where(c => claims.Contains(c.Type)))
            {
                resourceOwner.Claims.Add(claim);
            }

            if (!resourceOwner.Claims.Any(c => c.Type == Jwt.Constants.StandardResourceOwnerClaimNames.Subject))
            {
                resourceOwner.Claims.Add(new Claim(Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject));
            }

            await _resourceOwnerRepository.InsertAsync(resourceOwner);

            return(resourceOwner.Claims);
        }