Beispiel #1
0
 public static TRequest WithUser <TRequest>(this TRequest result, IdentityDto user)
     where TRequest : IRequest
 {
     result.User            = user;
     result.OriginatorGroup = user.Key.ToString();
     return(result);
 }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var user         = new IdentityDto().WithPrincipal(actionContext.RequestContext.Principal);
            var isAuthorized = AuthorizationService.IsAuthorized(this, user) || GetUserInfoOnly;

            if (!isAuthorized)
            {
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }
        }
        public async Task <IActionResult> LoginAsync([FromBody] IdentityDto request)
        {
            var command = Mapper.Map <LoginCommand>(request);
            var result  = await Mediator.Send(command);

            if (!string.IsNullOrEmpty(result.RefreshToken))
            {
                SetRefreshTokenInCookie(result.RefreshToken, result.RefreshTokenExpiration);
            }
            return(Ok(result));
        }
Beispiel #4
0
 public static IdentityDocument AsDocument(this IdentityDto dto, string hashedPassword)
 => new IdentityDocument
 {
     Id          = dto.Id,
     Username    = dto.Username,
     FullName    = dto.FullName,
     Email       = dto.Email,
     PhoneNumber = dto.PhoneNumber,
     Password    = hashedPassword,
     UpdatedAt   = DateTime.UtcNow
 };
        public async Task <ActionResult <ApiResponse <IdentityDto> > > ValidateIdentity(Dictionary <string, string> keyValues)
        {
            try
            {
                var isValid = await _userService.ValidateIdentity(keyValues);

                var identiy = new IdentityDto {
                    IsValid = isValid
                };
                return(identiy.CreateSuccessResponse("Customer validated successfully!"));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception.CreateErrorResponse()));
            }
        }
Beispiel #6
0
        public IActionResult CreateIdentity([FromBody] IdentityDto identity)
        {
            ulong accountId = ulong.Parse(User.Identity.Name, CultureInfo.InvariantCulture);

            StatePersistency statePersistency = _executionContextManager.ResolveStateExecutionServices(accountId);
            Account          account          = _accountsService.GetById(accountId);

            byte[] assetId = _assetsService.GenerateAssetId((AttributeType)identity.RootAttribute.AttributeType, identity.RootAttribute.Content);
            statePersistency.TransactionsService.IssueBlindedAsset(assetId, 0UL.ToByteArray(32), out byte[] originatingCommitment);
            identity.RootAttribute.OriginatingCommitment = originatingCommitment.ToHexString();

            Identity identityDb = _externalDataAccessService.CreateIdentity(accountId, identity.Description, new IdentityAttribute {
                AttributeType = AttributeType.IdCard, Content = identity.RootAttribute.Content, Subject = ClaimSubject.User, Commitment = originatingCommitment
            });

            identity.Id = identityDb.IdentityId.ToString(CultureInfo.InvariantCulture);

            string imageContent = null;

            foreach (var identityAttributeDto in identity.AssociatedAttributes)
            {
                IdentityAttribute identityAttribute = new IdentityAttribute
                {
                    AttributeType = (AttributeType)identityAttributeDto.AttributeType,
                    Content       = identityAttributeDto.Content,
                    Subject       = ClaimSubject.User
                };
                _externalDataAccessService.AddAssociatedIdentityAttribute(identityDb.IdentityId, ref identityAttribute);

                if (((AttributeType)identityAttributeDto.AttributeType) == AttributeType.PassportPhoto)
                {
                    imageContent = identityAttributeDto.Content;
                }
            }

            if (!string.IsNullOrEmpty(identity.RootAttribute.Content) && !string.IsNullOrEmpty(imageContent))
            {
                $"{Request.Scheme}://{Request.Host.ToUriComponent()}/biometric/".AppendPathSegment("RegisterPerson").PostJsonAsync(new BiometricPersonDataDto {
                    Requester = account.PublicSpendKey.ToHexString(), PersonData = identity.RootAttribute.Content, ImageString = imageContent
                });
            }

            _hubContext.Clients.Group(User.Identity.Name).SendAsync("PushIdentity", identity);

            return(Ok());
        }
