public RegistrationResponseDto RegisterUser(RegistrationRequestDto registrationRequestDto)
        {
            RegistrationResponseDto registrationResponseDto;

            try
            {
                registrationResponseDto = businessAuthentication.RegisterUser(registrationRequestDto);
                registrationResponseDto.ServiceResponseStatus = 1;
            }
            catch (SSException applicationException)
            {
                registrationResponseDto = new RegistrationResponseDto
                {
                    ServiceResponseStatus = 0,
                    ErrorMessage          = applicationException.Message,
                    ErrorCode             = applicationException.ExceptionCode
                };
            }
            catch (Exception exception)
            {
                registrationResponseDto = new RegistrationResponseDto
                {
                    ServiceResponseStatus = 0,
                    ErrorCode             = ExceptionAttributes.ExceptionCodes.InternalServerError,
                    ErrorMessage          = exception.Message
                };
            }


            return(registrationResponseDto);
        }
Exemplo n.º 2
0
        public async Task <RegistrationResultModel> RegisterAsync(RegistrationRequestDto model)
        {
            var cmRequest = _mapper.Map <RegistrationRequestModel>(model);

            var result = await _customerManagementServiceClient.CustomersApi.RegisterAsync(cmRequest);

            return(_mapper.Map <RegistrationResultModel>(result));
        }
        public async Task <RegistrationResultModel> SocialRegisterAsync(RegistrationRequestDto request, LoginProvider loginProvider)
        {
            var isEmailAllowed = _emailRestrictionsService.IsEmailAllowed(request.Email);

            if (!isEmailAllowed)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.EmailIsNotAllowed
                }
            }
            ;

            var(profileExists, errorResult) = await CheckIfProfileExists(request.Email);

            if (profileExists)
            {
                return new RegistrationResultModel {
                           Error = errorResult
                }
            }
            ;

            var customerId = Guid.NewGuid().ToString();
            var customerProfileLoginProvider = (CPLoginProvider)loginProvider;

            var customerProfileResult = await CreateCustomerProfileAsync(request, customerId, customerProfileLoginProvider);

            if (customerProfileResult == CustomerProfileErrorCodes.InvalidCountryOfNationalityId)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.InvalidCountryOfNationalityId
                }
            }
            ;

            if (customerProfileResult == CustomerProfileErrorCodes.CustomerProfileAlreadyExistsWithDifferentProvider ||
                customerProfileResult == CustomerProfileErrorCodes.CustomerProfileAlreadyExists)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.AlreadyRegistered
                }
            }
            ;

            await CreateCustomerWallet(customerId);

            if (!string.IsNullOrEmpty(request.ReferralCode))
            {
                await _customersRegistrationReferralDataRepository.AddAsync(customerId, request.ReferralCode);
            }

            _log.Info(message: "Successfully social registered customer", context: customerId);

            return(new RegistrationResultModel {
                CustomerId = customerId
            });
        }
 private RequestDto MapFromDatabaseDto(RegistrationRequestDto dto)
 {
     return(new RequestDto
     {
         Id = dto.Id,
         Login = dto.Login,
         Password = dto.Password,
         TTL = TimeSpan.FromSeconds(dto.TTLSeconds)
     });
 }
