public async Task Handle(AddSampleUsers busCommand)
        {
            // Create some fake user data
            var users = Enumerable.Range(0, busCommand.NumberOfUsers).Select(idx =>
            {
                var user = new CreateUser
                {
                    UserId    = Guid.NewGuid(),
                    FirstName = Name.GetFirstName(),
                    LastName  = Name.GetLastName(),
                    Password  = PasswordPattern.Bothify()
                };
                user.EmailAddress = string.Format("{0}[email protected]", Internet.GetUserName(user.FirstName, user.LastName));
                return(user);
            }).ToArray();

            // Get statement for recording sample users
            PreparedStatement prepared = await _statementCache.NoContext.GetOrAddAsync("INSERT INTO sample_data_users (userid) VALUES (?)");

            // Add the user and record their Id in C* (not a big deal if we fail halfway through since this is sample data)
            foreach (CreateUser user in users)
            {
                await _userManagement.CreateUser(user).ConfigureAwait(false);

                BoundStatement bound = prepared.Bind(user.UserId);
                await _session.ExecuteAsync(bound).ConfigureAwait(false);
            }
        }
Ejemplo n.º 2
0
        public IActionResult CreateUser([FromBody] CreateUserDto createUserDto)
        {
            //Validate Model
            if (!ModelState.IsValid)
            {
                Response.StatusCode = StatusCodes.Status412PreconditionFailed;
                return(Json(ModelState));
            }

            //Check if user allready exits
            var allreadyExists = userRepositoryService.LoginOrEmailIsAllreadyInUser(createUserDto.UserName, createUserDto.Email);

            if (allreadyExists)
            {
                Response.StatusCode = StatusCodes.Status409Conflict;
                return(Json("User name or email is allready in use."));
            }

            //Prepare user creation model
            var userCreationResult = userManagementService.CreateUser(createUserDto);

            if (userCreationResult.User == null)
            {
                Response.StatusCode = StatusCodes.Status400BadRequest;
                return(Json(userCreationResult.Errors));
            }

            //add user to db
            userRepositoryService.Insert(userCreationResult.User);
            unitOfWork.Save();

            return(StatusCode(201));
        }
Ejemplo n.º 3
0
        private Task PopulateData(IUserManagementService service)
        {
            Console.WriteLine("Quantity:");
            var quantityString = Console.ReadLine();

            if (!int.TryParse(quantityString, out int quantity))
            {
                return(Task.CompletedTask);
            }

            var rand = new Random();

            Parallel.ForEach(
                source: Enumerable.Range(0, quantity),
                parallelOptions: new ParallelOptions {
                MaxDegreeOfParallelism = 10
            },
                body: async index =>
            {
                var user = await service.CreateUser("A", "1", 18);
                await service.ChangeUserFirstName(user.Id, "B");
                await service.ChangeUserFirstName(user.Id, "User");
                await service.ChangeUserLastName(user.Id, "2");
                await service.ChangeUserLastName(user.Id, index.ToString());
                await service.ChangeUserAge(user.Id, 20);
                await service.ChangeUserAge(user.Id, rand.Next(20, 50));

                Console.WriteLine($"{index} user was populated.");
            }
                );

            return(Task.CompletedTask);
        }
Ejemplo n.º 4
0
        public async Task <JsonNetResult> RegisterUser(RegisterUserViewModel model)
        {
            if (ModelState.IsValid == false)
            {
                return(JsonFailure());
            }

            // Generate a user Id and try to register the user account (map from view model first)
            Guid userId     = Guid.NewGuid();
            var  createUser = new CreateUser
            {
                EmailAddress = model.EmailAddress,
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                Password     = model.Password,
                UserId       = userId
            };

            // TODO: Validation to try and minimize chance of duplicate users
            // if (await _userWriteModel.CreateUser(createUser) == false)
            // {
            //    ModelState.AddModelError(string.Empty, "A user with that email address already exists.");
            //    return JsonFailure();
            //}

            await _userManagement.CreateUser(createUser);

            // Assume creation successful so sign the user in
            SignTheUserIn(userId);

            // Return success
            return(JsonSuccess(new UserRegisteredViewModel {
                UserId = userId
            }));
        }
