Exemple #1
0
        public async Task ShouldCreateUser()
        {
            CreateUserRequestModel model = new CreateUserRequestModel()
            {
                Email = "*****@*****.**", Name = "user name", Password = "******"
            };

            _userRepositoryMock.GetByEmail(Arg.Any <string>()).Returns(null as User);
            _fileUploadUtilsMock.GetDefaultUserProfileImage().Returns(new MemoryStream());
            _fileUploadUtilsMock.UploadImage(Arg.Any <Stream>()).Returns(new FileDTO()
            {
                FileName = "FILENAME", FilePath = "FILEPATH"
            });

            Exception exception = await Record.ExceptionAsync(() => _userService.Create(model));

            Assert.Null(exception);

            _randomCodeUtils.Received(1).GenerateRandomCode();
            _hashUtilsMock.Received(1).GenerateHash(Arg.Is <string>(text => text == model.Password));
            await _fileUploadUtilsMock.Received(1).UploadImage(Arg.Any <Stream>());

            await _userRepositoryMock.Received(1).Create(Arg.Is <User>(user => user.Email == model.Email));

            await _userRepositoryMock.Received(1).Save();

            await _emailUtilsMock.Received(1).SendEmail(Arg.Is <string>(email => email == model.Email), Arg.Any <string>(), Arg.Any <string>());
        }
Exemple #2
0
        public async Task <IHttpActionResult> CreateUser(CreateUserRequestModel createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                ApplicationUser appUser       = _applicationUserFactory.Create(createUserModel.Username, createUserModel.Email);
                IdentityResult  addUserResult = await _applicationUserManager.CreateAsync(appUser, createUserModel.Password);

                if (!addUserResult.Succeeded)
                {
                    return(GetErrorResult(addUserResult));
                }

                string code = await _applicationUserManager.GenerateEmailConfirmationTokenAsync(appUser.Id);

                var callbackUrl = new Uri(Url.Link(UriName.Identity.Accounts.CONFIRM_EMAIL, new { userId = appUser.Id, code = code }));
                await _applicationUserManager.SendEmailAsync(appUser.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                return(CreatedAtRoute(UriName.Identity.Accounts.GET_USER, new { id = appUser.Id }, _applicationUserResponseFactory.Create(appUser)));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex, "Failed to CreateUser"));
            }
        }
        public async Task <ApiResponse> CreateUser(CreateUserRequestModel req)
        {
            User user = new();

            user.Email               = req.Email;
            user.Username            = req.Username;
            user.IsActive            = true;
            user.IsEmailVerification = false;

            if (req.IsHash)
            {
                user.PasswordHash = req.Password;
            }
            else
            {
                user.Password = req.Password;
            }

            await _context.AddAsync(user);

            await _context.SaveChangesAsync();

            return(new ApiResponse(
                       "Kullanıcı başarı ile oluşturuldu.",
                       new CreateUserResponseModel
            {
                Email = user.Email,
                Id = user.Id
            }));
        }
        public async Task <IActionResult> Post([FromBody] CreateUserRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.TryAddModelError("Model.Invalid", "Модель не является валидной");
                return(BadRequest(ModelState));
            }

            var identityUser = new User
            {
                UserName = model.UserName,
            };
            var result = await _userManager.CreateAsync(identityUser, model.Password);

            if (!result.Succeeded)
            {
                foreach (var e in result.Errors)
                {
                    ModelState.TryAddModelError(e.Code, e.Description);
                }

                return(new BadRequestObjectResult(ModelState));
            }

            return(new OkResult());
        }
Exemple #5
0
        public async Task <IActionResult> AddAuthenticatedUserRequestAsync(CreateUserRequestModel createUserRequestModel,
                                                                           CancellationToken cancellationToken)
        {
            await this.UserRequestService.AddAuthenticatedUserRequestAsync(createUserRequestModel, cancellationToken);

            return(Ok());
        }
