public async Task <GenericResponse <ShapedDataWithLinks> > GetRefreshTokens(RefreshTokenResourceParameter resourceParameter, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <ShapedDataWithLinks>(null, "Wrong media type"));
                }

                var refreshTokens = await this.dataService.RefreshTokens.FindAllAsync(resourceParameter);

                if (refreshTokens.Count == 0)
                {
                    return(GenericResponseBuilder.Success <ShapedDataWithLinks>(null));
                }

                var paginationMetaData = new PaginationMetaData
                {
                    TotalCount  = refreshTokens.TotalCount,
                    PageSize    = refreshTokens.PageSize,
                    CurrentPage = refreshTokens.CurrentPage,
                    TotalPages  = refreshTokens.TotalPages
                };

                var links = CreateLinksForRefreshTokens(resourceParameter, refreshTokens.HasNext, refreshTokens.HasPrevious);

                var shapedRefreshTokens = this.mapper
                                          .Map <IEnumerable <RefreshTokenDto> >(refreshTokens)
                                          .ShapeData(resourceParameter.Fields);

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);

                var refreshTokensToReturnWithLinks = shapedRefreshTokens.Select(token =>
                {
                    var tokenAsDictionary = token as IDictionary <string, object>;
                    if (includeLinks)
                    {
                        var userLinks = CreateLinksForRefreshToken((Guid)tokenAsDictionary["Id"], resourceParameter.Fields);
                        tokenAsDictionary.Add("links", userLinks);
                    }
                    return(tokenAsDictionary);
                });

                var refreshTokensToReturn = new ShapedDataWithLinks()
                {
                    Value = refreshTokensToReturnWithLinks,
                    Links = links,
                    PaginationMetaData = paginationMetaData
                };

                return(GenericResponseBuilder.Success <ShapedDataWithLinks>(refreshTokensToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - GetRefreshTokens. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <ShapedDataWithLinks>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> ResetPassword(ResetPasswordDto resetPasswordDto)
        {
            try
            {
                var identityUser = await this.dataService.UserManager.FindByEmailAsync(resetPasswordDto.Email);

                if (identityUser == null)
                {
                    return(GenericResponseBuilder.Success());
                }

                IdentityResult identityResult = await this.dataService.UserManager.ResetPasswordAsync(
                    identityUser, HttpUtility.UrlDecode(resetPasswordDto.Token), resetPasswordDto.Password);

                if (!identityResult.Succeeded)
                {
                    return(GenericResponseBuilder.NoSuccess <IdentityResult>(identityResult));
                }

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - ResetPassword. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess(ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <UserDto> > ManageUserClaims(Guid id, List <ClaimForManipulationDto> claims, bool remove = false)
        {
            try
            {
                var user = await this.dataService.UserManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return(GenericResponseBuilder.Success <UserDto>(null));
                }

                var currentUserClaims = await this.dataService.UserManager.GetClaimsAsync(user);

                foreach (var claim in claims)
                {
                    if (!currentUserClaims.Any(c => c.Type == claim.Type && c.Value == claim.Value) & !remove)
                    {
                        await this.dataService.UserManager.AddClaimAsync(user, CreateClaim(claim.Type, claim.Value));
                    }
                    else if (currentUserClaims.Any(c => c.Type == claim.Type && c.Value == claim.Value) & remove)
                    {
                        await this.dataService.UserManager.RemoveClaimAsync(user, CreateClaim(claim.Type, claim.Value));
                    }
                }
                return(GenericResponseBuilder.Success <UserDto>(this.mapper.Map <UserDto>(user)));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - ManageUserClaims. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <UserDto>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> ForgotPassword(UserEmailDto userEmailDto)
        {
            try
            {
                var identityUser = await this.dataService.UserManager.FindByEmailAsync(userEmailDto.Email);

                if (identityUser == null)
                {
                    return(GenericResponseBuilder.Success());
                }

                var token = await dataService.UserManager.GeneratePasswordResetTokenAsync(identityUser);

                var configKey     = "UIPageAddresses:ResetPasswordFormPageAddress";
                var emailObject   = GenerateEmailLink(identityUser, configKey, token, "email");
                var passwordEmail = this.mapper.Map <ForgotPasswordEmail>(emailObject);
                var emailSent     = await this.emailProvider.SendForgotPasswordEmail(passwordEmail);

                if (!emailSent)
                {
                    return(GenericResponseBuilder.NoSuccess("Email send failed"));
                }

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - ForgotPassword. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess(ex.Message.ToString()));
            }
        }
Esempio n. 5
0
        public async Task <GenericResponse> ChangePassword(Guid userId, ChangePasswordDto changePasswordDto)
        {
            try
            {
                var applicationUser = await this.dataService.UserManager.FindByIdAsync(userId.ToString());

                if (applicationUser == null)
                {
                    return(GenericResponseBuilder.NoSuccess <IdentityResult>(null));
                }

                var identityResult = await this.dataService.UserManager.ChangePasswordAsync(
                    applicationUser, changePasswordDto.CurrentPassword, changePasswordDto.NewPassword);

                if (!identityResult.Succeeded)
                {
                    return(GenericResponseBuilder.NoSuccess <IdentityResult>(identityResult, "Password change request unsuccessfully"));
                }

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - ChangePassword. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IdentityResult>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> DeleteRole(Guid id)
        {
            try
            {
                var roleEntity = await this.dataService.RoleManager.FindByIdAsync(id.ToString());

                if (roleEntity == null)
                {
                    return(GenericResponseBuilder.Success());
                }

                var result = await this.dataService.RoleManager.DeleteAsync(roleEntity);

                if (!result.Succeeded)
                {
                    return(GenericResponseBuilder.NoSuccess(result));
                }

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - DeleteRole. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess(ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <IList <Claim> > > GetUserClaims(Guid id)
        {
            try
            {
                var user = await this.dataService.UserManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return(GenericResponseBuilder.Success <IList <Claim> >(null));
                }

                var claimsToReturn = await this.dataService.UserManager.GetClaimsAsync(user);

                if (claimsToReturn.Count == 0)
                {
                    return(GenericResponseBuilder.Success <IList <Claim> >(null));
                }

                return(GenericResponseBuilder.Success <IList <Claim> >(claimsToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - GetUserClaims. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IList <Claim> >(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> ConfirmEmail(Guid userId, string token)
        {
            try
            {
                var userToConfirm = await this.dataService.UserManager.FindByIdAsync(userId.ToString());

                if (userToConfirm == null)
                {
                    return(GenericResponseBuilder.NoSuccess <IdentityResult>(null, "Not found"));
                }

                var identityResult = await this.dataService.UserManager.ConfirmEmailAsync(userToConfirm, token);

                if (identityResult.Succeeded)
                {
                    return(GenericResponseBuilder.Success());
                }

                return(GenericResponseBuilder.NoSuccess <IdentityResult>(identityResult));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - ConfirmEmail. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IdentityResult>(null, ex.Message.ToString()));
            }
        }
Esempio n. 9
0
        public async Task <GenericResponse <ApplicationClient> > GetApplicationClient(Guid id)
        {
            try
            {
                var entity = await this.dataService.ApplicationClients.FindByIdAsync(id);

                return(GenericResponseBuilder.Success <ApplicationClient>(entity));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - GetApplicationClient. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <ApplicationClient>(null, ex.Message.ToString()));
            }
        }
Esempio n. 10
0
        public async Task <GenericResponse <IDictionary <string, object> > > CreateApplicationClient(ApplicationClientForCreationDto applicationClient, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong media type"));
                }

                var regex = new Regex("^[a-zA-Z0-9 ]*$");
                if (!regex.IsMatch(applicationClient.Name))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Special characters are not allowed in the client name."));
                }

                var client = await this.dataService.ApplicationClients.FindByNameAsync(applicationClient.Name);

                if (client != null)
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, string.Format("Client already exits with name: {0}", applicationClient.Name)));
                }

                var applicationClientEntity = this.mapper.Map <ApplicationClient>(applicationClient);
                CreateClientSecret(applicationClientEntity);

                this.dataService.ApplicationClients.Create(applicationClientEntity);
                await this.dataService.CompleteAsync();

                var clientToReturn = this.mapper.Map <ApplicationClientDto>(applicationClientEntity)
                                     .ShapeData()
                                     as IDictionary <string, object>;

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);
                if (includeLinks)
                {
                    var links = CreateLinksForApplicationClient(applicationClientEntity.Id);
                    clientToReturn.Add("links", links);
                }

                return(GenericResponseBuilder.Success <IDictionary <string, object> >(clientToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - CreateApplicationClient. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <IEnumerable <IDictionary <string, object> > > > GetRoles(string fields, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <IEnumerable <IDictionary <string, object> > >(null, "Wrong media type"));
                }

                if (!this.propertyCheckerService.TypeHasProperties <RoleDto>(fields, true))
                {
                    return(GenericResponseBuilder.NoSuccess <IEnumerable <IDictionary <string, object> > >(null, "Wrong fields entered"));
                }

                var roles = await this.dataService.RoleManager.Roles.ToListAsync();

                var rolesToReturn = this.mapper
                                    .Map <IEnumerable <RoleDto> >(roles)
                                    .ShapeData(fields);

                if (roles.Count == 0)
                {
                    return(GenericResponseBuilder.Success <IEnumerable <IDictionary <string, object> > >(rolesToReturn));
                }

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);

                var rolesToReturnWithLinks = rolesToReturn.Select(role =>
                {
                    var roleAsDictionary = role as IDictionary <string, object>;
                    if (includeLinks)
                    {
                        var rolesLinks = CreateLinksForRole((Guid)roleAsDictionary["Id"], fields);
                        roleAsDictionary.Add("links", rolesLinks);
                    }
                    return(roleAsDictionary);
                });

                return(GenericResponseBuilder.Success <IEnumerable <IDictionary <string, object> > >(rolesToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - GetRoles. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IEnumerable <IDictionary <string, object> > >(null, ex.Message.ToString()));
            }
        }
Esempio n. 12
0
        public async Task <GenericResponse <IDictionary <string, object> > > GetUser(Guid id, string fields, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong media type"));
                }

                if (!propertyCheckerService.TypeHasProperties <UserWithRolesClaimsDto>(fields))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong fields entered"));
                }

                var user = await this.dataService.UserManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return(GenericResponseBuilder.Success <IDictionary <string, object> >(null));
                }

                var userToReturn = this.mapper.Map <UserWithRolesClaimsDto>(user);
                userToReturn.Roles = await this.dataService.UserManager.GetRolesAsync(user);

                userToReturn.Claims = await this.dataService.UserManager.GetClaimsAsync(user);

                var userToReturnShaped = userToReturn
                                         .ShapeData(fields)
                                         as IDictionary <string, object>;

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);

                if (includeLinks)
                {
                    var links = CreateLinksForUser(id, fields);
                    userToReturnShaped.Add("links", links);
                }

                return(GenericResponseBuilder.Success <IDictionary <string, object> >(userToReturnShaped));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - GetUser. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, ex.Message.ToString()));
            }
        }
