예제 #1
0
        public void Execute(UserInsertDto request)
        {
            if (this.Context.Users
                .Where(g => !g.IsDeleted)
                .Any(u => u.Email == request.Email))
            {
                throw new EntityAlreadyExistsException();
            }

            if (!this.Context.Genders.Any(g => g.Id == request.GenderId))
            {
                throw new EntityNotFoundException("gender");
            }

            this.Context.Users.Add(new User
            {
                Email    = request.Email,
                Password = request.Password,
                GenderId = request.GenderId,
                IsActive = request.IsActive,
                RoleId   = request.RoleId
            });

            this.Context.SaveChanges();

            this.emailSender.Subject = "Info news";
            this.emailSender.Body    = $"You have been added by administrator. Input parameters are <br/> Email: {request.Email} <br/>Password {request.Password}";
            this.emailSender.ToEmail = request.Email;
            this.emailSender.Send();
        }
예제 #2
0
        public async Task <IActionResult> Register(UserInsertDto userInsertDto)
        {
            try
            {
                var user = Mapper.Map <User>(userInsertDto);

                user.NextPasswordUpdate = DateTimeOffset.UtcNow.AddDays(15).DateTime;
                user.Password           = Encript.HashValue(user.Password);
                user.Date = DateTimeOffset.UtcNow.Date;

                if (await UserRepository.AddAsync(user))
                {
                    var userToReturn = Mapper.Map <UserViewDto>(user);
                    userToReturn.Date = GetDateTimeZoneUser(userToReturn.Date).Value;
                    return(Created(string.Empty, userToReturn));
                }
                else
                {
                    return(BadRequest("Não foi possível concluir o seu registro, por favor tente novamente em alguns instantes"));
                }
            }
            catch (Exception ex)
            {
                return(ErrorException(ex, nameof(Register)));
            }
        }
예제 #3
0
        public async Task UpdateUser_Returns_Ok()
        {
            //Arrange
            var userInsertDto = new UserInsertDto {
                Name = "Arian", LastName = "Joan"
            };
            var user = new User {
                Name = "Arian", LastName = "Joan"
            };
            var userToUpdate = new User {
                Name = "Arian", LastName = "Provenzano"
            };
            var userDto = new UserDto {
                Name = "Arian", LastName = "Joan"
            };

            _mapperMock.Setup(u => u.Map <UserInsertDto, User>(userInsertDto)).Returns(user);
            _mapperMock.Setup(u => u.Map <User, UserDto>(userToUpdate)).Returns(userDto);
            _userRepositoryMock.Setup(u => u.GetByIdAsync(2)).ReturnsAsync(user);
            _userRepositoryMock.Setup(u => u.Update(userToUpdate));
            _unitOfWorkMock.Setup(u => u.CompleteAsync());

            //Act
            var actual = await _userService.UpdateUser(userInsertDto, 2);

            //Assert
            Assert.AreEqual(userInsertDto.Name, userDto.Name);
            Assert.AreEqual(userInsertDto.LastName, userDto.LastName);
        }
예제 #4
0
        public async Task UpdateUser_Throw_UserNotFoundException()
        {
            //Arrange
            var userInsertDto = new UserInsertDto {
                Name = "Arian", LastName = "Joan"
            };
            var user = new User {
                Name = "Arian", LastName = "Joan"
            };
            var userToUpdate = new User {
                Name = "Arian", LastName = "Provenzano"
            };
            var userDto = new UserDto {
                Name = "Arian", LastName = "Joan"
            };

            _mapperMock.Setup(u => u.Map <UserInsertDto, User>(userInsertDto)).Returns(user);
            _mapperMock.Setup(u => u.Map <User, UserDto>(userToUpdate)).Returns(userDto);
            _userRepositoryMock.Setup(u => u.GetByIdAsync(2)).ReturnsAsync((User)null);
            _userRepositoryMock.Setup(u => u.Update(userToUpdate));
            _unitOfWorkMock.Setup(u => u.CompleteAsync());

            //Act and Assert
            Assert.ThrowsAsync <UserNotFoundException>(() => _userService.UpdateUser(userInsertDto, 2));
        }