Exemple #6
0
        public async Task <ActionResult <SessionCreateResponseModel> > PostUser(CreateUserRequestModel model)
        {
            var user = new User()
            {
                Id           = Guid.NewGuid(),
                Balance      = 500.0M,
                Name         = model.Username,
                Email        = model.Email,
                PasswordHash = IAuthService.HashPassword(model.Password),
                Role         = UserRoles.User,
            };

            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            var jwt = _authService.AuthenticateUser(new SessionCreateRequestModel()
            {
                Email = user.Email, Password = model.Password
            });

            if (string.IsNullOrEmpty(jwt))
            {
                return(BadRequest("Invalid username or password."));
            }
            _context.Sessions.Add(new Session()
            {
                Token = jwt, CreatedAt = DateTime.UtcNow, UserId = user.Id
            });
            await _context.SaveChangesAsync();

            return(Ok(new SessionCreateResponseModel()
            {
                Id_token = jwt
            }));
        }
Exemple #7
0
        public async Task Create(CreateUserRequestModel model)
        {
            await new CreateUserValidator().ValidateRequestModelAndThrow(model);

            User user = new User(model.Name, model.Email, model.Password);

            await ThrowIfUserNameAlreadyExists(user.Name);
            await ThrowIfUserEmailAlreadyExists(user.Email);


            user.UpdateConfirmationCode(_randomCodeUtils.GenerateRandomCode());
            user.UpdatePassword(_hashUtils.GenerateHash(user.Password));

            Stream  userDefaultProfileImage = _fileUploadUtils.GetDefaultUserProfileImage();
            FileDTO uploadedProfileImage    = await _fileUploadUtils.UploadImage(userDefaultProfileImage);

            ProfileImage image = new ProfileImage(uploadedProfileImage.FileName, uploadedProfileImage.FilePath);

            user.AddProfileImage(image);
            await _userRepository.Create(user);

            await _userRepository.Save();

            await _emailUtils.SendEmail(user.Email, "Confirmation", $"Please confirm your account using this code {user.ConfirmationCode}");
        }
