Пример #1
0
        public async Task CreateUser_username_used()
        {
            // Arrange
            var existingUser = new UserEntity()
            {
                Id       = Guid.NewGuid(),
                Username = "******",
                Password = "******"
            };

            UserEntities.Add(existingUser);
            var             controller = new UserController(UserService.Object);
            UserCreationDTO newUser    = new UserCreationDTO("CreateUserUsernameUsed", "Password");

            // Act
            ActionResult <UserDTO> response = await controller.CreateUser(newUser);

            // Assert
            Assert.IsInstanceOfType(response.Result, typeof(ConflictResult));
            var result = response.Result as ConflictResult;

            Assert.AreEqual(409, result.StatusCode);
            UserEntities.Remove(existingUser);
            //userRepository.Verify(repo => repo.GetUser(It.IsAny<string>()), Times.Once());
        }
Пример #2
0
        public ActionResult CreateUser([FromBody] UserCreationDTO newUser)
        {
            Console.WriteLine("Trying to create a new user. Information acquired\nUsername {0} \nPassword {1}", newUser.Username, newUser.Password);
            if (ds.GetPlayerByUsername(newUser.Username) != null)
            {
                return(BadRequest("User already exists"));
            }

            int.TryParse(config.GetSection("Auth:PwdSize").Value, out var size);

            if (size == 0)
            {
                throw new ArgumentException();
            }

            var salt = AuthService.SaltGenerator(size);

            var pwd = AuthService.HashPassword(newUser.Password, salt, size);

            Player player = ds.CreatePlayer(newUser.Username, pwd, salt);

            var newUserInfo = new
            { id       = player.Id,
              name     = player.Username,
              password = newUser.Password,
              token    = GetToken(player.Id) };

            return(CreatedAtRoute(null, newUserInfo));
        }
        public async Task <ActionResult> Put(int id, [FromForm] UserCreationDTO userCreationDTO)
        {
            var userDB = await context.User.FirstOrDefaultAsync(x => x.Id == id);

            if (userDB == null)
            {
                return(NotFound());
            }

            userDB = mapper.Map(userCreationDTO, userDB);

            if (userCreationDTO.Avatar_img != null)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await userCreationDTO.Avatar_img.CopyToAsync(memoryStream);

                    var content   = memoryStream.ToArray();
                    var extension = Path.GetExtension(userCreationDTO.Avatar_img.FileName);
                    userDB.Avatar_img = await fileStorageService.EditFile(content, extension, containerName,
                                                                          userDB.Avatar_img, userCreationDTO.Avatar_img.ContentType);
                }
            }

            await context.Database.ExecuteSqlInterpolatedAsync($"delete from FavoriteProjects where UserId = {userDB.Id}");

            await context.SaveChangesAsync();

            return(NoContent());
        }
        public async Task <ActionResult> PostUser([FromForm] UserCreationDTO userCreation)
        {
            var user = mapper.Map <User>(userCreation);



            if (userCreation.Avatar_img != null)
            {
                using (var memoryStream = new MemoryStream())
                {
                    await userCreation.Avatar_img.CopyToAsync(memoryStream);

                    var content   = memoryStream.ToArray();
                    var extension = Path.GetExtension(userCreation.Avatar_img.FileName);
                    user.Avatar_img = await fileStorageService.SaveFile(content, extension, containerName, userCreation.Avatar_img.ContentType);
                }
            }

            context.Add(user);
            await context.SaveChangesAsync();

            var userDTO = mapper.Map <UserDTO>(user);

            return(new CreatedAtRouteResult("getUsers", new { id = userDTO.Id }, userDTO));
        }
Пример #5
0
        public async Task <ActionResult <UserDTO> > CreateUser(UserCreationDTO dto)
        {
            // Check username not already used
            if (await _userService.DoesUserExist(dto.Username) == true)
            {
                return(Conflict());
            }

            try
            {
                UserDTO userDTO = await _userService.CreateUserAsync(dto);

                return(CreatedAtAction(nameof(GetUser), new { id = userDTO.Id }, userDTO));
            }
            catch (Exception ex)
            {
                var problemDetails = new ProblemDetails
                {
                    Title    = "An unexpected error occurred.",
                    Status   = StatusCodes.Status500InternalServerError,
                    Detail   = "Unable to create the user at this moment due to an error, the error has been logged and sent to the developers for fixing.",
                    Instance = HttpContext.TraceIdentifier,
                };
                return(StatusCode(StatusCodes.Status500InternalServerError, problemDetails));
            }
        }
