Exemple #1
0
        protected override IEnumerable <UserSocial> ResolveCore(UserPostDto source)
        {
            var userSocials   = new List <UserSocial>();
            var dbUserSocials = _userRepository.GetUserSocials(source.Username);

            if (source.Socials == null)
            {
                return(userSocials);
            }
            foreach (var social in source.Socials)
            {
                var userSocial = dbUserSocials.SingleOrDefault(s => s.Site == social.Key);
                if (userSocial != null)
                {
                    if (userSocial.Url != social.Value)
                    {
                        userSocial.Url = social.Value;
                    }
                    userSocials.Add(userSocial);
                }
                else
                {
                    userSocial = new UserSocial {
                        Username = source.Username, Site = social.Key, Url = social.Value
                    };
                    userSocials.Add(userSocial);
                }
            }
            return(userSocials);
        }
Exemple #2
0
        public async Task AddAdminWhenNoAdminPresent()
        {
            await using var context = new WebApiContext(_seeder.DbContextOptions);
            var controller = CreateController(context);

            await foreach (var user in context.Users)
            {
                user.GroupId = _userGroup.Id;
                context.Entry(user).State = EntityState.Modified;
            }

            await context.SaveChangesAsync();

            var userToAdd = new UserPostDto
            {
                Login    = "******",
                Password = "******",
                GroupId  = _adminGroup.Id
            };

            var result = await controller.PostUser(userToAdd);

            result.Result.ShouldBeAssignableTo <CreatedAtActionResult>();
            var addedUser = (UserGetDto)((CreatedAtActionResult)result.Result).Value;

            (await context.Users.FindAsync(addedUser.Id)).ShouldNotBeNull();
        }
Exemple #3
0
        public IEnumerable <UserPostDto> GetByPage(int userId, int page)
        {
            var posts = _repository.UserPost.GetByPage(userId, page, UserPostDto
                                                       .Selector(userId));

            return(posts);
        }
Exemple #4
0
        public void Get_User_Post_By_Page_Test()
        {
            var data    = GetFakeUserPosts(20);
            var service = GetService(data);
            var dtos    = data
                          .AsQueryable()
                          .Select(UserPostDto.Selector(7))
                          .Reverse()
                          .ToList();
            var controller = new UserPostController(service);
            var res        = controller.GetByPage(_userId, 1) as OkObjectResult;

            Assert.NotNull(res);

            var dataRes = res.Value as List <UserPostDto>;

            Assert.AreEqual(dtos.Count, dataRes.Count);
            for (int i = 0; i < dataRes.Count; i++)
            {
                Assert.AreEqual(dataRes.ElementAt(i).Id, dataRes.ElementAt(i).Id);
                Assert.AreEqual(dataRes.ElementAt(i).Content, dataRes.ElementAt(i).Content);
                Assert.AreEqual(dataRes.ElementAt(i).ImagePath, dataRes.ElementAt(i).ImagePath);
                Assert.AreEqual(dataRes.ElementAt(i).IsPostLikedByUser, dataRes.ElementAt(i)
                                .IsPostLikedByUser);
                Assert.AreEqual(dataRes.ElementAt(i).LikesCount, dataRes.ElementAt(i).LikesCount);
                Assert.AreEqual(dataRes.ElementAt(i).CommentsCount, dataRes.ElementAt(i)
                                .CommentsCount);
            }
        }
Exemple #5
0
        public async Task <ActionResult> RegisterUser(UserPostDto dto)
        {
            var user = await _userRepository.GetByEmail(dto.Email);

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

            user = await _userRepository.GetByUsername(dto.Username);

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

            var id      = Guid.NewGuid();
            var addedAt = DateTime.UtcNow;
            var salt    = _encrypter.GetSalt(dto.Password);
            var hash    = _encrypter.GetHash(dto.Password, salt);

            user = new User(id, dto.Username, dto.Email, hash, salt, addedAt);

            await _userRepository.Add(user);

            return(CreatedAtRoute("GetActiveUser", user));
        }