Exemple #8
0
        public async Task <MiscResponse <UserResponseModel> > CreateUserAsync(CreateUserRequestModel model)
        {
            var existingUser = this._userRepo.Find(x => x.Email == model.Email);

            if (existingUser.Any())
            {
                throw new ArgumentException($"A user exists with the given email '{model.Email}'");
            }

            string salt   = generateSalt();
            var    userId = await this._userRepo.AddAsync(new ApplicationUser
            {
                Email        = model.Email,
                IsAdmin      = model.IsAdmin,
                Name         = model.Name,
                Salt         = salt,
                PasswordHash = hashPassword(model.Password, salt)
            });

            return(new MiscResponse <UserResponseModel>()
            {
                Message = "User created successfully",
                Data = new UserResponseModel
                {
                    Email = model.Email,
                    Id = userId,
                    IsAdmin = model.IsAdmin,
                    Name = model.Name
                }
            });
        }
        public void TestCreateUser()
        {
            var USER = _helper.testUsers[1];

            UserController userControllerTest = new UserController();
            //Create test data model
            CreateUserRequestModel model = new CreateUserRequestModel()
            {
                Username = USER.Username,
                Password = USER.Password,
                Email    = USER.Email
            };

            //Test create user success
            var result = userControllerTest.CreateUser(model) as JsonResult;

            Assert.AreEqual(0, ((CreateUserResponseModel)result.Data).Errors.Count);

            //Test already existing username
            model.Email = "*****@*****.**";
            result      = userControllerTest.CreateUser(model) as JsonResult;
            Assert.AreNotEqual(0, ((CreateUserResponseModel)result.Data).Errors.Count);
            Assert.AreEqual("Username already exists.", ((CreateUserResponseModel)result.Data).Errors[0].ErrorMessage);

            //Test already existing email
            model.Email    = USER.Email;
            model.Username = ("neverBeforeBeenUsedUsername" + USER.Username);
            result         = userControllerTest.CreateUser(model) as JsonResult;
            Assert.AreNotEqual(0, ((CreateUserResponseModel)result.Data).Errors.Count);
            Assert.AreEqual("Email already in use.", ((CreateUserResponseModel)result.Data).Errors[0].ErrorMessage);
        }
        public async Task <ResponseWithModel <User> > CreateUser(CreateUserRequestModel createUserModel)
        {
            if (!EmailValidator.Validate(createUserModel.Email))
            {
                return(ResponseWithModel <User> .Unsuccessful("This email does not uphold conventions"));
            }

            //User to be inserted
            var user = new User
            {
                Id        = Guid.NewGuid(),
                Created   = DateTime.UtcNow,
                Email     = createUserModel.Email.ToLower(),
                LastLogin = DateTime.UtcNow,
                Password  = BCrypt.Net.BCrypt.HashPassword(createUserModel.Password),
                AuthLevel = createUserModel.AuthLevel,
            };

            var response = await _userRepository.CreateUser(user);

            if (!response.IsSuccessful)
            {
                return(ResponseWithModel <User> .Unsuccessful(response.Message));
            }

            return(ResponseWithModel <User> .Successfull(user));
        }
        public async Task <IActionResult> RegisterUser([FromBody] CreateUserRequestModel createUserRequestModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var masterResult = Repo.GetUserMaster(createUserRequestModel.UserEmail);

            if (masterResult != null)
            {
                return(Ok("Exists"));
            }

            var userMaster = Mapper.Map <UserMaster>(createUserRequestModel);

            (userMaster.Salt, userMaster.UserPassword) =
                _passwordHashingHelper.GetHashedPassword(createUserRequestModel.UserPassword);

            if (userMaster.Salt == null || userMaster.UserPassword == null)
            {
                return(StatusCode(500));
            }

            await Repo.AddDataToDataSet(userMaster);

            var result = Repo.SaveData();

            if (result != 1)
            {
                Logger.LogWarning("Failed to save data in UserMaster table");
                return(BadRequest("Could not input user data"));
            }

            createUserRequestModel = Mapper.Map(userMaster, createUserRequestModel);
            var userDetails = Mapper.Map <UserDetails>(createUserRequestModel);

            userDetails.UserId = userMaster.UserId;
            await Repo.AddDataToDataSet(userDetails);

            result = Repo.SaveData();
            if (result == 1)
            {
                var token = TokenHandler.Create(createUserRequestModel.UserEmail, AppSettings.Value.SigningKey);
                if (string.IsNullOrEmpty(token))
                {
                    return(StatusCode(500));
                }

                createUserRequestModel = Mapper.Map(userDetails, createUserRequestModel);
                var returnObject = Mapper.Map <CreateUserResponseModel>(createUserRequestModel);
                returnObject.Token = token;
                return(Created("api/users", returnObject));
            }

            Logger.LogWarning("Failed to save data in user details table");
            return(BadRequest("could not add a valid value. \n"));
        }
        public void ShouldHaveValidationErrorWithEmptyPassword(string password)
        {
            CreateUserRequestModel requestModel = new CreateUserRequestModel()
            {
                Password = password
            };

            _validator.ShouldHaveValidationErrorFor(r => r.Password, requestModel).WithErrorMessage("password cannot be empty.");
        }
        public void ShouldHaveValidationErrorWithEmptyEmail(string email)
        {
            CreateUserRequestModel requestModel = new CreateUserRequestModel()
            {
                Email = email
            };

            _validator.ShouldHaveValidationErrorFor(r => r.Email, requestModel).WithErrorMessage("email cannot be empty.");
        }
        public void ShouldHaveValidationErrorWithGreatherThan150CharactersName(string name)
        {
            CreateUserRequestModel requestModel = new CreateUserRequestModel()
            {
                Name = name
            };

            _validator.ShouldHaveValidationErrorFor(r => r.Name, requestModel).WithErrorMessage("name must be less than 150 characters.");
        }
        public void ShouldHaveValidationErrorWithGreaterThan60CharactersPassword(string password)
        {
            CreateUserRequestModel requestModel = new CreateUserRequestModel()
            {
                Password = password
            };

            _validator.ShouldHaveValidationErrorFor(r => r.Password, requestModel).WithErrorMessage("password must be less than 60 characters.");
        }
        public void ShouldHaveValidationErrorGreaterThan255CharactersEmail(string email)
        {
            CreateUserRequestModel requestModel = new CreateUserRequestModel()
            {
                Email = email
            };

            _validator.ShouldHaveValidationErrorFor(r => r.Email, requestModel).WithErrorMessage("email must be less than 254 characters.");
        }
        public void ShouldHaveValidationErrorWithNullName(string name)
        {
            CreateUserRequestModel requestModel = new CreateUserRequestModel()
            {
                Name = name
            };

            _validator.ShouldHaveValidationErrorFor(r => r.Name, requestModel).WithErrorMessage("name cannot be empty.");
        }
        public void ShouldHaveValidationErrorWithInvalidEmail(string email)
        {
            CreateUserRequestModel requestModel = new CreateUserRequestModel()
            {
                Email = email
            };

            _validator.ShouldHaveValidationErrorFor(r => r.Email, requestModel).WithErrorMessage("email must be a valid email.");
        }