Пример #6
0
        public ActionResult AddNewUser([FromBody] UserCreationDTO user)
        {
            User ActualUser = _mapper.Map <User>(user);
            var  res        = _repository.AddUser(ActualUser);

            if (!res)
            {
                return(StatusCode(409, $"email '{user.email}' already exist"));
            }
            _repository.save();
            return(Ok());
        }
Пример #7
0
        public UserCreatedDTO AddUser(UserCreationDTO userCreationDTO)
        {
            User user = Mapper.Map <User>(userCreationDTO);

            user.Id = GetNextId();

            User result = userRepository.CreateUser(user);

            UserCreatedDTO returnValue = Mapper.Map <UserCreatedDTO>(result);

            return(returnValue);
        }
Пример #8
0
        private List <FavoriteProjects> MapFavoriteProjects(UserCreationDTO userCreationDTO, User user)
        {
            var result = new List <FavoriteProjects>();

            foreach (var id in userCreationDTO.FavoriteProjectIds)
            {
                result.Add(new FavoriteProjects()
                {
                    ProjectId = id
                });
            }
            return(result);
        }
        public void AddUser_ShouldAddUserToDatasource_WhenValidUserCreationDTO()
        {
            UserCreationDTO userCreation = new UserCreationDTO()
            {
                FirstName = "Gareth",
                LastName  = "SouthGate",
                Password  = "******"
            };

            var returnValue = userManager.AddUser(userCreation);

            Assert.AreEqual(userCreation.FirstName, returnValue.FirstName);
            Assert.AreEqual(userCreation.LastName, returnValue.LastName);
            Assert.AreEqual(3, returnValue.Id);
        }
Пример #10
0
        public async Task <ActionResult <UserToken> > Register([FromBody] UserCreationDTO userCreationDTO)
        {
            var userRegister = await _accountsService.RegisterUserAsync(userCreationDTO);

            if (!userRegister.Succeeded)
            {
                foreach (var error in userRegister.Errors)
                {
                    ModelState.TryAddModelError(error.Code, error.Description);
                }
                return(BadRequest(ModelState));
            }

            return(await _accountsService.BuildToken(userCreationDTO.EmailAddress));
        }