Esempio n. 13
0
        public async Task <GenericResponse> UpdateApplicationClient(ApplicationClient applicationClient, ApplicationClientForUpdateDto applicationClientForUpdate)
        {
            try
            {
                this.mapper.Map(applicationClientForUpdate, applicationClient);

                this.dataService.ApplicationClients.Update(applicationClient);
                await this.dataService.CompleteAsync();

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - UpdateApplicationClient. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess(ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> UpdateUserProfile(UserProfile userProfile, UserProfileForUpdateDto userProfileToPatch)
        {
            try
            {
                this.mapper.Map(userProfileToPatch, userProfile);

                this.dataService.UserProfiles.Update(userProfile);
                await this.dataService.CompleteAsync();

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                //ToDo Log Error
                return(GenericResponseBuilder.NoSuccess($"{ex.Message} InnerException: {ex.InnerException.Message}"));
            }
        }
        public async Task <GenericResponse <IDictionary <string, object> > > AddNewUserProfile(Guid userId, UserProfileForCreationDto userProfileForCreation, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong media type."));
                }

                var currentUserProfileExists = await GetUserProfile(userId);

                if (currentUserProfileExists.Result != null)
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "User profile aready exits. Please use `PATCH` method for partial updates."));
                }


                var userProfileEntity = this.mapper.Map <UserProfile>(userProfileForCreation);
                userProfileEntity.UserId = userId;

                this.dataService.UserProfiles.Create(userProfileEntity);

                await this.dataService.CompleteAsync();

                var userProfileToReturn = this.mapper.Map <UserProfileDto>(userProfileEntity)
                                          .ShapeData()
                                          as IDictionary <string, object>;

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);
                if (includeLinks)
                {
                    var links = CreateLinksForUserProfiles(userId);
                    userProfileToReturn.Add("links", links);
                }

                return(GenericResponseBuilder.Success <IDictionary <string, object> >(userProfileToReturn));
            }
            catch (Exception ex)
            {
                //ToDo Log Error
                return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, $"{ex.Message} InnerException: {ex.InnerException.Message}"));
            }
        }
        public async Task <GenericResponse <IDictionary <string, object> > > GetRole(Guid id, string fields, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong media type"));
                }
                if (!propertyCheckerService.TypeHasProperties <RoleDto>(fields))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong fields entered"));
                }

                var roleEntity = await this.dataService.RoleManager.FindByIdAsync(id.ToString());

                if (roleEntity == null)
                {
                    var emptyDictionary = new Dictionary <string, object>();
                    return(GenericResponseBuilder.Success <IDictionary <string, object> >(emptyDictionary));
                }

                var roleToReturn = this.mapper.Map <RoleDto>(roleEntity)
                                   .ShapeData(fields)
                                   as IDictionary <string, object>;

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);

                if (includeLinks)
                {
                    var links = CreateLinksForRole(id, fields);
                    roleToReturn.Add("links", links);
                }

                return(GenericResponseBuilder.Success <IDictionary <string, object> >(roleToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - GetRole. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <IDictionary <string, object> > > GetUserProfileDto(Guid userId, string fields, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong media type"));
                }

                if (!propertyCheckerService.TypeHasProperties <UserProfileDto>(fields))
                {
                    return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, "Wrong fields entered"));
                }

                var existingUserProfile = await this.dataService
                                          .UserProfiles
                                          .FindByCondition(u => u.UserId == userId);

                if (existingUserProfile == null)
                {
                    return(GenericResponseBuilder.Success <IDictionary <string, object> >(null));
                }

                var userProfileToReturn = this.mapper.Map <UserProfileDto>(existingUserProfile)
                                          .ShapeData(fields)
                                          as IDictionary <string, object>;

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);
                if (includeLinks)
                {
                    var links = CreateLinksForUserProfiles(userId);
                    userProfileToReturn.Add("links", links);
                }
                return(GenericResponseBuilder.Success <IDictionary <string, object> >(userProfileToReturn));
            }
            catch (Exception ex)
            {
                //ToDo Log Error
                return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, $"{ex.Message} InnerException: {ex.InnerException.Message}"));
            }
        }