Exemplo n.º 5
0
        public async Task <ActionResult <RegistrationResponseDto> > Register(RegistrationRequestDto requestDto)
        {
            _logger.LogInformation($"{nameof(AccountController)}: {nameof(Register)} was called.");

            var request = _mapper.Map <RegistrationRequest>(requestDto);

            var response = await _authenticationService.RegisterAsync(request);

            return(Ok(_mapper.Map <RegistrationResponseDto>(response)));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> RegisterUserAsync([FromBody] RegistrationRequestDto dto)
        {
            Logger.LogInformation($"{nameof(RegisterUserAsync)}, dto:{dto.ToJson()}");
            var userToRegister = new User(
                dto.Email,
                dto.Firstname,
                dto.Lastname
                );

            await _userManager.RegisterAsync(userToRegister, dto.Password);

            return(Ok());
        }
 private Task <CustomerProfileErrorCodes> CreateCustomerProfileAsync(RegistrationRequestDto requestDto, string customerId, CPLoginProvider loginProvider)
 {
     return(_customerProfileClient.CustomerProfiles.CreateIfNotExistAsync(
                new CustomerProfileRequestModel
     {
         CustomerId = customerId,
         Email = requestDto.Email,
         LoginProvider = loginProvider,
         FirstName = requestDto.FirstName,
         LastName = requestDto.LastName,
         CountryOfNationalityId = requestDto.CountryOfNationalityId,
     }));
 }
 private async Task TrySaveAsync(RegistrationRequestDto dto)
 {
     try
     {
         dbContext.RegistrationRequests.Add(dto);
         await dbContext.SaveChangesAsync();
     }
     catch (DbUpdateException e)
     {
         e.ThrowIfDublicateEntry(new RequestException($"Attempt to save dublicate of registration request for login {dto.Login}"));
         throw;
     }
 }
Exemplo n.º 9
0
        private async Task SendAdminCreatedNotification(RegistrationRequestDto model, string adminId, string emailVerificationCode, IReadOnlyList <Permission> permissions)
        {
            var adminCreatedDto = new AdminCreatedEmailDto
            {
                AdminUserId           = adminId,
                Email                 = model.Email,
                EmailVerificationCode = emailVerificationCode.ToBase64(),
                Password              = model.Password,
                Name         = $"{model.FirstName} {model.LastName}",
                Localization = model.Localization
            };

            await _notificationsService.NotifyAdminCreatedAsync(adminCreatedDto);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Registrate([FromBody] RegistrationRequestDto registrationRequest)
        {
            bool isSuccessfulRegistration = await _accountService.RegistrateAsync(registrationRequest);

            if (!isSuccessfulRegistration)
            {
                return(null);
            }

            await _unitOfWork.CommitAsync();

            UserTokenDto userToken = await _accountService.Auth(registrationRequest.Login, registrationRequest.Password);

            await _unitOfWork.CommitAsync();

            return(Ok(userToken));
        }
        public RegistrationResponseDto Register(RegistrationRequestDto request)
        {
            if (_uow.Users.GetAll().Where(x => x.Username == request.EmailAddress).FirstOrDefault() == null)
            {
                User user = new User()
                {
                    Firstname = request.Firstname,
                    Lastname  = request.Lastname,
                    Email     = request.EmailAddress,
                    Username  = request.EmailAddress,
                    Password  = _encryptionService.TransformPassword(request.Password)
                };
                _uow.Users.Add(user);
                _uow.SaveChanges();
            }

            return(new RegistrationResponseDto());
        }
Exemplo n.º 12
0
        public async Task <bool> RegistrateAsync(RegistrationRequestDto registrationRequest)
        {
            var user = await _userRepository.GetAsync(registrationRequest.Login);

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

            user = new User(
                registrationRequest.FirstName,
                registrationRequest.LastName,
                registrationRequest.Login,
                registrationRequest.Email,
                registrationRequest.Password
                );
            _userRepository.Add(user);

            return(true);
        }
        public RegistrationResponseDto RegisterUser(RegistrationRequestDto registrationRequestDto)
        {
            RegistrationResponseDto registrationResponseDto = new RegistrationResponseDto();
            var keyNew   = Helper.GeneratePassword(25);
            var password = Helper.EncodePassword(registrationRequestDto.UserPassword, keyNew);
            var cModel   = new RegistrationCM
            {
                UserId       = Guid.NewGuid(),
                LoginName    = registrationRequestDto.LoginName,
                UserPassword = password,
                Email        = registrationRequestDto.Email,
                PhoneNumber  = registrationRequestDto.PhoneNumber,
                PasswordSalt = keyNew,
                IsActive     = true,
                FirstName    = registrationRequestDto.FirstName,
                LastName     = registrationRequestDto.LastName,
                RoleId       = registrationRequestDto.RoleId
            };

            var response = authenticationRepository.UserRegistration(cModel);

            registrationResponseDto.RegisteredUserId = response.RegisteredUserId;
            return(registrationResponseDto);
        }
 public IHttpActionResult Register(RegistrationRequestDto request)
 {
     return(Ok(_userService.Register(request)));
 }
Exemplo n.º 15
0
 public TokenDto TryToRegister(RegistrationRequestDto registrationRequestDto)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 16
0
 public async Task <IActionResult> Register([FromBody] RegistrationRequestDto dto)
 {
     return(null);
 }
        public async Task <RegistrationResultModel> RegisterAsync(RegistrationRequestDto request)
        {
            var isEmailAllowed = _emailRestrictionsService.IsEmailAllowed(request.Email);

            if (!isEmailAllowed)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.EmailIsNotAllowed
                }
            }
            ;

            var(profileExists, errorResult) = await CheckIfProfileExists(request.Email);

            if (profileExists)
            {
                return new RegistrationResultModel {
                           Error = errorResult
                }
            }
            ;

            var customerId = Guid.NewGuid().ToString();

            CredentialsCreateResponse credentialsCreateResult;

            try
            {
                credentialsCreateResult = await _credentialsClient.Api.CreateAsync(new CredentialsCreateRequest
                {
                    Login      = request.Email,
                    CustomerId = customerId,
                    Password   = request.Password
                });
            }
            catch (ClientApiException e) when(e.HttpStatusCode == HttpStatusCode.BadRequest)
            {
                return(new RegistrationResultModel
                {
                    Error = e.ErrorResponse.ModelErrors.First().Key == nameof(CredentialsCreateRequest.Password)
                        ? ServicesError.InvalidPasswordFormat
                        : ServicesError.InvalidLoginFormat
                });
            }

            if (credentialsCreateResult.Error == CredentialsError.LoginAlreadyExists)
            {
                return(await CheckUnfinishedCreationAsync(request));
            }

            if (credentialsCreateResult.Error != CredentialsError.None)
            {
                var exc = new InvalidOperationException(
                    $"Unexpected error during credentials creation for {request.Email.SanitizeEmail()}");
                _log.Error(exc, context: credentialsCreateResult.Error);
                throw exc;
            }

            var customerProfileResult = await CreateCustomerProfileAsync(request, customerId, CPLoginProvider.Standard);

            if (customerProfileResult == CustomerProfileErrorCodes.InvalidCountryOfNationalityId)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.InvalidCountryOfNationalityId
                }
            }
            ;

            if (customerProfileResult == CustomerProfileErrorCodes.CustomerProfileAlreadyExistsWithDifferentProvider ||
                customerProfileResult == CustomerProfileErrorCodes.CustomerProfileAlreadyExists)
            {
                //We should remove credentials in this case because on the first check there was not existing profile
                //so we created credentials but then profile with another provider was created before creating it with Standard
                await _credentialsClient.Api.RemoveAsync(request.Email);

                return(new RegistrationResultModel
                {
                    Error = customerProfileResult == CustomerProfileErrorCodes.CustomerProfileAlreadyExistsWithDifferentProvider
                        ? ServicesError.AlreadyRegisteredWithGoogle
                        : ServicesError.AlreadyRegistered
                });
            }

            await CreateCustomerWallet(customerId);

            if (!string.IsNullOrEmpty(request.ReferralCode))
            {
                await _customersRegistrationReferralDataRepository.AddAsync(customerId, request.ReferralCode);
            }

            _log.Info(message: "Successfully registered customer", context: customerId);

            return(new RegistrationResultModel {
                CustomerId = customerId
            });
        }