예제 #5
0
        public async Task <UserInsertDto> AddUser(UserInsertDto userDto)
        {
            var user = _mapper.Map <UserInsertDto, User>(userDto);
            await _UserRepository.AddAsync(user);

            await _unitOfWork.CompleteAsync();

            return(userDto);
        }
예제 #6
0
        public User Insert(UserInsertDto dto)
        {
            User user = new()
            {
                Login = dto.Login,
                Email = dto.Email,
                Senha = dto.Senha,
            };

            _userRepository.Insert(user);
            _userRepository.Persist();

            return(user);
        }
예제 #7
0
        /// <summary>
        /// registers user after all checks are done and hashed the password
        /// </summary>
        /// <param name="users"></param>
        /// <param name="_context"></param>
        /// <returns></returns>
        public string RegisterUser(UserInsertDto users, TodoContext _context)
        {
            _context.Users.Add(new User()
            {
                FirstName   = users.FirstName,
                LastName    = users.LastName,
                Password    = HashPassword(users.Pass),
                Email       = users.Email,
                CreatedOn   = DateTime.Now,
                IsActivated = true,
            });

            _context.SaveChanges();
            return("Registration success");
        }
예제 #8
0
        public async Task <UserDto> CreateUserAsync(UserInsertDto userDto)
        {
            var existingUser = await userRepository.GetByNameOrDefaultAsync(userDto.Name);

            if (existingUser != null)
            {
                throw new BadRequestException("a user already exist with this name");
            }
            var userToCreate = mapper.Map <DomainModels.User>(userDto);

            userToCreate.Password = userExtensionService.GetUserHashedPassword(userDto.Password);
            var createdUser = await userRepository.CreateAsync(userToCreate);

            return(mapper.Map <UserDto>(createdUser));
        }
예제 #9
0
 public ActionResult Post([FromBody] UserInsertDto value)
 {
     try
     {
         this.insertUserCommand.Execute(value);
         return(StatusCode(201));
     }
     catch (EntityAlreadyExistsException)
     {
         return(Conflict());
     }
     catch (Exception e)
     {
         return(StatusCode(500, e));
     }
 }
예제 #10
0
        public async Task <long> Insert(string contextUserEmail, UserInsertDto dto)
        {
            await ThrowIfNotInRole(contextUserEmail, UserRoleEnum.Admin);

            if (dto == null)
            {
                throw new ArgumentNullException(nameof(UserInsertDto));
            }

            var entity = dto.ToEntity();

            _context.Users.Add(entity);

            await _context.SaveChangesAsync();

            return(entity.Id);
        }
예제 #11
0
        public IActionResult Subscribe(ViewModels.User userView)
        {
            IContextFactory contextFactory = new DapperContextFactory(_configuration.GetSection("ConnectionStrings").GetSection("DB").Value);

            Models.User     user     = new Models.User(userView.Email, userView.Password, userView.Status);
            Models.HashSalt hashSalt = _authenticationService.ComputeHashSalt(user);
            Console.WriteLine(hashSalt.Hash);
            Console.WriteLine(hashSalt.Salt);
            UserInsertDto dto = new UserInsertDto(userView.Email, hashSalt.Hash, hashSalt.Salt, userView.Status);

            using (IContext context = contextFactory.Create())
            {
                _userRepository.Insert(dto, context);
                context.Commit();
                return(CreatedAtAction("subscribe", new{ userView.Email }));
            }
        }
예제 #12
0
        public async Task <IActionResult> AddUser([FromBody] UserInsertDto userDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest("The user cannot be added due to bad properties"));
                }

                var userAdded = await _userService.AddUser(userDto);

                return(Ok(userAdded));
            }
            catch (Exception ex)
            {
                return(BadRequest("The user cannot be added due to bad conection with database" + ex.Message));
            }
        }