Esempio n. 18
0
        public async Task <GenericResponse <ApplicationClientDto> > CreateApplicationClient(Guid id, ApplicationClient applicationClient)
        {
            try
            {
                CreateClientSecret(applicationClient);
                applicationClient.Id = id;

                this.dataService.ApplicationClients.Create(applicationClient);
                await this.dataService.CompleteAsync();

                var clientToReturn = this.mapper.Map <ApplicationClientDto>(applicationClient);
                return(GenericResponseBuilder.Success <ApplicationClientDto>(clientToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - CreateApplicationClient. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <ApplicationClientDto>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <UserProfileDto> > AddNewUserProfile(Guid userId, UserProfileForCreationDto userProfileForCreation)
        {
            try
            {
                var userProfileEntity = this.mapper.Map <UserProfile>(userProfileForCreation);
                userProfileEntity.UserId = userId;

                this.dataService.UserProfiles.Create(userProfileEntity);
                await this.dataService.CompleteAsync();

                var userToReturn = this.mapper.Map <UserProfileDto>(userProfileEntity);
                return(GenericResponseBuilder.Success <UserProfileDto>(userToReturn));
            }
            catch (Exception ex)
            {
                //ToDo Log Error
                return(GenericResponseBuilder.NoSuccess <UserProfileDto>(null, $"{ex.Message} InnerException: {ex.InnerException.Message}"));
            }
        }
        public async Task <GenericResponse <AuthenticationDto> > AuthenticateUser(HttpRequest request)
        {
            try
            {
                if (request.Headers["grant_type"].ToString().ToLower() != "refresh_token")
                {
                    return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, "Wrong grant type"));
                }

                var isValidClient = await this.authenticationProvider.ValidateApplicationClientAsync(request);

                if (!isValidClient.IsSuccessful)
                {
                    return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, isValidClient.ResponseMessage));
                }

                var refreshTokenFromHeader = request.Headers["refresh_token"].ToString();
                var isValidRefreshToken    = await this.refreshTokenProvider.ValidateRefreshToken(isValidClient.Result, refreshTokenFromHeader);

                if (!isValidRefreshToken.IsSuccessful)
                {
                    return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, isValidRefreshToken.ResponseMessage));
                }

                var isAuthorize = await this.authenticationProvider.ValidateUserAsync(isValidRefreshToken.Result.UserId);

                if (!isAuthorize.IsSuccessful)
                {
                    return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, isAuthorize.ResponseMessage));
                }

                AuthenticationDto authentificationDto = await CreateAuthentificationDto(isValidClient, isAuthorize);

                return(GenericResponseBuilder.Success <AuthenticationDto>(authentificationDto));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - AuthenticateUser. {0}. {0}. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <UserProfile> > GetUserProfile(Guid userId)
        {
            try
            {
                var existingUserProfile = await this.dataService
                                          .UserProfiles
                                          .FindByCondition(u => u.UserId == userId);

                if (existingUserProfile == null)
                {
                    return(GenericResponseBuilder.Success <UserProfile>(null));
                }

                return(GenericResponseBuilder.Success <UserProfile>(existingUserProfile));
            }
            catch (Exception ex)
            {
                //ToDo Log Error
                return(GenericResponseBuilder.NoSuccess <UserProfile>(null, $"{ex.Message} InnerException: {ex.InnerException.Message}"));
            }
        }