Exemple #6
0
        public async Task AddUserToUserGroupAndModifyUsingNotMatchingId()
        {
            await using var context = new WebApiContext(_seeder.DbContextOptions);
            var controller = CreateController(context);

            var userToAdd = new UserPostDto
            {
                Login    = "******",
                Password = "******",
                GroupId  = _userGroup.Id
            };

            var postResult = await controller.PostUser(userToAdd);

            postResult.Result.ShouldBeAssignableTo <CreatedAtActionResult>();

            var createdUser = (UserGetDto)((CreatedAtActionResult)postResult.Result).Value;

            var changes = new UserPutDto
            {
                Id      = createdUser.Id,
                Login   = "******",
                GroupId = _userGroup.Id,
            };

            var putResult = await controller.PutUser(createdUser.Id + 1, changes);

            putResult.ShouldBeAssignableTo <BadRequestResult>();

            var user = await context.Users.FindAsync(createdUser.Id);

            context.Users.Remove(user);
            await context.SaveChangesAsync();
        }
Exemple #7
0
        public async Task AddAdminWhenAdminPresentFails()
        {
            await using var context = new WebApiContext(_seeder.DbContextOptions);
            var controller = CreateController(context);

            var users = context.Users.ToList();

            foreach (var user in users)
            {
                user.GroupId = _userGroup.Id;
                context.Entry(user).State = EntityState.Modified;
            }

            users[new Random().Next(users.Count)].GroupId = _adminGroup.Id;

            await context.SaveChangesAsync();

            var userToAdd = new UserPostDto
            {
                Login    = "******",
                Password = "******",
                GroupId  = _adminGroup.Id
            };

            var result = await controller.PostUser(userToAdd);

            result.Result.ShouldBeAssignableTo <BadRequestResult>();

            context.Users.Count().ShouldBe(10);
        }
        public IActionResult Post([FromBody] UserPostDto userPostDto)
        {
            var user = _mapper.Map <User>(userPostDto);

            user.Role = "StandardUser";

            return(Ok(_userService.Create(user)));
        }
        public ActionResult <UserDto> Post([FromBody] UserPostDto dto)
        {
            UserDto result = _userAppService.Create(new User
            {
                UserName = dto.UserName,
                Name     = dto.Name,
            });

            return(CreatedAtAction(nameof(Get), new { id = result.Id }, result));
        }
        public ActionResult RegisterAccount([FromBody] UserPostDto user)
        {
            if (user.Name == null)
            {
                return(BadRequest());
            }
            User createdUser = _paymentRepo.AddNewUser(_mapper.Map <User>(user));

            return(Created("here", createdUser));
        }
        public async Task <UserViewDto> Login(UserPostDto user)
        {
            User record = await _context.Users.Where(u => u.EmailAddress == user.EmailAddress)
                          .FirstOrDefaultAsync();

            if (record == null)
            {
                throw new Exception("Cannot find a user using the email address entered");
            }

            using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
            {
                UTF8Encoding utf8   = new UTF8Encoding();
                byte[]       data   = sha256.ComputeHash(utf8.GetBytes(user.Password + record.Salt));
                var          result = Convert.ToBase64String(data);

                if (result != record.Hash)
                {
                    throw new Exception("Incorrect password or email address");
                }
            }

            var configurationBuilder = new ConfigurationBuilder();
            var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");

            configurationBuilder.AddJsonFile(path, false);

            var root = configurationBuilder.Build();

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(root.GetSection("AppSettings").GetSection("Encrytion").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("Id", record.ID.ToString()),
                    new Claim("EmaillAddress", record.EmailAddress.ToString()),
                    new Claim("Firstname", record.FirstName.ToString()),
                    new Claim("Lastname", record.LastName.ToString()),
                    new Claim("UserType", "System")
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var newToken = tokenHandler.CreateToken(tokenDescriptor);
            var token    = tokenHandler.WriteToken(newToken);

            UserViewDto response = new UserViewDto()
            {
                Token = token
            };

            return(response);
        }
        public async Task <UserDto> AddAsync(UserPostDto userPostDto)
        {
            var user = AutoMapper.Mapper.Map <UserPostDto, User>(userPostDto);
            await _userRepository.AddAsync(user);

            user = await _userRepository.GetSingleByUserIdAsync(user.UserId);

            var userDto = AutoMapper.Mapper.Map <User, UserDto>(user);

            //await _userElasticsearch.UpdateAsync(userDto);
            return(userDto);
        }
Exemple #13
0
        public async Task <User> AddAsync(UserPostDto entity)
        {
            UserPostDtoValidator validator = new UserPostDtoValidator();
            ValidationResult     results   = validator.Validate(entity);

            if (!results.IsValid)
            {
                throw new ValidationException("UserPostDTO", string.Join(". ", results.Errors));
            }

            return(await _repository.AddAsync(mapper.Map <User>(entity)));
        }
Exemple #14
0
 public async Task <ActionResult> Login(UserPostDto user)
 {
     try
     {
         _usersService = new UsersService(_context);
         return(Ok(JsonConvert.SerializeObject(await _usersService.Login(user))));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
Exemple #15
0
        public async Task <ActionResult <UserDto> > PostAsync([FromBody] UserPostDto dto)
        {
            var result = _mapper.Map <UserDto>(
                await _userAppService.CreateAsync(new User
            {
                UserName = dto.UserName,
                Name     = dto.Name,
            })
                );

            //返回201并添加Location标头并填充值
            return(CreatedAtAction(nameof(GetByIdAsync), new { id = result.Id }, result));
        }
Exemple #16
0
        public async Task <IActionResult> CreatePerson(UserPostDto personToAdd)
        {
            try
            {
                var guid = await _userRepository.addUser(personToAdd);

                return(guid == Guid.Empty ? (IActionResult)StatusCode(500) : Ok(guid));
            }
            catch (Exception e)
            {
                return(StatusCode(500));
            }
        }
Exemple #17
0
        public async Task <ActionResult <UserPostDto> > RegisterUser(UserPostDto user)
        {
            try
            {
                _usersService = new UsersService(_context);
                await _usersService.RegisterUser(user);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #18
0
        public async Task AddAndDeleteUserInUserGroup()
        {
            await using var context = new WebApiContext(_seeder.DbContextOptions);
            var controller = CreateController(context);

            var userToAdd = new UserPostDto
            {
                Login    = "******",
                Password = "******",
                GroupId  = _userGroup.Id
            };

            var postResult = await controller.PostUser(userToAdd);

            postResult.Result.ShouldBeAssignableTo <CreatedAtActionResult>();

            var createdUser = (UserGetDto)((CreatedAtActionResult)postResult.Result).Value;

            createdUser.Login.ShouldBe(userToAdd.Login);
            createdUser.Group.ShouldBeEquivalentTo(_userGroup);
            createdUser.State.ShouldBeEquivalentTo(_activeState);
            createdUser.CreatedDate.ShouldBeInRange(DateTime.Now - TimeSpan.FromSeconds(5), DateTime.Now);

            (await context.Users.FindAsync(createdUser.Id)).ShouldNotBeNull();
            context.Users.Count().ShouldBe(11);

            var deleteResult = await controller.DeleteUser(createdUser.Id);

            deleteResult.Result.ShouldBeAssignableTo <OkResult>();

            var deletedUsed = deleteResult.Value;

            deletedUsed.Login.ShouldBe(userToAdd.Login);
            deletedUsed.Group.ShouldBeEquivalentTo(_userGroup);
            deletedUsed.State.ShouldBeEquivalentTo(_blockedState);
            deletedUsed.CreatedDate.ShouldBe(createdUser.CreatedDate);

            (await context.Users.FindAsync(createdUser.Id)).ShouldNotBeNull();
            context.Users.Count().ShouldBe(11);

            var user = await context.Users.FindAsync(createdUser.Id);

            context.Users.Remove(user);
            await context.SaveChangesAsync();

            context.Users.Count().ShouldBe(10);
        }
Exemple #19
0
        public async Task <ActionResult <UserGetDto> > PostUser(UserPostDto user)
        {
            await using var transaction = await _context.Database.BeginTransactionAsync(IsolationLevel.Serializable);

            try
            {
                if (await _context.UserGroups.FindAsync(user.GroupId) == null)
                {
                    return(BadRequest());
                }

                if (!await _adminElevation.CanEnterGroup(user.GroupId))
                {
                    return(BadRequest());
                }

                if (!await _signupThrottler.IsSignupAllowed(user.Login))
                {
                    return(Conflict());
                }

                var activeState = await _context.GetActiveStateAsync();

                var hashed = _passwordHasher.Hash(user.Password);
                var entity = new User
                {
                    Login        = user.Login,
                    PasswordHash = hashed.Hash,
                    Salt         = hashed.Salt,
                    CreatedDate  = DateTime.Now,
                    GroupId      = user.GroupId,
                    StateId      = activeState.Id
                };

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

                await transaction.CommitAsync();

                return(CreatedAtAction("GetUser", new { id = entity.Id }, _mapper.Map <UserGetDto>(entity)));
            }
            catch (DBConcurrencyException e)
            {
                Console.WriteLine(e);
                return(Conflict());
            }
        }
Exemple #20
0
        public async Task AddUserToUserGroupAndModifyUsingMatchingId()
        {
            await using var context = new WebApiContext(_seeder.DbContextOptions);
            var controller = CreateController(context);

            var userToAdd = new UserPostDto
            {
                Login    = "******",
                Password = "******",
                GroupId  = _userGroup.Id
            };

            var postResult = await controller.PostUser(userToAdd);

            postResult.Result.ShouldBeAssignableTo <CreatedAtActionResult>();

            var createdUser = (UserGetDto)((CreatedAtActionResult)postResult.Result).Value;

            var changes = new UserPutDto
            {
                Id      = createdUser.Id,
                Login   = "******",
                GroupId = _userGroup.Id,
            };

            var putResult = await controller.PutUser(createdUser.Id, changes);

            putResult.ShouldBeAssignableTo <OkResult>();

            var getResult = await controller.GetUser(createdUser.Id);

            getResult.Result.ShouldBeAssignableTo <OkResult>();

            var changedUser = getResult.Value;

            changedUser.Id.ShouldBe(createdUser.Id);
            changedUser.Login.ShouldBe(changes.Login);
            changedUser.State.ShouldBeEquivalentTo(_activeState);
            changedUser.Group.ShouldBeEquivalentTo(_userGroup);
            changedUser.CreatedDate.ShouldBe(createdUser.CreatedDate);

            var user = await context.Users.FindAsync(createdUser.Id);

            context.Users.Remove(user);
            await context.SaveChangesAsync();
        }
Exemple #21
0
        public async Task <IHttpActionResult> Register(UserPostDto userPostDto)
        {
            if (userPostDto == null)
            {
                return(BadRequest("Missing data"));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var            userModel = Mapper.Map <UserPostDto, UserModel>(userPostDto);
            var            user      = Mapper.Map <UserPostDto, User>(userPostDto);
            IdentityResult result    = await _repo.RegisterUser(userModel);

            if (result.Succeeded)
            {
                var dbUser = await _repo.FindUser(userModel.UserName, userModel.Password);

                await _userService.AddAsync(user);

                var code = await _repo.GenerateEmailConfirmationTokenAsync(dbUser.Id);

                var callbackUrl = string.Format("{0}/account/confirm?userid={1}&code={2}", MailService, HttpUtility.UrlEncode(dbUser.Id),
                                                HttpUtility.UrlEncode(code));

                try
                {
                    await _repo.SendEmailAsync(dbUser.Id,
                                               "Confirm your account",
                                               "Please confirm your account by clicking this link: <a href=\""
                                               + callbackUrl + "\">link</a>");
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }

            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return(errorResult);
            }
            return(Ok(Mapper.Map <User, UserDto>(user)));
        }
        public async Task <IActionResult> PostUser(UserPostDto userPostDto)
        {
            if (userPostDto == null)
            {
                return(BadRequest("Missing data"));
            }
            var validator = new UserPostDtoValidation(_userService);
            var result    = validator.Validate(userPostDto);

            if (!result.IsValid)
            {
                return(BadRequest(result.Errors));
            }
            var user = await _userService.AddAsync(userPostDto);

            return(Ok(user));
        }
        public async Task RegisterUser(UserPostDto user)
        {
            Random random = new Random();
            string salt   = Encryt((random.Next(1, 999999) + random.Next(1, 999999)).ToString());
            string hash   = Encryt(user.Password + salt);

            User userCreate = new User()
            {
                FirstName    = user.FirstName,
                LastName     = user.LastName,
                EmailAddress = user.EmailAddress,
                Hash         = hash,
                Salt         = salt
            };

            _context.Users.Add(userCreate);
            await _context.SaveChangesAsync();
        }
Exemple #24
0
        public async void Post_SignUp_ValidModel_ReturnsOk()
        {
            var path = $"{BaseUri}/signup";
            var dto  = new UserPostDto()
            {
                FirstName   = "Robbe",
                LastName    = "Durnez",
                Email       = "*****@*****.**",
                Password    = "******",
                PhoneNumber = "+32497635253",
                UserType    = UserType.Customer
            };
            var json = JsonConvert.SerializeObject(dto);
            var body = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await _client.PostAsync(path, body);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
Exemple #25
0
        public async Task AddWithInvalidGroupFails()
        {
            await using var context = new WebApiContext(_seeder.DbContextOptions);
            var controller = CreateController(context);

            var maxGroupId = await context.UserGroups.MaxAsync(g => g.Id);

            var userToAdd = new UserPostDto
            {
                Login    = "******",
                Password = "******",
                GroupId  = maxGroupId + 1
            };

            var result = await controller.PostUser(userToAdd);

            result.Result.ShouldBeAssignableTo <BadRequestResult>();

            context.Users.Count().ShouldBe(10);
        }
Exemple #26
0
        public async Task <User> SignUpAsync(UserPostDto dto)
        {
            var path = $"{_baseUri}/signup";

            try
            {
                var userDto = await WebApiClient.PostCallApi <UserDto, UserPostDto>(path, dto);

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

                await SaveUserAsync(user);

                return(user);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
Exemple #27
0
        public async Task <IActionResult> Post([FromBody] UserPostDto user)
        {
            if (ModelState.IsValid == false)
            {
                return(BadRequest(ModelState));
            }

            var userCreateeDto = Mapper.Map <UserPostDto, UserCreateDto>(user);

            var result = await _userService.AddAsync(userCreateeDto);

            if (result.ErrorCategory != ErrorCategory.NoError)
            {
                return(FormatErrorResult(result.ErrorCategory, result.Message));
            }

            var userGetDto = Mapper.Map <User, UserGetDto>(result.Obj);

            return(Created($"api/Users/{userGetDto.Id}", userGetDto));
        }
Exemple #28
0
        public void Execute(UserPostDto request)
        {
            _validator.ValidateAndThrow(request);
            using (var dbContextTransaction = _context.Database.BeginTransaction())
            {
                var user = new User
                {
                    FirstName = request.FirstName,
                    LastName  = request.LastName,
                    Email     = request.Email,
                    Pass      = request.Pass,
                    PID       = request.PID,
                    RoleId    = 2
                };

                _context.Users.Add(user);
                _context.SaveChanges();

                var authUseCases = new List <int> {
                    13, 17, 23, 7, 6, 18
                };
                foreach (var useCase in authUseCases)
                {
                    var useCaseRow = new UserUseCase
                    {
                        UserId    = user.Id,
                        UseCaseId = useCase
                    };
                    _context.UserUseCases.Add(useCaseRow);
                }
                _context.SaveChanges();
                dbContextTransaction.Commit();
            }
            _sender.Send(new SendEmailDto
            {
                Content = "<h1>You are successfully registrated now!</h1>",
                SendTo  = request.Email,
                Subject = "E-store registration"
            });
        }
        public async Task Post_WhenServiceReturnsNotFound_ShouldReturn404Status()
        {
            //Arrange
            var modelStateDictionary = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            var userPostDto = new UserPostDto
            {
                BankAccount = new BankAccountDto {
                    AccountNumber = "12345678", BankName = "ABank"
                },
                Email     = "*****@*****.**",
                FirstName = "Jason",
                LastName  = "Wilson",
                Username  = "******"
            };

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(m => m.AddAsync(It.IsAny <UserCreateDto>()))
            .ReturnsAsync(
                new Core.Models.Result <Core.Models.User>
            {
                ErrorCategory = Core.Models.ErrorCategory.NotFound,
                Obj           = new Core.Models.User {
                }
            }
                );

            var usersController = new UsersController(mockUserService.Object, null);

            //Act
            var result = await usersController.Post(userPostDto);

            //Assert
            mockUserService.Verify(m => m.AddAsync(It.IsAny <UserCreateDto>()), Times.Once);
            var notFoundResult = result as NotFoundObjectResult;

            Assert.IsNotNull(notFoundResult);
            Assert.AreEqual(404, notFoundResult.StatusCode);
        }
        public async Task Post_WhenBadData_ShouldReturn400Status()
        {
            //Arrange
            var modelStateDictionary = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            var userPostDto = new UserPostDto
            {
                BankAccount = new BankAccountDto {
                    AccountNumber = "12345678", BankName = "ABank"
                },
                Email     = "*****@*****.**",
                FirstName = "Jason",
                LastName  = "Wilson",
                Username  = "******"
            };

            const string badDataMessage = "bad data";

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(m => m.AddAsync(It.IsAny <UserCreateDto>()))
            .ReturnsAsync(
                new Core.Models.Result <Core.Models.User>
            {
                ErrorCategory = Core.Models.ErrorCategory.BadData,
                Message       = badDataMessage,
                Obj           = new Core.Models.User {
                }
            }
                );

            var usersController = new UsersController(mockUserService.Object, null);

            //Act
            var result = await usersController.Post(userPostDto);

            //Assert
            mockUserService.Verify(m => m.AddAsync(It.IsAny <UserCreateDto>()), Times.Once);
            Assert.IsTrue(result is BadRequestObjectResult);
        }