Ejemplo n.º 1
0
        public async void CreateAsync(UserCreateDTO user, String azureUId, ResponseLogic expected)
        {
            var existingUser = new User()
            {
                Id = 1, Firstname = "IAlready", Surname = "Exist", Mail = "*****@*****.**", AzureUId = "existingAuzreUId"
            };
            var existingLocation = new Location()
            {
                Id = 1, City = "Sydney", Country = "Australia"
            };

            userRepository     = new UserRepository(setupContextForIntegrationTests());
            skillRepository    = new SkillRepository(context);
            projectRepository  = new ProjectRepository(context);
            locationRepository = new LocationRepository(context);

            var locationLogic = new LocationLogic(locationRepository, userRepository, projectRepository);

            context.Users.Add(existingUser);
            context.Locations.Add(existingLocation);
            context.SaveChanges();

            //SanityCheck
            Assert.Equal(1, await context.Users.CountAsync());
            Assert.Equal(existingUser, await context.Users.FirstAsync());
            Assert.Equal(1, await context.Locations.CountAsync());
            Assert.Equal(existingLocation, await context.Locations.FirstAsync());

            using (var logic = new UserLogic(userRepository, skillLogicMock.Object, sparkLogicMock.Object, locationLogic))
            {
                var result = await logic.CreateAsync(user, azureUId);

                Assert.Equal(expected, result);
            }
        }