Ejemplo n.º 5
0
        public async Task <ActionResult <UserDto> > Register(RegisterDto registerData)
        {
            var user = await _userManagementService.CreateUser(registerData);

            if (user == null)
            {
                return(BadRequest("This username is already taken"));
            }
            return(Ok(user));
        }
Ejemplo n.º 6
0
        private async Task CreateCommand(IUserManagementService service)
        {
            Console.WriteLine("First Name:");
            var firstName = Console.ReadLine();

            Console.WriteLine("Last Name:");
            var lastName = Console.ReadLine();

            Console.WriteLine("Age:");
            var age = int.Parse(Console.ReadLine());

            var a = await service.CreateUser(firstName, lastName, age);

            Console.WriteLine($"Created {JsonConvert.SerializeObject(a)}");
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> CreateUser([FromBody] User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var added = await _userManagementService.CreateUser(user);

            if (added)
            {
                return(Ok("User created"));
            }
            else
            {
                return(Conflict("User already existing"));
            }
        }
Ejemplo n.º 8
0
        public IHttpActionResult Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = new UserDetail()
            {
                UserName = model.Email, Email = model.Email
            };

            var result = userManagementService.CreateUser(user, model.Password);

            if (result.HasError)
            {
                return(GetErrorResult(result));
            }

            return(Ok());
        }
        public HttpResponseMessage CreateUser(CreateUserRequest request)
        {
            HttpResponseMessage hrm;

            try
            {
                var operationResult = userManagement.CreateUser(request.Email, request.Password);
                if (operationResult.IsSuccess)
                {
                    hrm = Request.CreateResponse(HttpStatusCode.OK, operationResult.Message);
                }
                else
                {
                    hrm = Request.CreateErrorResponse(HttpStatusCode.BadRequest, operationResult.Message);
                }
            }
            catch (Exception e)
            {
                hrm = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
            return(hrm);
        }
Ejemplo n.º 10
0
        public async Task <ApiResponse> Register([FromBody] RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                throw new ApiException(ModelState.AllErrors());
            }

            var      idGenerator = new IdGenerator(IdGeneratorType.User);
            AuthUser user        = new(model.Email, model.FirstName, model.LastName,
                                       new AppUserId(idGenerator.CreateId()));

            var result = await _userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                throw new ApiException(result.Errors);
            }

            var addUser = new AddUserDto(user.AppUserId,
                                         user.FirstName,
                                         user.LastName,
                                         user.Email);

            try
            {
                await _userManagementService.CreateUser(addUser);

                return(new ApiResponse("Successfully registered", StatusCodes.Status201Created));
            }
            catch (Exception ex)
            {
                await _userManager.DeleteAsync(user);

                throw new ApiException(ex);
            }
        }
Ejemplo n.º 11
0
        public ClientRegistrationResponse Post([FromBody] ClientRegistrationRequest request)
        {
            try
            {
                _logger.Info("register new client: ");
                _logger.Info(JsonConvert.SerializeObject(request, Formatting.Indented));

                var loginName = $"{request.FirstName[0].ToString().ToLowerInvariant()}.{request.LastName.ToLowerInvariant()}";

                var clientId = _userService.CreateClient(new RegisteredClient
                {
                    Country      = request.Country,
                    State        = RegisteredClientState.Pending,
                    CreationUser = loginName,
                    CreationDate = DateTime.Now,
                });

                var workContext = new WorkContext {
                    UserId = Guid.Empty, LoginName = loginName
                };

                var user = _userService.CreateUser(workContext, new User
                {
                    RegisteredClientId = clientId,
                    LoginName          = loginName,
                    FirstName          = request.FirstName,
                    LastName           = request.LastName,
                    Email                   = request.Email,
                    EmailIsValidated        = false,
                    Password                = request.EncryptedPassword,
                    PasswordLastChangedDate = DateTime.Now,
                    IsActive                = true,
                });

                var mailServerConfig = new MailServerConfiguration
                {
                    Hostname  = "smtp.gmail.com",
                    Port      = 587,
                    Username  = "******",
                    Password  = "******",
                    From      = "*****@*****.**",
                    EnableSsl = true,
                    IsActive  = true
                };

                var renderedMessage = _mailService.RenderMailContent("0000000000", "AppSolutions", "NewClientRegistrationUserMailAddressValidation", "EN", new
                {
                    FirstName        = request.FirstName,
                    LastName         = request.LastName,
                    MailAddress      = request.Email,
                    VerificationLink = $"http://localhost:29328/User/EmailVerification/{clientId}/{user.UserId}"
                });

                var message = new MailMessage
                {
                    From = new MailAddress {
                        Address = mailServerConfig.From
                    },
                    To = new List <MailAddress> {
                        new MailAddress {
                            Address = request.Email
                        }
                    },
                    IsBodyHtml = renderedMessage.IsBodyHtml,
                    Subject    = renderedMessage.Subject,
                    Body       = renderedMessage.Body,
                };

                _mailService.SendMail(mailServerConfig, message);

                return(ClientRegistrationResponse.Success(clientId, request.Email));
            }
            catch (Exception e)
            {
                _logger.Error(e);
                return(ClientRegistrationResponse.Error(e));
            }
        }