Exemple #19
0
        public IActionResult CreateUser(CreateUserRequestModel newUser)
        {
            if (!ModelState.IsValid)
            {
                return(View("CreateUserPage", newUser));
            }

            _users.Create(newUser);
            return(RedirectToAction("UsersPage"));
        }
        public async Task <IActionResult> Register(CreateUserRequestModel model)
        {
            ApplicationUser user = new ApplicationUser
            {
                UserName = model.Email,
                Email    = model.Email,
            };
            var result = await _userManager.CreateAsync(user, model.Password);

            return(RedirectToAction("Index", "Home"));
        }
        public async Task <IActionResult> CreateUser([FromBody] CreateUserRequestModel requestModel)
        {
            var result = await _userHandler.CreateUser(requestModel);

            if (!result.IsSuccessful)
            {
                return(StatusCode(400, result.Message));
            }

            return(new ObjectResult(new { id = result.Entity.Id }));
        }
        public async Task ShouldReturnCreatedAtRouteOnCallCreate()
        {
            CreateUserRequestModel model = new CreateUserRequestModel()
            {
                Email = "*****@*****.**", Name = "New User Name", Password = "******"
            };
            HttpResponseMessage httpResponse = await _httpClient.PostAsync("../users", _createRequestHelper.CreateStringContent(model));

            Assert.Equal((int)HttpStatusCode.Created, (int)httpResponse.StatusCode);
            _database.ResetDatabase();
        }
Exemple #23
0
        public async Task <ActionResult <UserResponseModel> > CreateAsync([FromBody] CreateUserRequestModel createUserRequestModel)
        {
            const string actionName = nameof(CreateAsync);

            Logger.LogDebug(LoggingMessage.ProcessingRequestWithModel, actionName, createUserRequestModel);
            var response = await _userAppService.CreateAsync(createUserRequestModel);

            Logger.LogInfomation(LoggingMessage.RequestResults, actionName);

            return(Ok(response));
        }