Beispiel #7
0
        public async Task <IActionResult> CreateIdentity(long accountId, [FromBody] IdentityDto identity)
        {
            //StatePersistency statePersistency = _executionContextManager.ResolveStateExecutionServices(accountId);
            AccountDescriptor account = _accountsService.GetById(accountId);

            //byte[] assetId = await _assetsService.GenerateAssetId(identity.RootAttribute.SchemeName, identity.RootAttribute.Content, account.PublicSpendKey.ToHexString()).ConfigureAwait(false);
            //statePersistency.TransactionsService.IssueBlindedAsset(assetId, 0UL.ToByteArray(32), out byte[] originatingCommitment);
            //identity.RootAttribute.OriginatingCommitment = originatingCommitment.ToHexString();

            IEnumerable <(string attributeName, string content)> attrs = await GetAttribitesAndContent(identity, account).ConfigureAwait(false);

            Identity identityDb = _dataAccessService.CreateIdentity(account.AccountId, identity.Description, attrs.ToArray());

            identity.Id = identityDb.IdentityId.ToString(CultureInfo.InvariantCulture);

            return(Ok(identity.Id));
        }
Beispiel #8
0
        public virtual bool IsAuthorized(IAccessCriteria criteria, IdentityDto actualUser)
        {
            if (actualUser?.State == null || !actualUser.State.Equals(UserState.Active))
            {
                return(false);
            }

            var isAuthorized = false;

            if (actualUser.Roles == null)
            {
                return(IsAuthorized(criteria, null, actualUser.UserReference));
            }

            foreach (var role in actualUser.Roles)
            {
                if (role.RoleProcesses == null)
                {
                    isAuthorized = IsAuthorized(criteria, role.RoleType, actualUser.UserReference);
                    if (isAuthorized)
                    {
                        break;
                    }

                    continue;
                }

                foreach (var process in role.RoleProcesses)
                {
                    isAuthorized = IsAuthorized(criteria, role.RoleType, actualUser.UserReference, process.Name,
                                                process.Target, process.IsDenied);
                    if (isAuthorized)
                    {
                        break;
                    }
                }

                if (isAuthorized)
                {
                    break;
                }
            }

            return(isAuthorized);
        }
        public void AddUser_ReturnCount()
        {
            using (var transaction = _dbFixture.Connection.BeginTransaction())
            {
                var context     = _dbFixture.CreateContext(transaction);
                var userManager = TestHelpers.Identity.CreateUserManager(context);

                var shiftService = new UserService(userManager, new NullLogger <UserService>());

                var dto = new IdentityDto()
                {
                    MemberId = 15, Data = new AccountCredsData {
                        Email = "*****@*****.**", Password = "******", ConfirmPassword = "******"
                    }
                };

                var shiftResult = shiftService.RegisterUser(dto).Result;

                Assert.True(context.Users.Any(u => u.MemberId == 15));
            }
        }
Beispiel #10
0
        public virtual async Task <IdentityDto> GetUserAsync(string accessToken)
        {
            var cacheKey = OAuthHelperTypeName + nameof(IdentityDto) + accessToken;
            var user     = InProcessCache.GetCachedItem <IdentityDto>(cacheKey);

            if (user != null)
            {
                return(user);
            }

            var claims = await GetClaimsFromIdentityServiceAsync(accessToken);

            user = new IdentityDto().WithClaims(claims);

            if (user == null)
            {
                return(null);
            }

            var expiration = Settings.AccessTokenValidationResultLifeSpan ?? TimeSpan.FromSeconds(10);
            await InProcessCache.SetCachedItemAsync(cacheKey, user, expiration);

            return(user);
        }
 public async Task <IActionResult> Register([FromBody] IdentityDto dto)
 {
     return(new ObjectResult(await _userService.RegisterUser(dto)));
 }
