public async Task <IdentityUtilsResult <TTenantDto> > AddTenant(TTenantDto tenantDto)
        {
            tenantDto.Hostnames ??= new List <string>();

            var hostsAlreadyExist = await dbContext.TenantHosts
                                    .Where(x => tenantDto.Hostnames.Contains(x.Hostname))
                                    .AnyAsync();

            if (hostsAlreadyExist)
            {
                return(IdentityUtilsResult <TTenantDto> .ErrorResult("Hostname already assigned to different tenant"));
            }

            var tenant = mapper.Map <TTenant>(tenantDto);

            tenant.Hosts = tenantDto.Hostnames
                           .Select(x => new IdentityManagerTenantHost
            {
                Hostname = x.Trim()
            })
                           .ToList();

            var result = ModelValidator.ValidateDataAnnotations(tenant);

            if (!result.isValid)
            {
                return(IdentityUtilsResult <TTenantDto> .ErrorResult(result.ToIdentityUtilsResult().ErrorMessages));
            }

            dbContext.Tenants.Add(tenant);
            await dbContext.SaveChangesAsync();

            return(IdentityUtilsResult <TTenantDto> .SuccessResult(ToDto(tenant)));
        }
예제 #2
0
        /// <summary>
        /// Uses AutoMapper to map retrieved user to speciefied type
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <IdentityUtilsResult <TDto> > FindByIdAsync <TDto>(Guid id) where TDto : class
        {
            var user = await FindByIdAsync(id);

            return(user.Success
                ? IdentityUtilsResult <TDto> .SuccessResult(mapper.Map <TDto>(user.Data.Single()))
                : IdentityUtilsResult <TDto> .ErrorResult(user.ErrorMessages));
        }
        public virtual async Task <IdentityUtilsResult <TTenantDto> > UpdateTenant([FromRoute] Guid tenantId, [FromBody] TTenantDto tenant)
        {
            if (tenantId != tenant.TenantId)
            {
                return(IdentityUtilsResult <TTenantDto> .ErrorResult("Id specified in route and payload are not the same!"));
            }

            return(await tenantService.UpdateTenant(tenant));
        }
        public async Task <IdentityUtilsResult <TTenantDto> > GetTenant(Guid id)
        {
            var tenantResult = await GetTenantDb(id);

            var result = tenantResult.Success
                ? IdentityUtilsResult <TTenantDto> .SuccessResult(ToDto(tenantResult.Data))
                : IdentityUtilsResult <TTenantDto> .ErrorResult(tenantResult.ErrorMessages);

            return(result);
        }
예제 #5
0
        internal async static Task <IdentityUtilsResult> ParseRestResultTask(this Task <RestResult <IdentityUtilsResult> > restResultTask)
        {
            var restResult = await restResultTask;

            if (!restResult.Success)
            {
                return(IdentityUtilsResult.ErrorResult(restResult.ErrorMessages));
            }

            return(restResult.ResponseData);
        }
예제 #6
0
        public async Task <IdentityUtilsResult <TUserDto> > FindByNameAsync <TUserDto>(string name) where TUserDto : class
        {
            var userResult = await FindByNameAsync(name);

            if (!userResult.Success)
            {
                return(IdentityUtilsResult <TUserDto> .ErrorResult(userResult.ErrorMessages));
            }

            return(IdentityUtilsResult <TUserDto> .SuccessResult(mapper.Map <TUserDto>(userResult.Data.First())));
        }
예제 #7
0
        public async Task <IdentityUtilsResult <TUser> > FindByNameAsync(string name)
        {
            var user = await userManager.FindByNameAsync(name);

            if (user == null)
            {
                return(IdentityUtilsResult <TUser> .ErrorResult("User with specified name not found"));
            }

            return(IdentityUtilsResult <TUser> .SuccessResult(user));
        }
예제 #8
0
        private async Task <IdentityUtilsResult <TRole> > GetRoleById(Guid roleId)
        {
            var role = await roleManager.FindByIdAsync(roleId.ToString());

            if (role == null)
            {
                return(IdentityUtilsResult <TRole> .ErrorResult("Role with specified ID not found"));
            }

            return(IdentityUtilsResult <TRole> .SuccessResult(role));
        }