Exemple #24
0
        /**
         * POSTs to our API with the CreateUserRequestModel and returns
         * an IRestResponse
         */
        public IRestResponse CreateUser(CreateUserRequestModel model)
        {
            RestRequest request = new RestRequest(CreatePath);

            //Any authentication can be done here, in one place
            var authToken = GetAuthToken();

            request.AddHeader("Authorization", authToken);
            request.AddJsonBody(model);

            return(Client.Post(request));
        }
        public async Task <IActionResult> CreateUser([FromBody] CreateUserRequestModel requestModel)
        {
            /*
             * //baseurl for creating user on identityServer
             * var baseurl = _identityConfig.Value.IdentityServerUrl + "/identity/users";
             *
             * var httpClient = new HttpClient();
             *
             * httpClient.DefaultRequestHeaders
             *  .Accept
             *  .Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
             *
             *
             * //Serialize object to json-format
             * var json = JsonConvert.SerializeObject(new CreateIdentityUser
             * {
             *  AuthLevel = requestModel.AccessLevel,
             *  Email = requestModel.Email,
             *  Password = requestModel.Password,
             *
             *
             * }, Formatting.Indented);
             *
             * var httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
             *
             * //Create user on identityServer
             * var identityResult = await httpClient.PostAsync(baseurl, httpContent);
             *
             * //Evaluate if the result was succesful or not
             * if (!identityResult.IsSuccessStatusCode)
             * {
             *  if (identityResult.Content != null)
             *  {
             *      var errorMsg = await identityResult.Content.ReadAsStringAsync();
             *      return StatusCode((int)identityResult.StatusCode , errorMsg);
             *  }
             *  return StatusCode((int)identityResult.StatusCode, identityResult.ReasonPhrase);
             * }
             */
            //Since the result was succesfull, try and read the result for an id generated from the identityServer
            var id = Guid.NewGuid();

            var response = await CommandRouter.RouteAsync <CreateUserCommand, IdResponse>(
                new CreateUserCommand(id, requestModel.Name, requestModel.Email, requestModel.Password, requestModel.AccessLevel, requestModel.BaseWage, requestModel.EmploymentDate));

            if (!response.IsSuccessful)
            {
                return(StatusCode(400, response.Message));
            }

            return(new ObjectResult(response.Id));
        }
Exemple #26
0
        public async Task <UserDto> Create(CreateUserRequestModel model)
        {
            var user = new Data.Models.User
            {
                UserName = model.UserName,
                Email    = model.UserName,
                RoleId   = model.Role
            };

            await _userManager.CreateAsync(user, model.Password);

            return(await FindByUserName(user.UserName));
        }
Exemple #27
0
        public async Task <IActionResult> Create(CreateUserRequestModel model)
        {
            try
            {
                await _userService.Create(model);

                return(CreatedAtRoute("", null));
            }
            catch (Exception exception)
            {
                return(this.HandleExceptionToUserAndLogIfExceptionIsUnexpected(exception));
            }
        }
Exemple #28
0
 public void Create(CreateUserRequestModel newUser)
 {
     _context.Users.Add(new User
     {
         FirstName       = newUser.FirstName,
         LastName        = newUser.LastName,
         Email           = newUser.Email,
         Username        = newUser.Username,
         ProfileImageUrl = newUser.ProfileImageUrl,
         CoverImageUrl   = newUser.CoverImageUrl,
     });
     _context.SaveChanges();
 }
Exemple #29
0
        public ActionResult CreateUser(CreateUserRequestModel request)
        {
            //CreateUserResponseModel response = Mapper.Map<CreateUserRequestModel, CreateUserResponseModel>(request);
            var response = new CreateUserResponseModel()
            {
                Username = request.Username,
                Email    = request.Email
            };

            response.Errors = UserService.CreateUser(request.Username, request.Email, request.Password); //this creates a user and returns errors if it cannot

            return(Json(response));
        }
        public async Task <IActionResult> CreateUser([FromBody] CreateUserRequestModel createUserRequestModel)
        {
            //Validate the user
            var response = await UserHandler.MigrateUser(createUserRequestModel.Id, createUserRequestModel.Email.ToLower(), createUserRequestModel.Password);

            if (!response.IsSuccessful)
            {
                Console.WriteLine(response.Message);
                Log.Logger.Error(nameof(CreateUser) + " failed for {Id}, {Email} with {@Response}", createUserRequestModel.Id, createUserRequestModel.Email, response);
                return(StatusCode(403, response.Message));
            }

            return(new ObjectResult(response.Token));
        }