Beispiel #12
0
        public async Task <bool> Register(MemberRegisterDto dto)
        {
            var apiClient = _httpFactory.CreateClient(Constants.HttpClients.ApiClient);

            // send request to create member
            var memberResponse = await apiClient.PostAsJsonAsync($"{Constants.ControllerNames.Teams}/{Constants.Routes.Register}", dto, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            // log error and return false if request returns bad statuscode
            if (!memberResponse.IsSuccessStatusCode)
            {
                var stringContent = await memberResponse.Content.ReadAsStringAsync();

                _logger.LogError(stringContent);
                return(false);
            }

            var memberResult = await memberResponse.Content.ReadFromJsonAsync <ApiResult <int> >(new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            // if member creation is successful, send returned member id, username and password to idp to request identity account creation
            if (memberResult.Successful)
            {
                var idpClient = _httpFactory.CreateClient(Constants.HttpClients.IdpClient);

                var identityDto = new IdentityDto {
                    MemberId = memberResult.Data, Data = dto.Account
                };

                var idpResponse = await idpClient.PostAsJsonAsync($"{Constants.ControllerNames.User}/{Constants.Routes.Register}", identityDto, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                // log error and return false if request returns bad statuscode
                if (!idpResponse.IsSuccessStatusCode)
                {
                    var stringContent = await idpResponse.Content.ReadAsStringAsync();

                    _logger.LogError(stringContent);

                    var successCodeDeleteResponse = await idpClient.PostAsJsonAsync($"{Constants.ControllerNames.Teams}/{Constants.Routes.Delete}", memberResult.Data, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                    if (!successCodeDeleteResponse.IsSuccessStatusCode)
                    {
                        stringContent = await memberResponse.Content.ReadAsStringAsync();

                        _logger.LogError(stringContent);
                        return(false);
                    }

                    return(false);
                }

                var idpResult = await idpResponse.Content.ReadFromJsonAsync <ApiResult <object> >();

                if (idpResult.Successful)
                {
                    return(true);
                }

                // log error and return false if identity account creation wasn't successful
                _logger.LogError(idpResult.Error);
                var apiResultDeleteResponse = await idpClient.PostAsJsonAsync($"{Constants.ControllerNames.Teams}/{Constants.Routes.Delete}", memberResult.Data, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

                if (!apiResultDeleteResponse.IsSuccessStatusCode)
                {
                    var stringContent = await memberResponse.Content.ReadAsStringAsync();

                    _logger.LogError(stringContent);
                    return(false);
                }

                return(false);
            }

            // log error and return false if member profile creation wasn't successful
            _logger.LogError(memberResult.Error);
            return(false);
        }
Beispiel #13
0
        private async Task <IEnumerable <(string attributeName, string content)> > GetAttribitesAndContent(IdentityDto identity, AccountDescriptor account)
        {
            IEnumerable <(string attributeName, string content)> attrs;

            IdentitiesScheme rootScheme = _dataAccessService.GetRootIdentityScheme(account.PublicSpendKey.ToHexString());

            if (rootScheme != null)
            {
                IdentityAttributeDto rootAttribute = identity.Attributes.FirstOrDefault(a => a.AttributeName == rootScheme.AttributeName);
                byte[] rootAssetId = await _assetsService.GenerateAssetId(rootScheme.AttributeSchemeName, rootAttribute.Content, account.PublicSpendKey.ToHexString()).ConfigureAwait(false);

                var protectionIdentityAttribute = identity.Attributes.FirstOrDefault(a => a.AttributeName == AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD);
                if (protectionIdentityAttribute != null)
                {
                    protectionIdentityAttribute.Content = rootAssetId.ToHexString();
                }

                attrs = identity.Attributes.Select(a => (a.AttributeName, a.Content));

                if (protectionIdentityAttribute == null)
                {
                    attrs = attrs.Append((AttributesSchemes.ATTR_SCHEME_NAME_PASSWORD, rootAssetId.ToHexString()));
                }
            }
            else
            {
                attrs = identity.Attributes.Select(a => (a.AttributeName, a.Content));
            }

            return(attrs);
        }
Beispiel #14
0
        public async Task <ApiResult <object> > RegisterUser(IdentityDto dto)
        {
            var result = new ApiResult <object>();

            if (dto != null)
            {
                // create user account
                var user = new AppUser
                {
                    Email = dto.Data.Email,
                    // TODO: Add email confirmation
                    EmailConfirmed = true,
                    UserName       = dto.Data.Email,
                    MemberId       = dto.MemberId
                };

                var identityResult = await _userManager.CreateAsync(user, dto.Data.Password);

                if (identityResult.Succeeded)
                {
                    _logger.LogInformation($"Registration: New user {dto.Data.Password} was successfully created");

                    // add member role to user
                    var roleResult = await _userManager.AddToRoleAsync(user, "Member");

                    if (roleResult.Succeeded)
                    {
                        _logger.LogInformation($"Registration: New user {dto.Data.Email} was added to member role");
                        _logger.LogInformation($"Registration complete for user {dto.Data.Email}");
                        result = new ApiResult <object>
                        {
                            Successful = true
                        };
                    }
                    else
                    {
                        _logger.LogError($"Registration Error: An error occurred when adding role to {dto.Data.Email}:");
                        result = new ApiResult <object>
                        {
                            Error      = $"Registration Error: An error occurred when adding role to {dto.Data.Email}:",
                            Successful = false
                        };
                    }
                }
                else
                {
                    _logger.LogError($"An error occured when creating new user {dto.Data.Email}:");
                    string errorString = $"An error occured when creating new user {dto.Data.Email}:\n\n";
                    foreach (var error in identityResult.Errors)
                    {
                        _logger.LogError($"{error.Code}: {error.Description}");
                        errorString += error + ".\n";
                    }
                    result = new ApiResult <object>
                    {
                        Error      = errorString,
                        Successful = false
                    };
                }
            }
            else
            {
                result = new ApiResult <object>
                {
                    Error      = "Invalid registration data",
                    Successful = false
                };
            }

            // something went wrong, return result
            return(result);
        }