예제 #13
0
        public void ToEntity_UserInsertDto_To_User()
        {
            var userDto = new UserInsertDto
            {
                DisplayName = "Prince Solms",
                Email       = "*****@*****.**",
                Role        = Data.Entities.UserRoleEnum.Admin
            };

            var user = userDto.ToEntity();

            var propertyExceptions = new Dictionary <string, Func <bool> >
            {
                { nameof(User.Id), () => true },
                { nameof(User.Password), () => true },
            };

            EnsureConversionThroughReflection(userDto, user, propertyExceptions);
        }
예제 #14
0
        public void Execute(UserInsertDto request)
        {
            var user = this.Context.Users.Find(request.Id);

            if (user == null)
            {
                throw new EntityNotFoundException("user");
            }
            if (user.IsDeleted)
            {
                throw new EntityNotFoundException("user");
            }

            if (!this.Context.Genders.Any(g => g.Id == request.GenderId))
            {
                throw new EntityNotFoundException("gender");
            }

            if (user.Email != request.Email)
            {
                if (this.Context.Users.Any(u => u.Email == request.Email))
                {
                    throw new EntityAlreadyExistsException("user");
                }
                else
                {
                    user.Email = request.Email;
                }
            }

            if (user.Password != request.Password)
            {
                user.Password = request.Password;
            }
            if (user.IsActive != request.IsActive)
            {
                user.IsActive = request.IsActive;
            }

            user.ModifiedAt = DateTime.Now;

            this.Context.SaveChanges();
        }
예제 #15
0
        public async Task AddUser_Returns_Ok()
        {
            //Arrange
            var user = new User {
                Name = "Arian", LastName = "Joan"
            };
            var userInsertDto = new UserInsertDto {
                Name = "Arian", LastName = "Joan"
            };

            _userRepositoryMock.Setup(u => u.AddAsync(user));
            _mapperMock.Setup(u => u.Map <UserInsertDto, User>(userInsertDto)).Returns(user);

            //Act
            var actual = await _userService.AddUser(userInsertDto);

            //Assert
            Assert.AreEqual(userInsertDto, actual);
        }
        public async Task <IActionResult> Register(UserInsertDto user)
        {
            UserValidator validator = new UserValidator();
            var           result    = validator.Validate(user);

            if (!result.IsValid)
            {
                ViewData["Uni"] = await _uniService.GetAllAsync();

                return(View("Register", user));
            }
            if (!_userService.CheckUniqueEmail(user.Email))
            {
                ModelState.AddModelError("Email", "This mail address already exists");
                ViewData["Uni"] = await _uniService.GetAllAsync();

                return(View("Register", user));
            }
            user.PasswordHash = Crypto.HashPassword(user.PasswordHash);
            var dbUser = _mapper.Map <AppUser>(user);

            dbUser.UserName = dbUser.Email;
            await _userService.AddAsync(dbUser);

            //await _userManager.CreateAsync(dbUser,dbUser.PasswordHash);
            var test = await _userManager.AddToRoleAsync(dbUser, "author");

            var token = await _userManager.GenerateEmailConfirmationTokenAsync(dbUser);

            var confLink = Url.Action("ConfEmail", "Account",
                                      new { userId = dbUser.Id, tok = token }, Request.Scheme);
            EmailSender email = new EmailSender();

            try
            {
                await email.SendEmailAsync(user.Email, "Confirmation Email", confLink);
            }
            catch (Exception err)
            {
            }
            return(RedirectToAction("Index", "Home"));
        }
예제 #17
0
        public async Task <IActionResult> RegisterUser([FromBody] UserInsertDto user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (!user.Email.Contains("@"))
            {
                return(StatusCode(409, "E-mail is invalid"));
            }

            if (!user.Email.Contains("."))
            {
                return(StatusCode(409, "E-mail is invalid"));
            }

            if (_context.Users.Any(e => e.Email == user.Email))
            {
                return(StatusCode(409, "E-mail is already registered"));
            }



            Register RegisterHandler = new Register();

            try
            {
                return(Ok(RegisterHandler.RegisterUser(new UserInsertDto()
                {
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    Email = user.Email,
                    Pass = user.Pass,
                }, _context)));
            }
            catch (Exception e)
            {
                throw;
            }
        }