Ejemplo n.º 2
0
        public IActionResult CreateUser([FromBody] UserCreateDTO user)
        {
            if (user == null)
            {
                // ToDo Log this
            }
            List <InterestsUser> interests = new List <InterestsUser>();


            foreach (var interest in user.Interests)
            {
                interests.Add(new InterestsUser {
                    TelephoneNumber = user.TelephoneNumber, InterestId = interest.InterestId
                });
            }
            var userEntity = _mapper.Map <User>(user);

            userEntity.InterestsUsers = interests;
            _repository.Users.CreateUser(userEntity);
            _repository.Save();

            var userReadDto = _mapper.Map <UserReadDTO>(userEntity);

            return(CreatedAtRoute(nameof(GetUserByNumber), new { num = userReadDto.TelephoneNumber }, userReadDto));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> PostUser([FromBody] UserCreateDTO userCreateDTO)
        {
            _logger.Info("Executing PostUser() method...");
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Custom Validation
            var isEmailExists = await _userService.IsEmailExistsAsync(userCreateDTO.Email);

            if (isEmailExists)
            {
                ModelState.AddModelError("Email", "Podany adres email istnieje w bazie.");
                return(BadRequest(ModelState));
            }

            bool result = await _userService.CreateUserAsync(userCreateDTO);

            if (!result)
            {
                _logger.Error("Error during user registration");
                return(BadRequest());
            }
            _logger.Info(string.Format("User {0} {1} has been added ", userCreateDTO.FirstName, userCreateDTO.LastName));

            var user = await this._userManager.FindByNameAsync(userCreateDTO.Email);

            var userToken = new UserTokenDTO
            {
                Token = this._oAuthService.GetUserAuthToken(userCreateDTO.Email, user.Id.ToString())
            };

            return(StatusCode((int)HttpStatusCode.Created, userToken));
        }
        public JsonResult Get(string id)
        {
            UserCreateDTO result = null;

            try
            {
                var user = UserManager.FindById(id);

                if (user != null)
                {
                    result        = new UserCreateDTO();
                    result.Id     = user.Id;
                    result.Email  = user.Email;
                    result.Roles  = UserManager.GetRoles(user.Id);
                    result.Claims = UserManager.GetClaims(user.Id)
                                    .Select(t => new UserClaimDTO()
                    {
                        Key = t.Type, Value = t.Value
                    })
                                    .ToList();
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> CreateUserAsync([FromForm] UserCreateDTO user)
        {
            if (user.Username == "" || user.Username is null)
            {
                return(BadRequest("You have to enter a username"));
            }
            if (!user.Email.Contains('@'))
            {
                return(BadRequest("You have to enter a valid email address"));
            }
            if (user.Password1 == "" || user.Password1 is null)
            {
                return(BadRequest("You have to enter a password"));
            }
            if (user.Password1 != user.Password2)
            {
                return(BadRequest("The two passwords do not match"));
            }

            var exist = await UserRepo.ReadAsync(user.Username);

            if (exist is not null)
            {
                return(BadRequest("The username is already taken"));
            }

            await UserRepo.CreateAsync(user);

            return(Redirect("/login"));
            //return Ok("You were succesfully registered and can login now");
        }
Ejemplo n.º 6
0
        public async Task Create_ThanResponseWithCode201AndCorrespondedBody()
        {
            var userCreate = new UserCreateDTO
            {
                FirstName = "A",
                LastName  = "B",
                Birthday  = new DateTime(2000, 10, 10),
                TeamId    = null
            };

            string jsonInString = JsonConvert.SerializeObject(userCreate);
            var    httpResponse = await client.PostAsync("api/users",
                                                         new StringContent(jsonInString, Encoding.UTF8, "application/json"));

            var stringResponse = await httpResponse.Content.ReadAsStringAsync();

            var createdUser = JsonConvert.DeserializeObject <UserDTO>(stringResponse);

            await client.DeleteAsync($"api/users/{createdUser.Id}");

            Assert.Equal(HttpStatusCode.Created, httpResponse.StatusCode);
            Assert.Equal(userCreate.FirstName, createdUser.FirstName);
            Assert.Equal(userCreate.LastName, createdUser.LastName);
            Assert.Equal(userCreate.Email, createdUser.Email);
            Assert.Equal(userCreate.Birthday, createdUser.Birthday);
            Assert.Equal(userCreate.TeamId, createdUser.TeamId);
        }
Ejemplo n.º 7
0
        public async Task <ActionResult <UserReadDTO> > CreateUser(UserCreateDTO userCreateDTO)
        {
            try
            {
                var hashedPassword = BCrypt.Net.BCrypt.HashPassword(userCreateDTO.password, 10);
                userCreateDTO.password = hashedPassword;
                var userModel = _mapper.Map <User>(userCreateDTO);
                try
                {
                    await _repository.CreateUser(userModel);
                }
                catch (Exception e)
                {
                    if ("Email alredy exists!".Equals(e.Message))
                    {
                        return(BadRequest(new { error = "Email alredy exists!" }));
                    }
                    throw e;
                }
                await _repository.SaveChanges();

                var userReadDTO = _mapper.Map <UserReadDTO>(userModel);
                return(CreatedAtRoute(nameof(CreateUser), userReadDTO));
            }
            catch (Exception)
            {
                return(new StatusCodeResult(StatusCodes.Status500InternalServerError));
            }
        }
Ejemplo n.º 8
0
        public ActionResult <User> PostUser(UserCreateDTO user)
        {
            var userMapped = _mapper.Map <User>(user);

            if (userMapped.Role != Policies.User && userMapped.Role != Policies.Admin)
            {
                return(BadRequest());
            }
            if (userMapped.Role == Policies.Admin)
            {
                var identity = HttpContext.User.Identity as ClaimsIdentity;
                if (identity != null && !HttpContext.User.IsInRole(Policies.Admin))
                {
                    return(Forbid());
                }
                else
                {
                    return(BadRequest());
                }
            }
            userMapped.RefreshToken           = "";
            userMapped.RefreshTokenExpiryDate = DateTime.Now;
            _repository.PostUser(userMapped);
            var userReadDTO = _mapper.Map <UserReadDTO>(userMapped);

            return(CreatedAtRoute(nameof(GetUserById), new { Id = userReadDTO.Id }, userReadDTO));
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Insert([FromBody] UserCreateDTO request)
        {
            try
            {
                if (String.IsNullOrEmpty(request.Username))
                {
                    ModelState.AddModelError("Username", "Username is empty");
                }

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

                User user = new User()
                {
                    DisplayName = request.DisplayName,
                    Email       = request.Email,
                    Username    = request.Username,
                    Password    = request.Password,
                    RoleId      = request.RoleId
                };

                _userService.Insert(user);
                return(Ok(user));
            }
            catch (Exception ex)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError));
            }
        }
Ejemplo n.º 10
0
        public async Task <ActionResult <UserReadDTO> > CreateUser([FromBody] UserCreateDTO userCreateDto)
        {
            if (userCreateDto == null)
            {
                return(BadRequest());
            }

            var model = new User
                        (
                userCreateDto.Email,
                userCreateDto.Firstname,
                userCreateDto.Lastname,
                userCreateDto.Username,
                userCreateDto.Role,
                userCreateDto.Password,
                userCreateDto.Salt
                        );
            await _userService.AddUser(model);

            var userReadDto = new UserReadDTO
            {
                UserId    = model.UserId,
                Email     = model.Email,
                Role      = model.Role,
                Username  = model.Username,
                Firstname = model.Firstname,
                Lastname  = model.Lastname,
            };

            return(CreatedAtRoute(nameof(GetUser), new { Id = userReadDto.UserId }, userReadDto));
        }
Ejemplo n.º 11
0
        public async Task <ActionResult <UserCreateDTO> > UpdateUserById(string id, UserCreateDTO userCreateDTO)
        {
            var checkUser = await _userRepo.GetOneUser(id);

            if (checkUser != null)
            {
                AppUser updatedUser = new AppUser()
                {
                    UserId            = userCreateDTO.UserId,
                    UserRole          = userCreateDTO.UserRole,
                    First             = userCreateDTO.First,
                    Last              = userCreateDTO.Last,
                    Email             = userCreateDTO.Email,
                    NumPacksPurchased = userCreateDTO.NumPacksPurchased,
                    CurrencyAmount    = userCreateDTO.CurrencyAmount
                };

                bool result = await _userRepo.UpdateUserById(id, updatedUser);

                if (result)
                {
                    return(NoContent()); //update successfull
                }
                else
                {
                    return(BadRequest()); //something wrong with update
                }
            }
            return(NotFound()); //Return 404 if no auction details found
        }
Ejemplo n.º 12
0
        public async Task <ActionResult <UserReadDTO> > CreateUser(UserCreateDTO userCreateDTO)
        {
            var existingUser = await _context.Users.Where(u => u.Username.Equals(userCreateDTO.Username)).FirstOrDefaultAsync();

            if (existingUser != null)
            {
                return(BadRequest(new { message = "Naudotojas su slapyvardžiu \"" + userCreateDTO.Username + "\" jau egzistuoja." }));
            }

            var existingEmail = await _context.Users.Where(u => u.Email.Equals(userCreateDTO.Email)).FirstOrDefaultAsync();

            if (existingEmail != null)
            {
                return(BadRequest(new { message = "Naudotojas su el. paštu \"" + userCreateDTO.Email + "\" jau egzistuoja." }));
            }

            var user = _mapper.Map <User>(userCreateDTO);

            user.Role = Role.User;
            _userService.CreateHashedPassword(user, userCreateDTO.Password);
            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            var returningUser = _mapper.Map <UserReadDTO>(user);

            return(CreatedAtAction("GetUser", new { id = user.Id }, returningUser));
        }
Ejemplo n.º 13
0
        public IActionResult Create(UserCreateDTO userDto)
        {
            var user = userDto.ToUser();

            user = _userRepository.Create(user);
            return(Ok(user.ToDTO()));
        }
        public async Task E_Possivel_Invocar_a_Controller_Create()
        {
            var serviceMock = new Mock <IUserService>();
            var nome        = Faker.Name.FullName();
            var email       = Faker.Internet.Email();

            serviceMock.Setup(m => m.Post(It.IsAny <UserCreateDTO>())).ReturnsAsync(
                new UserCreateResultDTO
            {
                Id       = Guid.NewGuid(),
                Name     = nome,
                Email    = email,
                CreateAt = DateTime.UtcNow
            }
                );

            _controller = new UsersController(serviceMock.Object);
            _controller.ModelState.AddModelError("Name", "É um Campo Obrigatório");

            Mock <IUrlHelper> url = new Mock <IUrlHelper>();

            url.Setup(x => x.Link(It.IsAny <string>(), It.IsAny <object>())).Returns("http://localhost:5000");
            _controller.Url = url.Object;

            var userDtoCreate = new UserCreateDTO
            {
                Name  = nome,
                Email = email,
            };

            var result = await _controller.Post(userDtoCreate);

            Assert.True(result is BadRequestObjectResult);
        }
Ejemplo n.º 15
0
        public async Task <ActionResult> Post([FromBody] UserCreateDTO user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var result = await _userService.Post(user);

                if (result != null)
                {
                    return(Created(new Uri(Url.Link("GetById", new { id = result.Id })), result));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (ArgumentException e)
            {
                return(StatusCode((int)HttpStatusCode.InternalServerError, e.Message));
            }
        }
Ejemplo n.º 16
0
 private bool IsCorrectRole(UserCreateDTO User)
 {
     return(User.Roles.All(
                Item =>
                Item == RoleName.Admin.ToString() ||
                Item == RoleName.User.ToString()));
 }
Ejemplo n.º 17
0
        public async Task <UserDTO> CreateUser(UserCreateDTO dto)
        {
            var entity = dto.ToEntity();

            entity.SecurityStamp = Guid.NewGuid().ToString();

            var tryCreate = await UserManager.CreateAsync(entity, dto.Password);

            if (!tryCreate.Succeeded)
            {
                throw new Exception(string.Join(",", tryCreate.Errors));
            }

            var _claims = dto.Claims.Select(claim => new Claim(claim.Key, claim.Value));

            if (_claims.Count() > 0)
            {
                await UserManager.AddClaimsAsync(entity, _claims);
            }

            if (dto.Roles.Count() > 0)
            {
                await UserManager.AddToRolesAsync(entity, dto.Roles);
            }

            return(entity.ToDTO());
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> Create([FromBody] UserCreateDTO userDTO)
        {
            var location = GetControllerActionNames();

            try
            {
                _logger.LogInfo($"{location}: User submission Attempted");
                if (userDTO == null)
                {
                    _logger.LogWarn($"{location}: Empty request was submitted");
                    return(BadRequest(ModelState));
                }
                if (!ModelState.IsValid)
                {
                    _logger.LogWarn($"{location}: User Data was Incomplete");
                    return(BadRequest(ModelState));
                }
                var user   = _mapper.Map <User>(userDTO);
                var isGood = await _userRepository.Create(user);

                if (!isGood)
                {
                    return(InternalError($"{location}: User creation failed"));
                }

                _logger.LogInfo($"{location}: User Data was created");
                return(Created("Create", new { user }));
            }
            catch (Exception e)
            {
                return(InternalError($"{location}: {e.Message} - {e.InnerException}"));
            }
        }
Ejemplo n.º 19
0
        public AddResult CreateNewPersonnel(UserCreateDTO user, UserRoles role)
        {
            if (!DataValidation.ValidateTelNum(user.TelNumber))
            {
                return(AddResult.InvalidInput);
            }
            if (!DataValidation.ValidatePassport(user.Passport))
            {
                return(AddResult.InvalidInput);
            }
            if (!DataValidation.ValidatePassport(user.EmplBook))
            {
                return(AddResult.InvalidInput);
            }

            user.Role = role;
            var res = HotelApiClient.GetInstance().CreatePersonnel(user);

            if (res == System.Net.HttpStatusCode.NoContent)
            {
                //Storage.Instance.ChangeAllClients(clientDTO);
                return(AddResult.Success);
            }
            if (res == System.Net.HttpStatusCode.Conflict)
            {
                return(AddResult.AlreadyCreated);
            }

            return(AddResult.Error);
        }
Ejemplo n.º 20
0
        public async Task Join_given_existant_sessionkey_and_user_joins_scrummaster()
        {
            var sessionRepo = new Mock <ISessionRepository>();
            var cache       = new MemoryCache(new MemoryCacheOptions());

            sessionRepo.Setup(s => s.FindByKeyAsync(It.IsAny <string>()))
            .ReturnsAsync(new SessionDTO
            {
                SessionKey = "ABC1234", Users = new HashSet <UserDTO> {
                    new UserDTO {
                        IsHost = false
                    }
                }
            });

            sessionRepo.Setup(s => s.AddUserToSession(It.IsAny <UserCreateDTO>(), It.IsAny <int>()))
            .Returns(new UserDTO {
                Id = 42
            });

            var controller = new SessionController(sessionRepo.Object, cache, null);
            var input      = new UserCreateDTO {
                Nickname = "Marty McTestface", IsHost = true
            };
            var post = await controller.Join("ABC1234", input);

            Assert.IsType <UserStateResponseDTO>(post.Value);
            Assert.IsType <string>(post.Value.Token);
            Assert.True(post.Value.Token != string.Empty);
        }
Ejemplo n.º 21
0
        public async Task DeleteById_ThanResponseWithCode204AndGetByIdResponseCode404()
        {
            var userCreate = new UserCreateDTO
            {
                Birthday = new DateTime(2000, 10, 10)
            };

            string jsonInString = JsonConvert.SerializeObject(userCreate);
            await client.PostAsync("api/users",
                                   new StringContent(jsonInString, Encoding.UTF8, "application/json"));

            var httpResponseUsers = await client.GetAsync($"api/users");

            var stringResponseUsers = await httpResponseUsers.Content.ReadAsStringAsync();

            var users = JsonConvert.DeserializeObject <ICollection <UserDTO> >(stringResponseUsers);

            var httpResponse = await client.DeleteAsync($"api/users/{users.Max(u => u.Id)}");

            Assert.Equal(HttpStatusCode.NoContent, httpResponse.StatusCode);

            var httpResponseGetById = await client.GetAsync($"api/users/{users.Max(u => u.Id)}");

            Assert.Equal(HttpStatusCode.NotFound, httpResponseGetById.StatusCode);
        }
Ejemplo n.º 22
0
        public async Task <ResponseLogic> CreateAsync(UserCreateDTO user, string azureUId)
        {
            var existing = await _repository.FindFromAzureUIdAsync(azureUId);

            if (existing != null)
            {
                return(ResponseLogic.ALREADY_EXISTS);
            }

            if (user.Location != null)
            {
                var success = await _locationLogic.CreateAsync(new LocationCreateDTO()
                {
                    City = user.Location.City, Country = user.Location.Country
                });

                if (success == ResponseLogic.SUCCESS)
                {
                    user.Location = await _locationLogic.FindExactAsync(user.Location.City, user.Location.Country);
                }
                else
                {
                    return(ResponseLogic.ERROR_CREATING);
                }
            }

            var id = await _repository.CreateAsync(user, azureUId);

            if (id == 0)
            {
                return(ResponseLogic.ERROR_CREATING);
            }

            return(ResponseLogic.SUCCESS);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Adds new user into system and signing him in
        /// </summary>
        /// <param name="user">User to be added</param>
        /// <returns>Information about signed user</returns>
        /// <exception cref="BLException">Throw when email has been already used</exception>
        public async Task <UserSignedDTO> AddUserAsync(UserCreateDTO user)
        {
            using var uow = UowProviderFunc().Create();
            var repo = userRepositoryFunc();

            if (await repo.GetByEmailAsync(user?.Email) != null)
            {
                throw new BLException(UserErrorCode.EmailAlreadyUsed, ErrorMessages.EmailAlreadyUsed);
            }

            var entity = mapper.Map <User>(user);

            var(hash, salt) = SecurityHelper.CreateHash(user.Password);
            var currentDateTime = DateTime.Now;

            entity.PasswordHash = hash;
            entity.PasswordSalt = salt;
            entity.LastLoginOn  = currentDateTime;
            entity.CreatedOn    = currentDateTime;
            entity.TokenHash    = Convert.ToBase64String(SecurityHelper.CreateHash(salt, user.Token));

            repo.Insert(entity);
            await uow.CommitAsync();

            var result = mapper.Map <UserSignedDTO>(entity);

            result.Token = user.Token;
            return(result);
        }
Ejemplo n.º 24
0
        public async Task Post_given_invalid_Role_returns_BadRequest_with_error_message()
        {
            var dto = new UserCreateDTO
            {
                FirstName = "Test",
                SurName   = "Test",
                Email     = "test@Test",
                Password  = "******",
                UserRole  = "test"
            };

            var responseText = "Users must have an assigned a valid role";

            var repository = new Mock <IUserRepository>();

            var logger = new Mock <ILogger <UsersController> >();

            var controller = new UsersController(repository.Object, logger.Object);

            var post = await controller.Post(dto);

            var result = post.Result as BadRequestObjectResult;

            Assert.IsType <BadRequestObjectResult>(post.Result);
            Assert.Equal(responseText, result.Value);
        }
        public ActionResult <ResponseModelDTO> Authenticate([FromBody] UserCreateDTO user)
        {
            var userModel = _mapper.Map <UserModel>(user);
            var response  = _repository.Authenticate(userModel);

            _repository.SaveChanges();
            return(Ok(response));
        }
Ejemplo n.º 26
0
        public IActionResult Create(UserCreateDTO userCreateDTO)
        {
            // this.UserAppService.



            return(Ok());
        }
Ejemplo n.º 27
0
        public async Task <int> Create(UserCreateDTO user)
        {
            var response = await _client.PostAsync("api/v1/users", user.ToHttpContent());

            var newUserId = response.Content.To <int>().Result;

            return(response.IsSuccessStatusCode ? newUserId : -1);
        }
Ejemplo n.º 28
0
        public async Task <UserSignedDTO> Post(UserCreateDTO user)
        {
            user.Token = JwtTokenHelper.GenerateToken(user.Email);

            return(await ExecuteAsync(
                       () => userFacade.AddUserAsync(user),
                       (ex) => throw new BadRequestException(ex)));
        }
Ejemplo n.º 29
0
        public async Task <Response <UserDTO> > CreateUserWithPasswordRestore(UserCreateDTO dto, string code)
        {
            var user = await CreateUser(dto);

            await _changePasswordRepository.AddRequest(user.Data.Id, code);

            return(user);
        }
Ejemplo n.º 30
0
 public static bool UserCreateIsValid(UserCreateDTO newUser)
 {
     return(!(newUser == null || newUser.LastName?.Length > 32 || newUser.LastName?.Length == 0 ||
              newUser.FirstName?.Length > 32 || newUser.FirstName?.Length == 0 ||
              newUser.UserName?.Length > 32 || newUser.UserName?.Length == 0 ||
              newUser.Email?.Length > 250 || !RegExpEmail.IsMatch(newUser.Email) ||
              !RegExpPassword.IsMatch(newUser.Password)));
 }