Пример #11
0
        public IActionResult AddUser([FromBody] UserCreationDTO user)
        {
            if (user == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var returnValue = userManager.AddUser(user);

            return(CreatedAtRoute("GetUserById", new { id = returnValue.Id }, returnValue));
        }
Пример #12
0
        public async Task <ActionResult> Post([FromBody] UserCreationDTO userCreationDTO)
        {
            var user = mapper.Map <User>(userCreationDTO);

            if (user == null)
            {
                return(BadRequest());
            }
            user.userid     = context.tblUser.Max(x => x.userid) + 1;
            user.created_on = DateTime.Now.Date;
            user.updated_on = DateTime.Now.Date;
            context.Add(user);
            await context.SaveChangesAsync();

            var userDTO = mapper.Map <UserDTO>(user);

            return(new CreatedAtRouteResult("getUser", new { id = userDTO.userid }, userDTO));
        }
Пример #13
0
        public async Task <UserDTO> CreateUserAsync(UserCreationDTO userCreationDTO)
        {
            UserEntity entity = userCreationDTO.ToUserEntity();

            byte[] salt           = _authService.GenerateSalt();
            string hashedPassword = _authService.HashPassword(entity.Password, salt);

            entity.Password = hashedPassword;
            entity.Salt     = salt;

            UserEntity addedEntity = await _userRepository.PostUser(entity);

            if (_userRepository.Save() == false)
            {
                throw new Exception();
            }

            return(addedEntity.ToUserDto());
        }
Пример #14
0
        public async Task CreateUser()
        {
            // Arrange
            var             controller = new UserController(UserService.Object);
            UserCreationDTO newUser    = new UserCreationDTO("CreateUserUsername", "CreateUserPassword");

            // Act
            ActionResult <UserDTO> response = await controller.CreateUser(newUser);

            // Assert
            Assert.IsInstanceOfType(response.Result, typeof(CreatedAtActionResult));
            var result = response.Result as CreatedAtActionResult;

            Assert.AreEqual(201, result.StatusCode);
            Assert.IsNotNull(result.Value);
            Assert.IsInstanceOfType(result.Value, typeof(UserDTO));
            UserDTO createdItem = result.Value as UserDTO;

            Assert.AreEqual(createdItem.Username, "CreateUserUsername");
        }
        public void AddUser_ShouldReturn201_WhenCalledWithValidUserCreationDTO()
        {
            UserCreationDTO userCreationDTO = new UserCreationDTO()
            {
                FirstName = "Matthew",
                LastName  = "Roberts",
                Password  = "******"
            };

            var result   = userController.AddUser(userCreationDTO);
            var response = result as CreatedAtRouteResult;

            Assert.IsNotNull(response);
            Assert.AreEqual(201, response.StatusCode);
            Assert.AreEqual("GetUserById", response.RouteName);
            Assert.IsTrue(response.Value is UserCreatedDTO);
            UserCreatedDTO userCreatedDTO = response.Value as UserCreatedDTO;

            Assert.AreEqual(userCreationDTO.FirstName, userCreatedDTO.FirstName);
            Assert.AreEqual(userCreationDTO.LastName, userCreatedDTO.LastName);
        }
        public async Task <ActionResult> SignUpMember(UserCreationDTO user)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UserProfileModel newUser = new UserProfileModel();
                    newUser.Email         = newUser.UserName = user.Email;
                    newUser.FirstName     = user.FirstName;
                    newUser.LastName      = user.LastName;
                    newUser.Height        = user.Height;
                    newUser.CurrentWeight = user.CurrentWeight;
                    newUser.DateOfBirth   = new DateTimeOffset(Convert.ToDateTime(user.DateOfBirth));
                    newUser.PhoneNumber   = user.PhoneNumber;

                    var result       = _memberManager.CreateAsync(newUser, user.Password).GetAwaiter().GetResult();
                    var token        = _memberManager.GenerateEmailConfirmationTokenAsync(newUser).GetAwaiter().GetResult();
                    var confirmEmail = _memberManager.ConfirmEmailAsync(newUser, token).GetAwaiter().GetResult();
                    if (confirmEmail.Succeeded)
                    {
                        if (result.Succeeded)
                        {
                            var newResult = _memberManager.AddToRoleAsync(newUser, AppRoles.Member).GetAwaiter().GetResult();
                            if (newResult.Succeeded)
                            {
                                return(Json("User created Successfully"));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(Json(ex.Message));
                }
            }
            return(Json("ModelState not valid"));
        }
Пример #17
0
        public async Task <IdentityResult> RegisterUserAsync(UserCreationDTO userCreationDTO)
        {
            var user = new User {
                UserName     = userCreationDTO.EmailAddress, Email = userCreationDTO.EmailAddress,
                FirstName    = userCreationDTO.FirstName, LastName = userCreationDTO.LastName,
                RegisterDate = DateTime.UtcNow
            };
            var register = await _userManager.CreateAsync(user, userCreationDTO.Password);

            if (!register.Succeeded)
            {
                var errors = new StringBuilder();
                foreach (var error in register.Errors)
                {
                    errors.Append($"{error.Code} ");
                }
                _logger.LogWarn($"Failed to register {user}. Errors: {errors}");
            }
            else
            {
                _logger.LogInfo($"{user} registered successfully.");
            }
            return(register);
        }
Пример #18
0
        public async Task <UserDTO> AddAsync(UserCreationDTO user)
        {
            User result = await AddAsync(_mapper.Map <UserCreationDTO, User>(user));

            return(_mapper.Map <User, UserDTO>(result));
        }