예제 #9
0
        /// <summary>
        /// Retrieves user by ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <IdentityUtilsResult <TUser> > FindByIdAsync(Guid id)
        {
            var user = await userManager.FindByIdAsync(id.ToString());

            if (user == null)
            {
                return(IdentityUtilsResult <TUser> .ErrorResult("User with specified ID not found"));
            }
            else
            {
                return(IdentityUtilsResult <TUser> .SuccessResult(user));
            }
        }
        public async Task <IdentityUtilsResult <TTenantDto> > UpdateTenant(TTenantDto tenantDto)
        {
            using var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);

            var hostsAlreadyExist = await dbContext.TenantHosts
                                    .Where(x => x.TenantId != tenantDto.TenantId)
                                    .Where(x => tenantDto.Hostnames.Contains(x.Hostname))
                                    .AnyAsync();

            if (hostsAlreadyExist)
            {
                return(IdentityUtilsResult <TTenantDto> .ErrorResult("Hostname already assigned to different tenant"));
            }

            var currentHosts = dbContext.TenantHosts.Where(x => x.TenantId == tenantDto.TenantId);

            dbContext.TenantHosts.RemoveRange(currentHosts);
            await dbContext.SaveChangesAsync();

            var tenantDbResult = await GetTenantDb(tenantDto.TenantId, false);

            if (!tenantDbResult.Success)
            {
                return(IdentityUtilsResult <TTenantDto> .ErrorResult(tenantDbResult.ErrorMessages));
            }

            var tenant = tenantDbResult.Data.First();

            mapper.Map(tenantDto, tenant);
            var hosts = tenantDto.Hostnames
                        .Select(x => new IdentityManagerTenantHost
            {
                TenantId = tenantDto.TenantId,
                Hostname = x
            });

            var result = ModelValidator.ValidateDataAnnotations(tenant);

            if (!result.isValid)
            {
                return(IdentityUtilsResult <TTenantDto> .ErrorResult(result.ToIdentityUtilsResult().ErrorMessages));
            }

            dbContext.Tenants.Update(tenant);
            dbContext.TenantHosts.AddRange(hosts);
            await dbContext.SaveChangesAsync();

            scope.Complete();

            return(IdentityUtilsResult <TTenantDto> .SuccessResult(ToDto(tenant)));
        }
        public async Task <IdentityUtilsResult> DeleteTenant(Guid id)
        {
            var tenantDbResult = await GetTenantDb(id);

            if (!tenantDbResult.Success)
            {
                return(IdentityUtilsResult.ErrorResult(tenantDbResult.ErrorMessages));
            }

            var hostsToDelete = dbContext.TenantHosts.Where(x => x.TenantId == id);

            dbContext.TenantHosts.RemoveRange(hostsToDelete);
            dbContext.Tenants.RemoveRange(tenantDbResult.Data);
            await dbContext.SaveChangesAsync();

            return(IdentityUtilsResult.SuccessResult);
        }
        private async Task <IdentityUtilsResult <TTenant> > GetTenantDb(Guid id, bool includeHosts = true)
        {
            var     tenantQuery = dbContext.Tenants.Where(x => x.TenantId == id);
            TTenant tenant      = null;

            if (includeHosts)
            {
                tenant = await tenantQuery.Include(x => x.Hosts).FirstOrDefaultAsync();
            }
            else
            {
                tenant = await tenantQuery.FirstOrDefaultAsync();
            }

            var result = tenant == null
                ? IdentityUtilsResult <TTenant> .ErrorResult("Tenant with specified ID does not exist")
                : IdentityUtilsResult <TTenant> .SuccessResult(tenant);

            return(result);
        }
예제 #13
0
        public async Task <IdentityUtilsResult> UpdateUser(TUserDto user)
        {
            var userDbResult = await FindByIdAsync(user.Id);

            if (!userDbResult.Success)
            {
                return(IdentityUtilsResult.ErrorResult(userDbResult.ErrorMessages));
            }

            var userDb = userDbResult.Data.First();

            mapper.Map(user, userDb);

            var result = ModelValidator.ValidateDataAnnotations(userDb).ToIdentityUtilsResult();

            if (!result.Success)
            {
                return(result.ToTypedResult <TUserDto>());
            }

            var managerValidationResult = await new UserValidator <TUser>().ValidateAsync(userManager, userDb);

            if (!managerValidationResult.Succeeded)
            {
                return(managerValidationResult.ToIdentityUtilsResult().ToTypedResult <TUserDto>());
            }

            var identityResult = await userManager.UpdateAsync(userDb);

            if (!identityResult.Succeeded)
            {
                return(identityResult.ToIdentityUtilsResult());
            }

            mapper.Map(userDbResult.Data.Single(), user);
            return(IdentityUtilsResult.SuccessResult);
        }
예제 #14
0
        public virtual async Task <IdentityUtilsResult <TokenResponse> > GetToken(TokenRequest request)
        {
            var config = HttpContext.RequestServices.GetService(typeof(IIdentityUtilsAuthenticationConfig)) as IIdentityUtilsAuthenticationConfig;

            request.ClientId = config?.ClientId ?? request.ClientId;

            HttpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues>
            {
                { "client_id", request.ClientId },
                { "grant_type", request.GrantType },
                { "username", request.Username },
                { "password", request.Password },
                { "refresh_token", request.RefreshToken },
            });

            // validate client
            var client = await clientStore.FindEnabledClientByIdAsync(request.ClientId);

            var invalidClient = !client.AllowedGrantTypes.Intersect(GrantTypes.ResourceOwnerPassword).Any() && !(request.GrantType == AuthenticationConstants.GrantTypeRefreshToken);

            if (client == null || invalidClient)
            {
                return(IdentityUtilsResult <TokenResponse> .ErrorResult($"Client id not found or invalid grant type"));
            }
            var clientResult = new ClientSecretValidationResult
            {
                IsError = false,
                Client  = client
            };

            var form = new NameValueCollection
            {
                { "client_id", request.ClientId },
                { "grant_type", request.GrantType },
                { "refresh_token", request.RefreshToken },
                { "username", request.Username },
                { "password", request.Password },
            };

            // validate request
            var requestResult = await requestValidator.ValidateRequestAsync(form, clientResult);

            if (requestResult.IsError)
            {
                await events.RaiseAsync(new TokenIssuedFailureEvent(requestResult));

                return(IdentityUtilsResult <TokenResponse> .ErrorResult($"{requestResult.Error} - {requestResult.ErrorDescription}"));
            }

            // create response
            var response = await responseGenerator.ProcessAsync(requestResult);

            await events.RaiseAsync(new TokenIssuedSuccessEvent(response, requestResult));

            // return result
            var tokenResponse = new TokenResponse
            {
                AccessToken  = response.AccessToken,
                RefreshToken = response.RefreshToken,
                Lifetime     = response.AccessTokenLifetime,
                Scopes       = response.Scope.Split(' ')
            };

            return(IdentityUtilsResult <TokenResponse> .SuccessResult(tokenResponse));
        }