Exemplo n.º 18
0
 public IHttpActionResult Register(RegistrationRequestDto dto)
 {
     return(Ok(identityService.TryToRegister(dto)));
 }
        private async Task <RegistrationResultModel> CheckUnfinishedCreationAsync(RegistrationRequestDto requestDto)
        {
            _log.Warning("Trying to finish unfinished registration", context: requestDto.Email.SanitizeEmail());

            var customerCreds = await _credentialsClient.Api.ValidateCredentialsAsync(
                new CredentialsValidationRequest { Login = requestDto.Email, Password = requestDto.Password });

            if (customerCreds.CustomerId == null)
            {
                if (customerCreds.Error == CredentialsError.PasswordMismatch)
                {
                    return new RegistrationResultModel {
                               Error = ServicesError.RegisteredWithAnotherPassword
                    }
                }
                ;

                var exc = new InvalidOperationException(
                    $"Unexpected error for {requestDto.Email.SanitizeEmail()} password validation");
                _log.Error(exc, context: customerCreds.Error);
                throw exc;
            }

            var customerWallet =
                await _privateBlockchainFacadeClient.CustomersApi.GetWalletAddress(Guid.Parse(customerCreds.CustomerId));

            if (customerWallet.WalletAddress != null)
            {
                _log.Warning("Another registration attempt",
                             context: new { customerCreds.CustomerId, Login = requestDto.Email.SanitizeEmail() });
                return(new RegistrationResultModel {
                    Error = ServicesError.AlreadyRegistered
                });
            }

            var customerProfileResult = await CreateCustomerProfileAsync
                                            (requestDto, customerCreds.CustomerId, CPLoginProvider.Standard);

            if (customerProfileResult == CustomerProfileErrorCodes.InvalidCountryOfNationalityId)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.InvalidCountryOfNationalityId
                }
            }
            ;

            if (customerProfileResult == CustomerProfileErrorCodes.CustomerProfileAlreadyExistsWithDifferentProvider)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.AlreadyRegisteredWithGoogle
                }
            }
            ;

            await CreateCustomerWallet(customerCreds.CustomerId);

            if (!string.IsNullOrEmpty(requestDto.ReferralCode))
            {
                await _customersRegistrationReferralDataRepository.AddAsync(customerCreds.CustomerId, requestDto.ReferralCode);
            }

            _log.Info(message: "Successfully registered customer", context: customerCreds.CustomerId);

            return(new RegistrationResultModel {
                CustomerId = customerCreds.CustomerId
            });
        }