Ejemplo n.º 12
0
        public async Task Register(CreateUserRequest request)
        {
            request.Password = _sha512Service.GetBase64Hash(request.Password);

            await _userManagementService.CreateUser(request);;
        }
Ejemplo n.º 13
0
        public ResponseDTO <Session> SsoLogin(SsoUserRequestDTO request)
        {
            ResponseDTO <Session> response = new ResponseDTO <Session>();

            // Before anything happens, validate that this request is coming from the known sso server
            if (!_signatureService.isValidSignature(request.GetStringToSign(), request.Signature))
            {
                response.Data  = null;
                response.Error = "My signature: " + _signatureService.Sign(request.GetStringToSign()) + " Compared to: " + request.Signature;
                _loggerService.LogError(LogConstants.FAIL_LOGIN, request.SsoUserId, "", response.Error, "");
                return(response);
            }

            // Protect against replay attacks by checking the timestamp
            if (DateTimeOffset.Now.AddSeconds(5).ToUnixTimeMilliseconds() < request.Timestamp)
            {
                response.Data  = null;
                response.Error = ErrorStrings.OLD_SSO_REQUEST;
                _loggerService.LogError(LogConstants.FAIL_LOGIN, request.SsoUserId, "", response.Error, "");
                return(response);
            }

            // Convert request SsoId into Guid
            Guid ssoId = new Guid(request.SsoUserId);

            // Search for user in database
            ResponseDTO <UserAccountDTO> userAccountResponse = _userManagementService.GetUserBySsoId(ssoId);
            UserAccountDTO userDTO = userAccountResponse.Data;

            // If the user does not exist in the data store, register the user as a standard user
            if (userAccountResponse.Data == null)
            {
                // Verify the email is not null
                if (request.Email == null)
                {
                    response.Data  = null;
                    response.Error = "User email may not be null.";
                    _loggerService.LogError(LogConstants.FAIL_LOGIN, request.SsoUserId, "", response.Error, "");
                    return(response);
                }

                // Create an unassigned user account
                UserAccount user = new UserAccount()
                {
                    SsoId       = ssoId,
                    Username    = request.Email,
                    IsActive    = true,
                    AcceptedTOS = false,
                    RoleType    = Roles.UNASSIGNED
                };
                List <Claim> newClaims = _claimService.GetUserClaims(Roles.UNASSIGNED, request.Email).Data;

                // Add user to datastore
                ResponseDTO <bool> createUserResponse = _userManagementService.CreateUser(user, newClaims);

                // Check if user creation succeded
                if (!createUserResponse.Data)
                {
                    response.Data  = null;
                    response.Error = createUserResponse.Error;
                    _loggerService.LogError(LogConstants.FAIL_LOGIN, request.SsoUserId, "", response.Error, "");
                    return(response);
                }

                // User now exists in database, proceed with login as normal
                userDTO = new UserAccountDTO(user);
            }

            // Create session for user
            ResponseDTO <Session> sessionResponseDTO = _sessionService.CreateSession(userDTO.Id);

            _loggerService.LogAction(LogConstants.ACTION_LOGIN, userDTO.SsoId.ToString(), sessionResponseDTO.Data.SessionId.ToString());

            return(sessionResponseDTO);
        }
Ejemplo n.º 14
0
        public UserCreationResponse CreateUser(User user, bool sendEmail, string language)
        {
            var requestContext = OperationContext.Current.Extensions.Find <ConnectionContext>();

            return(_userManagementService.CreateUser(user, sendEmail, language, requestContext.CustomerId));
        }