Esempio n. 22
0
        public async Task <GenericResponse> DeleteApplicationClient(Guid id)
        {
            try
            {
                var clientToDelete = await this.dataService.ApplicationClients.FindByIdAsync(id);

                if (clientToDelete == null)
                {
                    return(GenericResponseBuilder.Success());
                }

                this.dataService.ApplicationClients.Delete(clientToDelete);
                await this.dataService.CompleteAsync();

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - DeleteApplicationClient. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess(ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <UserDto> > ManageUserRoles(Guid id, List <RoleForManipulationDto> roles, bool remove = false)
        {
            try
            {
                var user = await this.dataService.UserManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return(GenericResponseBuilder.Success <UserDto>(null));
                }

                var currentUserRoles = await this.dataService.UserManager.GetRolesAsync(user);

                foreach (var role in roles)
                {
                    if (currentUserRoles.Any(r => r.Equals(role.Name, StringComparison.OrdinalIgnoreCase)) & remove)
                    {
                        await this.dataService.UserManager.RemoveFromRoleAsync(user, role.Name);
                    }
                    else if (!currentUserRoles.Any(r => r.Equals(role.Name, StringComparison.OrdinalIgnoreCase)) & !remove)
                    {
                        var roleEntity = await this.dataService.RoleManager.FindByNameAsync(role.Name);

                        if (roleEntity == null)
                        {
                            roleEntity = this.mapper.Map <IdentityRole>(role);
                            await this.dataService.RoleManager.CreateAsync(roleEntity);
                        }
                        await this.dataService.UserManager.AddToRoleAsync(user, role.Name);
                    }
                }
                return(GenericResponseBuilder.Success <UserDto>(this.mapper.Map <UserDto>(user)));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - ManageUserRoles. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <UserDto>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> CreateRole(RoleForManipulationDto role, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess("Wrong media type"));
                }
                var roleEntity = this.mapper.Map <IdentityRole>(role);
                var result     = await this.dataService.RoleManager.CreateAsync(roleEntity);

                if (!result.Succeeded)
                {
                    return(GenericResponseBuilder.NoSuccess <IdentityResult>(result));
                }

                var roleToReturn = this.mapper.Map <RoleDto>(roleEntity)
                                   .ShapeData()
                                   as IDictionary <string, object>;;

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);

                if (includeLinks)
                {
                    var links = CreateLinksForRole(Guid.Parse(roleEntity.Id));
                    roleToReturn.Add("links", links);
                }

                return(GenericResponseBuilder.Success <IDictionary <string, object> >(roleToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - CreateRole. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IDictionary <string, object> >(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> AddNewUser(UserForRegistrationDto user)
        {
            try
            {
                var identityUser   = this.mapper.Map <ApplicationUser>(user);
                var identityResult = await this.dataService.UserManager.CreateAsync(identityUser, user.Password);

                if (identityResult.Succeeded)
                {
                    await AddInitialClaim(identityUser, user.UserType);

                    var token = await dataService.UserManager.GenerateEmailConfirmationTokenAsync(identityUser);

                    var configKey         = "UIPageAddresses:ConfirmUserFormPageAddress";
                    var emailObject       = GenerateEmailLink(identityUser, configKey, token, "id");
                    var registrationEmail = this.mapper.Map <RegistrationEmail>(emailObject);
                    var emailSent         = await this.emailProvider.SendRegistrationEmail(registrationEmail);

                    var userToReturn = this.mapper.Map <UserRegistrationReturnDto>(identityUser);
                    if (!emailSent)
                    {
                        userToReturn.EmailSentDuringRegistration = false;
                    }

                    var successResponse = GenericResponseBuilder.Success <UserDto>(userToReturn);
                    return(successResponse);
                }

                var failResponse = GenericResponseBuilder.NoSuccess <IdentityResult>(identityResult);
                return(failResponse);
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - AddNewUser. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <IdentityResult>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse <AuthenticationDto> > AuthenticateUser(UserForAuthenticationDto user, HttpRequest request)
        {
            try
            {
                if (request.Headers["grant_type"].ToString().ToLower() != "password")
                {
                    return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, "Wrong grant type"));
                }

                var isValidClient = await this.authenticationProvider.ValidateApplicationClientAsync(request);

                if (!isValidClient.IsSuccessful)
                {
                    return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, isValidClient.ResponseMessage));
                }

                var isAuthorize = await this.authenticationProvider.ValidateUserAuthenticationAsync(user);

                if (!isAuthorize.IsSuccessful)
                {
                    return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, isAuthorize.ResponseMessage));
                }

                var userClaims = await this.dataService.UserManager.GetClaimsAsync(isAuthorize.Result);

                var userRoles = await this.dataService.UserManager.GetRolesAsync(isAuthorize.Result);

                AuthenticationDto authentificationDto = await CreateAuthentificationDto(isValidClient, isAuthorize);

                return(GenericResponseBuilder.Success <AuthenticationDto>(authentificationDto));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - AuthenticateUser. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <AuthenticationDto>(null, ex.Message.ToString()));
            }
        }
        public async Task <GenericResponse> DeleteUserProfileClient(Guid userId)
        {
            try
            {
                var existingUserProfile = await this.dataService
                                          .UserProfiles
                                          .FindByCondition(u => u.UserId == userId);

                if (existingUserProfile == null)
                {
                    return(GenericResponseBuilder.Success());
                }

                this.dataService.UserProfiles.Delete(existingUserProfile);
                await this.dataService.CompleteAsync();

                return(GenericResponseBuilder.Success());
            }
            catch (Exception ex)
            {
                // ToDo Log Error
                return(GenericResponseBuilder.NoSuccess($"{ex.Message} InnerException: {ex.InnerException.Message}"));
            }
        }