Exemplo n.º 20
0
        public async Task <RegistrationResultModel> RegisterAsync(RegistrationRequestDto model)
        {
            var adminId = Guid.NewGuid().ToString();

            model.Email = model.Email.ToLower();

            CredentialsCreateResponse adminCredentialsCreationResult;

            try
            {
                adminCredentialsCreationResult = await _credentialsClient.Admins.CreateAsync(
                    new AdminCredentialsCreateRequest { Login = model.Email, AdminId = adminId, Password = model.Password });
            }
            catch (ClientApiException exception) when(exception.HttpStatusCode == HttpStatusCode.BadRequest)
            {
                return(new RegistrationResultModel {
                    Error = ServicesError.InvalidEmailOrPasswordFormat
                });
            }

            if (adminCredentialsCreationResult.Error == CredentialsError.LoginAlreadyExists)
            {
                return new RegistrationResultModel {
                           Error = ServicesError.AlreadyRegistered
                }
            }
            ;

            var emailHash = GetHash(model.Email);

            if (adminCredentialsCreationResult.Error != CredentialsError.None)
            {
                const string errorMessage = "An error occurred while creating admin credentials.";

                _log.Error(errorMessage, context:
                           $"adminUserId: {adminId}; email: {emailHash}; error: {adminCredentialsCreationResult.Error}");

                throw new InvalidOperationException(errorMessage);
            }

            var registrationDateTime = DateTime.UtcNow;

            var result = await _adminUsersRepository.TryCreateAsync(
                new AdminUserEncrypted
            {
                AdminUserId           = adminId,
                EmailHash             = emailHash,
                RegisteredAt          = registrationDateTime,
                IsActive              = true,
                UseDefaultPermissions = false
            });

            if (result)
            {
                _log.Info("Admin user created for an account.", context: $"adminUserId: {adminId}; email: {emailHash}");
            }
            else
            {
                _log.Warning("Trying to create a duplicate admin user.", context: $"email: {emailHash}");

                return(new RegistrationResultModel {
                    Error = ServicesError.AlreadyRegistered
                });
            }

            var adminProfileCreationResult = await _customerProfileClient.AdminProfiles.AddAsync(
                _mapper.Map <RegistrationRequestDto, AdminProfileRequest>(model,
                                                                          opt => opt.AfterMap((src, dest) => { dest.AdminId = Guid.Parse(adminId); }))
                );

            await _permissionsService.CreateOrUpdatePermissionsAsync(adminId, model.Permissions);

            await _permissionsCache.SetAsync(adminId, model.Permissions.ToList());

            if (adminProfileCreationResult.ErrorCode != AdminProfileErrorCodes.None)
            {
                _log.Error(message: "An error occurred while creating admin profile.",
                           context: $"adminUserId: {adminId}; error: {adminProfileCreationResult.ErrorCode}");
            }

            #region email verification code

            var emailVerificationCode = Guid.NewGuid().ToString();

            var emailVerificationCodeEntity = await _emailVerificationCodeRepository.CreateOrUpdateAsync(
                adminId,
                emailVerificationCode);

            #endregion

            await _notificationsService.NotifyAdminCreatedAsync(new AdminCreatedEmailDto
            {
                AdminUserId           = adminId,
                Email                 = model.Email,
                EmailVerificationCode = emailVerificationCode.ToBase64(),
                Password              = model.Password,
                Name         = $"{model.FirstName} {model.LastName}",
                Localization = model.Localization
            });

            _log.Info(message: "Successfully generated AdminCreatedEmail", context: adminId);

            var adminUser = _mapper.Map <AdminUser>(adminProfileCreationResult.Data);
            adminUser.AdminUserId           = adminId;
            adminUser.Permissions           = model.Permissions.ToList();
            adminUser.RegisteredAt          = registrationDateTime;
            adminUser.UseDefaultPermissions = false;
            adminUser.IsActive = true;

            return(new RegistrationResultModel {
                Admin = adminUser
            });
        }