public void ValidRegisterShouldCreateANewUser() { var options = new DbContextOptionsBuilder <UsersDbContext>() .UseInMemoryDatabase(databaseName: "ValidRegisterShouldCreateANewUser") .Options; using (var context = new UsersDbContext(options)) { var usersService = new UsersService(context, registerValidator, config); var added = new PostUserDto { FirstName = "test_firstName", LastName = "test_lastName", Username = "******", Password = "******" }; var result = usersService.Register(added); Assert.IsNull(result); var newUser = context.Users.Last(); Assert.AreEqual(added.FirstName, newUser.FirstName); Assert.AreEqual(added.LastName, newUser.LastName); Assert.AreEqual(added.Username, newUser.Username); } }
public void GetAllShouldReturnAllUsers() { var options = new DbContextOptionsBuilder <UsersDbContext>() .UseInMemoryDatabase(databaseName: nameof(GetAllShouldReturnAllUsers)) .Options; using (var context = new UsersDbContext(options)) { var usersService = new UsersService(context, registerValidator, config); var added1 = new PostUserDto { FirstName = "aaaaa", LastName = "bbbbb", Username = "******", Password = "******" }; var added2 = new PostUserDto { FirstName = "ccccc", LastName = "ddddd", Username = "******", Password = "******" }; usersService.Register(added1); usersService.Register(added2); int numberOfElements = usersService.GetAll().Count(); Assert.NotZero(numberOfElements); Assert.AreEqual(2, numberOfElements); } }
public void TestNewPost() { PostUserDto pdto = new PostUserDto("Test", "Test de tests"); var test = _postUserController.CreatePostUser(pdto); Assert.NotNull((test as ObjectResult).StatusCode); }
public void DeleteShouldDeleteUser() { var options = new DbContextOptionsBuilder <UsersDbContext>() .UseInMemoryDatabase(databaseName: nameof(DeleteShouldDeleteUser)) .Options; using (var context = new UsersDbContext(options)) { var UsersService = new UsersService(context, registerValidator, config); var newUser = new PostUserDto { FirstName = "toDel", LastName = "toDel", Password = "******", Username = "******" }; UsersService.Register(newUser); User addedUser = context.Users.Last(); context.Entry(addedUser).State = EntityState.Detached; //var addedUser = context.Users.Where(u => u.Username == "alina3").FirstOrDefault(); UsersService.DeleteUser(addedUser.Id); int users = UsersService.GetAll().Count(); Assert.Zero(users); } }
public async Task <KorisnikDto> PostUser(PostUserDto postUser) { var user = new Korisnik() { UserName = postUser.UserName, Ime = postUser.Ime, Prezime = postUser.Prezime, Email = postUser.Email, Slika = postUser.Slika, EmailConfirmed = true, LockoutEnabled = true, SecurityStamp = Guid.NewGuid().ToString(), Lozinka = postUser.Lozinka }; await _userManager.CreateAsync(user, user.Lozinka); await _userManager.AddToRoleAsync(user, "korisnik"); await _context.SaveChangesAsync(); var korisnik = _mapper.Map <KorisnikDto>(user); return(korisnik); }
public async Task <IActionResult> Token([FromForm] PostUserDto userDto) { _logger.LogInformation("Invoked api/Accounts/token"); ClaimsIdentity identity = await GetIdentity(userDto.Username, userDto.Password); if (identity == null) { return(StatusCode(400, new { Message = "Invalid username or password." })); } var now = DateTime.UtcNow; // create token var jwt = new JwtSecurityToken( issuer: _authOptions.Issuer, audience: _authOptions.Audience, notBefore: now, claims: identity.Claims, expires: now.Add(TimeSpan.FromMinutes(_authOptions.Lifetime)), signingCredentials: new SigningCredentials( new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_authOptions.SecretKey)), SecurityAlgorithms.HmacSha256)); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, username = identity.Name }; return(StatusCode(200, new { access_token = response.access_token, username = response.username })); }
public IActionResult Put(int id, [FromBody] PostUserDto userNew) { User addedBy = userService.GetCurrentUser(HttpContext); var result = userService.Upsert(id, userNew, addedBy); return(Ok(result)); }
public void AuthenticateShouldLoginAUser() { var options = new DbContextOptionsBuilder <UsersDbContext>() .UseInMemoryDatabase(databaseName: nameof(AuthenticateShouldLoginAUser)) .Options; using (var context = new UsersDbContext(options)) { var usersService = new UsersService(context, registerValidator, config); var added = new PostUserDto { FirstName = "test_first", LastName = "test_last", Username = "******", Password = "******" }; var result = usersService.Register(added); var authenticated = new PostLoginDto { Username = "******", Password = "******" }; var authresult = usersService.Authenticate(added.Username, added.Password); Assert.IsNotNull(authresult); Assert.AreEqual(authenticated.Username, authresult.Username); } }
public void TestChangePostLikeNumber() { PostUserDto pdto = new PostUserDto("Test", "Test de tests"); var test = _postUserController.CreatePostUser(pdto); var addLike = _postUserController.LikePostUser(((test as OkObjectResult).Value as PostsUser).postId); Assert.Equal(1, ((addLike as OkObjectResult).Value as PostsUser).postLike); }
public IActionResult Register([FromBody] PostUserDto registerModel) { var errors = _userService.Register(registerModel); //, out User user); if (errors != null) { return(BadRequest(errors)); } return(Ok()); //user); }
public IActionResult Post([FromBody] PostUserDto userNew) { var user = _userService.Create(userNew); if (user == null) { return(BadRequest(user)); } return(Ok()); }
public async Task <IActionResult> Post(PostUserDto user) { try { return(Ok(await _userService.AddUser(user))); } catch (System.Exception) { return(BadRequest()); } }
public void TestMultiplePostUnlikeNumber() { PostUserDto pdto = new PostUserDto("Test", "Test de tests"); var test = _postUserController.CreatePostUser(pdto); var addLike1 = _postUserController.LikePostUser(((test as OkObjectResult).Value as PostsUser).postId); var addLike2 = _postUserController.LikePostUser(((test as OkObjectResult).Value as PostsUser).postId); var addLike3 = _postUserController.LikePostUser(((test as OkObjectResult).Value as PostsUser).postId); var unlike = _postUserController.UnlikePostUser(((test as OkObjectResult).Value as PostsUser).postId); Assert.Equal(2, ((unlike as OkObjectResult).Value as PostsUser).postLike); }
public IActionResult CreatePostUser([FromBody] PostUserDto pu) { var post = pu.CreatePostUser(); if (post != null) { _maBd.PostsUser.Add(post); _maBd.SaveChanges(); return(new OkObjectResult(post)); } return(new ObjectResult(null)); }
public IActionResult Put(int id, [FromBody] PostUserDto userNew) { //User addedBy = _userService.GetCurrentUser(HttpContext); // var result = _userService.Upsert(id, userNew, addedBy); User currentLogedUser = _userService.GetCurrentUser(HttpContext); var regDate = currentLogedUser.CreatedAt; var currentDate = DateTime.Now; var minDate = currentDate.Subtract(regDate).Days / (365 / 12); if (currentLogedUser.UserRole == UserRole.UserManager) { User getUser = _userService.GetById(id); if (getUser == null) { return(NotFound()); } } if (currentLogedUser.UserRole == UserRole.UserManager) { User getUser = _userService.GetById(id); if (getUser.UserRole == UserRole.Admin) { return(Forbid()); } } if (currentLogedUser.UserRole == UserRole.UserManager) { User getUser = _userService.GetById(id); if (getUser.UserRole == UserRole.UserManager && minDate <= 6) { return(Forbid()); } } if (currentLogedUser.UserRole == UserRole.UserManager) { User getUser = _userService.GetById(id); if (getUser.UserRole == UserRole.UserManager && minDate >= 6) { var result1 = _userService.Upsert(id, userNew); return(Ok(result1)); } } var result = _userService.Upsert(id, userNew); return(Ok(result));; }
public IActionResult ModifyPostUser([FromBody] PostUserDto updatedPost, int id) { var post = _maBd.PostsUser.FirstOrDefault(m => m.postId == id); if (post == null) { return(new ObjectResult(null)); } _maBd.Entry(post).CurrentValues.SetValues(updatedPost); _maBd.SaveChanges(); return(new OkObjectResult(post)); }
public async Task <ActionResult> RegisterUser([FromForm] PostUserDto userDto) { _logger.LogInformation("Invoked api/Accounts/register"); CoreModels.User coreUser = _mapper.Map <CoreModels.User>(userDto); bool isCreated = await _userService.AddUserAsync(coreUser, userDto.Password); if (isCreated) { return(StatusCode(201)); } return(StatusCode(400)); }
public void Setup() { config = Options.Create(new AppSettings { Secret = "adlkfadlkasfaskldffalaksfaDFLKAjdflkadjfaldkfjsd" }); registerValidator = new RegisterValidator(); user = new PostUserDto { FirstName = "user_test_big", LastName = "user_test_big", Username = "******", Password = "******" }; }
public async Task <IActionResult> Post([FromBody] PostUserDto postUserDto) { try { var serviceResult = await _userservice.CreateUser(postUserDto.Name, postUserDto.Password, (int)postUserDto.UserType); if (!serviceResult.Success) { return(BadRequest(serviceResult.ValidationMessages)); } var result = _mapper.Map <UserDto>(serviceResult.Result); return(Created($"User: {result.UserId}", result)); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
public GetUserDto Register(PostUserDto registerInfo) { User existing = context.Users.FirstOrDefault(u => u.Username == registerInfo.Username); if (existing != null) { return(null); } context.Users.Add(new User { LastName = registerInfo.LastName, FirstName = registerInfo.FirstName, Password = ComputeSha256Hash(registerInfo.Password), Username = registerInfo.Username }); context.SaveChanges(); return(Authenticate(registerInfo.Username, registerInfo.Password)); }
public void userIsValid(PostUserDto user) { var errorMessagesList = new List <string> { }; if (user.Username == null) { errorMessagesList.Add("Username cannot be empty"); } if (user.Name == null) { errorMessagesList.Add("Name cannot be empty"); } string pattern = null; pattern = "^[0-9]{10}$"; if (!Regex.IsMatch(user.PhoneNumber, pattern)) { errorMessagesList.Add("Invalid Phone, must have 10 digits"); } try { MailAddress m = new MailAddress(user.Email); } catch (System.Exception) { errorMessagesList.Add("Invalid Format Email"); } pattern = "^[a-zA-Z0-9]{3,}$"; if (!Regex.IsMatch(user.Password, pattern)) { errorMessagesList.Add("Invalid format password, minimun 4 length"); } if (errorMessagesList.Count() != 0) { string errorMessages = string.Join(",", errorMessagesList); throw new Exception(errorMessages); } }
public ErrorsCollection Register(PostUserDto registerInfo) { var errors = registerValidator.Validate(registerInfo, context); if (errors != null) { return(errors); } context.Users.Add(new User { LastName = registerInfo.LastName, FirstName = registerInfo.FirstName, Password = ComputeSha256Hash(registerInfo.Password), Username = registerInfo.Username, UserRole = UserRole.Regular }); context.SaveChanges(); //return Authenticate(registerInfo.Username, registerInfo.Password); return(null); }
public IActionResult CreateUser([FromBody] PostUserDto user) { if (user == null) { return(BadRequest()); } var userEntity = mapper.Map <UserEntity>(user); userEntity = userRepository.Insert(userEntity); if (!ModelState.IsValid) { return(UnprocessableEntity(ModelState)); } return(CreatedAtRoute( nameof(GetUserById), new { userId = userEntity.Id }, userEntity.Id )); }
public ErrorsCollection Validate(PostUserDto postUserDto, UsersDbContext usersDbContext) { ErrorsCollection errorsCollection = new ErrorsCollection { Entity = nameof(postUserDto) }; User existing = usersDbContext.Users.FirstOrDefault(u => u.Username == postUserDto.Username); if (existing != null) { errorsCollection.ErrorMessages.Add($"Username {postUserDto.Username} is already used!"); } if (postUserDto.Password.Length < 6) { errorsCollection.ErrorMessages.Add("The password has to have > 5 chars"); } int numberOfDigits = 0; foreach (char c in postUserDto.Password) { if (c >= '0' && c <= '9') { numberOfDigits++; } } if (numberOfDigits < 2) { errorsCollection.ErrorMessages.Add("The password must contain at least 2 digits"); } if (errorsCollection.ErrorMessages.Count > 0) { return(errorsCollection); } return(null); }
public ErrorsCollection Register(PostUserDto registerInfo) { var errors = registerValidator.Validate(registerInfo, context); if (errors != null) { return(errors); } User userToAdd = new User { LastName = registerInfo.LastName, FirstName = registerInfo.FirstName, Password = ComputeSha256Hash(registerInfo.Password), Username = registerInfo.Username, UserUserRoles = new List <UserUserRole>(), DateAdded = DateTime.Now }; var regularRole = context .UserRoles .FirstOrDefault(ur => ur.Name == UserRoles.Regular); context.Users.Add(userToAdd); //context.SaveChanges(); context.UserUserRoles.Add(new UserUserRole { User = userToAdd, UserRole = regularRole, StartTime = DateTime.Now, EndTime = null }); context.SaveChanges(); //return Authenticate(registerInfo.Username, registerInfo.Password); return(null); }
public async Task <ResponseService <GetUserDto> > AddUser(PostUserDto user) { var response = new ResponseService <GetUserDto>(); try { new ObjectValidation().userIsValid(user); User userTrueFormat = _mapper.Map <User>(user); User userExist = _context.Users.FirstOrDefault(u => u.Username == user.Username || u.Email == user.Email); if (userExist != null) { throw new System.Exception("User Already exist"); } CreatePasswordHash(user.Password, out byte[] passwordHash, out byte[] passwordSalt); userTrueFormat.PasswordHash = passwordHash; userTrueFormat.Salt = passwordSalt; await _context.Users.AddAsync(userTrueFormat); await _context.SaveChangesAsync(); response.Data = _mapper.Map <GetUserDto>(user); response.Success = true; response.Message = "User creation successfull!"; } catch (System.Exception ex) { response.Success = false; response.Message = ex.Message; } return(response); }
public IActionResult Register([FromBody] PostUserDto registerModel) { var user = _userService.Register(registerModel); return(Ok(user)); }
public async Task <KorisnikDto> AddUser(PostUserDto postUser) { var user = await _service.PostUser(postUser); return(user); }