Esempio n. 28
0
        public async Task <GenericResponse <ShapedDataWithLinks> > GetApplicationClients(ApplicationClientResourceParameter resourceParameter, string mediaType)
        {
            try
            {
                if (!MediaTypeHeaderValue.TryParse(mediaType,
                                                   out MediaTypeHeaderValue parsedMediaType))
                {
                    return(GenericResponseBuilder.NoSuccess <ShapedDataWithLinks>(null, "Wrong media type"));
                }
                if (!propertyMappingService.ValidMappingExistsFor <ApplicationClientDto, ApplicationClient>(resourceParameter.OrderBy))
                {
                    return(GenericResponseBuilder.NoSuccess <ShapedDataWithLinks>(null, "Wrong OrderBy entered"));
                }
                if (!propertyCheckerService.TypeHasProperties <ApplicationClientDto>(resourceParameter.Fields, true))
                {
                    return(GenericResponseBuilder.NoSuccess <ShapedDataWithLinks>(null, "Wrong fields entered"));
                }

                var applicationClients = await this.dataService.ApplicationClients.FindAllAsync(resourceParameter);

                if (applicationClients.Count == 0)
                {
                    return(GenericResponseBuilder.Success <ShapedDataWithLinks>(null));
                }

                var paginationMetaData = new PaginationMetaData()
                {
                    TotalCount  = applicationClients.TotalCount,
                    PageSize    = applicationClients.PageSize,
                    CurrentPage = applicationClients.CurrentPage,
                    TotalPages  = applicationClients.TotalPages
                };

                var links = CreateLinksForApplicationClients(resourceParameter, applicationClients.HasNext, applicationClients.HasPrevious);

                var shapedClientsToReturn = this.mapper
                                            .Map <IEnumerable <ApplicationClientDto> >(applicationClients)
                                            .ShapeData(resourceParameter.Fields);

                var includeLinks = parsedMediaType.SubTypeWithoutSuffix
                                   .EndsWith("hateoas", StringComparison.InvariantCultureIgnoreCase);
                var shapedClientsToReturnWithLinks = shapedClientsToReturn.Select(client =>
                {
                    var userAsDictionary = client as IDictionary <string, object>;
                    if (includeLinks)
                    {
                        var userLinks = CreateLinksForApplicationClient((Guid)userAsDictionary["Id"], resourceParameter.Fields);
                        userAsDictionary.Add("links", userLinks);
                    }
                    return(userAsDictionary);
                });

                var applicationClientsToReturn = new ShapedDataWithLinks()
                {
                    Value = shapedClientsToReturnWithLinks,
                    Links = links,
                    PaginationMetaData = paginationMetaData
                };

                return(GenericResponseBuilder.Success <ShapedDataWithLinks>(applicationClientsToReturn));
            }
            catch (Exception ex)
            {
                logger.LogError(string.Format("Error in BLL - GetApplicationClients. {0}", ex.Message));
                return(GenericResponseBuilder.NoSuccess <ShapedDataWithLinks>(null, ex.Message.ToString()));
            }
        }