예제 #18
0
        public void Insert(UserInsertDto dto, IContext context)
        {
            if (dto == null)
            {
                throw new ArgumentNullException(nameof(dto));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            const string sql = @"insert into dbo.Users (Email, Hash, Salt, Status)
                                values(@Email, @Hash, @Salt, @Status)";

            context.Execute(sql, new
            {
                dto.Email,
                dto.Hash,
                dto.Salt,
                dto.Status
            });
        }
예제 #19
0
        public async Task <UserDto> UpdateUser(UserInsertDto userDto, int id)
        {
            var user = _mapper.Map <UserInsertDto, User>(userDto);

            var userToUpdate = await _UserRepository.GetByIdAsync(id);

            if (userToUpdate == null)
            {
                throw new UserNotFoundException(id.ToString());
            }

            userToUpdate.Name     = user.Name;
            userToUpdate.LastName = user.LastName;

            _UserRepository.Update(userToUpdate);
            await _unitOfWork.CompleteAsync();

            var userUpdated = _mapper.Map <User, UserDto>(userToUpdate);

            return(userUpdated);
        }
예제 #20
0
        public async Task <IActionResult> Post([FromBody] UserInsertDto dto)
        {
            var trans = await _userService.BeginTransactionAsync();

            try
            {
                var id = await _userService.Insert(ContextUserEmail, dto);

                trans.Commit();

                var data = await _userService.Find(x => x.Id == id);

                return(Ok(data));
            }
            catch (Exception e)
            {
                trans.Rollback();

                return(Exception(e));
            }
        }
예제 #21
0
 public ActionResult Put(int id, [FromBody] UserInsertDto value)
 {
     try
     {
         value.Id = id;
         this.updateUserCommand.Execute(value);
         return(NoContent());
     }
     catch (EntityNotFoundException)
     {
         return(NotFound());
     }
     catch (EntityAlreadyExistsException)
     {
         return(Conflict());
     }
     catch (Exception)
     {
         return(StatusCode(500));
     }
 }
예제 #22
0
        public UserDto Insert(UserInsertDto dto)
        {
            UserDto userDto = null;

            try
            {
                var user = Mapper.Map <UserInsertDto, User>(dto);

                _unitOfWork.CreateTransaction();

                _unitOfWork.GenericRepository <User>().Insert(user);
                _unitOfWork.Save();

                _unitOfWork.Commit();

                userDto = Mapper.Map <User, UserDto>(user);
            }
            catch (Exception ex)
            {
                Tracing.SaveException(ex);
                _unitOfWork.Rollback();
            }
            return(userDto);
        }
예제 #23
0
        public async Task <IActionResult> UpdateUser([FromBody] UserInsertDto newUser, [FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("The user cannot be updated due to bad properties"));
            }

            try
            {
                var userUpdated = await _userService.UpdateUser(newUser, id);

                return(Ok(userUpdated));
            }

            catch (UserNotFoundException ex)
            {
                return(NotFound(ex.Message));
            }

            catch (Exception ex)
            {
                return(BadRequest("The user cannot be updated due to bad conection with database" + ex.Message));
            }
        }
예제 #24
0
        public IActionResult Insert(UserInsertDto dto)
        {
            User user = _aplicUser.Insert(dto);

            return(Created("", user));
        }
예제 #25
0
 public async Task <IActionResult> Register(UserInsertDto userInsertDto)
 {
     return(Ok());
 }
예제 #26
0
        public async Task <ActionResult <UserDto> > CreateAsync([FromBody] UserInsertDto user)
        {
            var createdUser = await userService.CreateUserAsync(user);

            return(Created($"/api/users/${createdUser.Id}", createdUser));
        }