Exemplo n.º 1
0
        public void Add(AddUserDto dto)
        {
            var user = dto.MapTo <User>();

            AddAndSave(user);
            SaveChanges();
        }
Exemplo n.º 2
0
        public void Execute(AddUserDto request)
        {
            if (Context.Users.Any(u => u.Username.ToLower() == request.Username.ToLower()))
            {
                throw new EntityAlreadyExistsException("User with that username");
            }

            if (Context.Users.Any(u => u.Email.ToLower() == request.Email.ToLower()))
            {
                throw new EntityAlreadyExistsException("User with that email");
            }

            if (request.Password != request.ConfirmPassword)
            {
                throw new EntityMustHaveConfirmedPassword("Password fields must match.");
            }

            Context.Users.Add(new User
            {
                FirstName = request.FirstName,
                LastName  = request.LastName,
                Username  = request.Username,
                Email     = request.Email,
                Password  = request.Password,
                RoleId    = request.RoleId
            });

            Context.SaveChanges();
        }
Exemplo n.º 3
0
        public async Task <CreationState> AddUserAsnc(AddUserDto addUserDto)
        {
            var creationState = new CreationState {
                IsCreatedSuccessfully = false, CreatedObjectId = null
            };

            var checkUsersAddedBefore = await _unitOfWork.UserRepository.FindElementAsync(x => x.Email == addUserDto.Email || x.PhoneNumber == addUserDto.PhoneNumber);

            if (checkUsersAddedBefore == null)
            {
                var newUser = _mapper.Map <AddUserDto, UsersProfile>(addUserDto);
                await _unitOfWork.UserRepository.CreateAsync(newUser);

                creationState.IsCreatedSuccessfully = await _unitOfWork.SaveAsync() > 0;

                creationState.CreatedObjectId = newUser.Id;

                string extention = Path.GetExtension(addUserDto.File.FileName);
                string path      = _hostEnvironment.WebRootPath + "/Uploads/" + newUser.Id + extention;
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await addUserDto.File.CopyToAsync(stream);
                }
            }
            else
            {
                creationState.ErrorMessages.Add("This user added before");
            }

            return(creationState);
        }
Exemplo n.º 4
0
        public async Task <UserClaimsDto> Register(AddUserDto userDto)
        {
            if (await _genericRepository.FindBy(x => x.Email == userDto.Email).AnyAsync())
            {
                return(null);
            }

            User user = new User {
                UserName = userDto.Username, Email = userDto.Email
            };

            if (!string.IsNullOrEmpty(userDto.Password))
            {
                byte[] passwordHash, passwordSalt;
                HashSaltHelper.GeneratePasswordHashAndSalt(userDto.Password, out passwordHash, out passwordSalt);

                user.PasswordHash = passwordHash;
                user.PasswordSalt = passwordSalt;

                await _genericRepository.Add(user);

                return(_mapper.Map <UserClaimsDto>(user));
            }

            return(null);
        }
Exemplo n.º 5
0
        public async Task <ServiceResponse <List <GetUserDto> > > AddUser(AddUserDto newUser)
        {
            ServiceResponse <List <GetUserDto> > serviceResponse = new ServiceResponse <List <GetUserDto> >();

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

            user.DateCreated = DateTime.Now.ToUniversalTime().ToString();
            Guid g = Guid.NewGuid();

            user.ActivateKey = g.ToString().Replace("-", "");
            //user.Password = BC.HashPassword(newUser.Password);
            user.PasswordHash = customPasswordHasher.HashPassword(newUser.Password);
            user.Status       = UserStatus.Disabled;

            try
            {
                await _context.Users.AddAsync(user);

                await _context.SaveChangesAsync();

                serviceResponse.Data = (_context.Users.Select(u => _mapper.Map <GetUserDto>(u))).ToList();
            }
            catch (System.Exception ex)
            {
                serviceResponse.Success = false;
                serviceResponse.Message = ex.ToString();
            }

            return(serviceResponse);
        }
Exemplo n.º 6
0
 public ActionResult Create(AddUserDto dto)
 {
     if (!ModelState.IsValid)
     {
         TempData["error"] = Messages.INPUT_ERROR;
         return(RedirectToAction(nameof(Create)));
     }
     try
     {
         executor.ExecuteCommand(addUser, dto);
         addUserCases.Execute(dto.Username);
         TempData["success"] = Messages.USER_CREATE_SUCCESS;
         return(RedirectToAction(nameof(Index)));
     }
     catch (EntityNotAllowedException)
     {
         return(RedirectToAction("PageNotFound", "Redirections"));
     }
     catch (EntityAlreadyExistsException e)
     {
         TempData["error"] = e.Message;
     }
     catch (Exception)
     {
         TempData["error"] = Messages.USER_CREATE_ERROR;
     }
     return(RedirectToAction("Create"));
 }
Exemplo n.º 7
0
        public void Execute(AddUserDto request)
        {
            if (Context.Users.Any(c => c.Username == request.UserName))
            {
                throw new EntityAlreadyExists();
            }

            Context.Add(new Domen.User
            {
                Username   = request.UserName,
                Email      = request.Email,
                Password   = request.Password,
                UserTypeId = request.userType
            });



            Context.SaveChanges();
            var email = request.Email;

            _emailSender.Subject = "Uspesna registracija";
            _emailSender.Body    = "Uspesno ste se registrovali.";
            _emailSender.ToEmail = email;
            _emailSender.Send();
        }
Exemplo n.º 8
0
 public IActionResult Post([FromBody] AddUserDto dto)
 {
     try
     {
         addUser.Execute(dto);
         return(StatusCode(201));
     }
     catch (EntityAlreadyExistsException e)
     {
         return(StatusCode(409, new
         {
             Errors = new List <string> {
                 e.Message
             }
         }));
     }
     catch (Exception e)
     {
         return(StatusCode(500, new
         {
             Errors = new List <string> {
                 e.Message
             }
         }));
     }
 }
Exemplo n.º 9
0
        public void Execute(AddUserDto reqest)
        {
            if (context.Users.Any(u => u.Email == reqest.Email))
            {
                throw new AlreadyExistsEx("User with this email already exists");
            }

            if (!context.Roles.Any(r => r.Id == reqest.RoleId))
            {
                throw new NotFoundEx();
            }

            var user = new User
            {
                FirstName = reqest.FirstName,
                LastName  = reqest.LastName,
                Email     = reqest.Email,
                Password  = reqest.Password,
                RoleId    = reqest.RoleId
            };

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

            emailer.Subject = "Server Message";
            emailer.Body    = "A User has been created and added to the database";
            emailer.ToEmail = "*****@*****.**";
            emailer.Send();
        }
Exemplo n.º 10
0
        public async Task <IActionResult> UpdateUser(int updatedById, [FromBody] AddUserDto userDto)
        {
            if (userDto == null || updatedById <= 0)
            {
                _logger.LogError("User or UpdatedByUserId cannot be zero or null");
                return(BadRequest(new ResponseMessages {
                    Message = "User Is Null", status = "400"
                }));
            }
            var userEntity = _mapper.Map <User>(userDto);
            var userVal    = await _userManager.Update(userEntity);

            if (userVal != 0)
            {
                var updatedUser = _mapper.Map <AddUserDto>(userVal);
                _logger.LogInfo($"Update user successfully  as login id :{updatedUser.LoginId} and updated by userid : {updatedById}");
                return(CreatedAtRoute("UserById", new { userid = updatedUser.userId }, updatedUser));
            }
            else
            {
                return(BadRequest(new ResponseMessages {
                    Message = "User Not Updated", status = "400"
                }));
            }
        }
Exemplo n.º 11
0
        public async Task <IActionResult> RegisterUser([FromBody] AddUserDto userDto)
        {
            if (userDto == null)
            {
                _logger.LogError("User Object cannot be zero or null");
                return(BadRequest(new ResponseMessages {
                    Message = "User is null ", status = "400"
                }));
            }
            var userEntity = _mapper.Map <User>(userDto);
            var userVal    = await _userManager.Add(userEntity);

            if (userVal != 0)
            {
                //var createdUser = _mapper.Map<AddUserDto>(userEntity);
                _logger.LogInfo($"New created user as login ID : {userEntity.LoginID}");
                //return CreatedAtRoute("UserById", new { userid = createdUser.userId }, createdUser);
                return(Ok(new ResponseMessages {
                    Message = "User Created Successfully", status = "200"
                }));
            }
            else
            {
                return(BadRequest(new ResponseMessages {
                    Message = "User Not Created ", status = "400"
                }));
            }
        }
Exemplo n.º 12
0
        public async Task <IActionResult> AddAdmin([FromBody] AddUserDto userDto)
        {
            var a = CurrentUserId;
            await _userService.AddAdmin(userDto);

            return(Ok());
        }
Exemplo n.º 13
0
        private async Task CompleteUserCreation(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                ErrorMessage = "Invalid external code. Please try again later";
            }

            // redirect url should not be encoded
            var data = await _apiClient.ExchangeCodeAsync(code, _discordOAuth.RedirectUrl);

            if (data?.User == null || data.User.Id == 0)
            {
                ErrorMessage = "Failed to communicate with Discord servers. Please try again later";
                return;
            }
            else
            {
                var dto = new AddUserDto()
                {
                    Code          = code,
                    HardwareId    = state,
                    DiscordUserId = data.User.Id
                };

                ApiUser apiUser = await _apiUserService.GetOrAddAsync(dto);

                ApiKey = apiUser.ApiKey;
            }
        }
Exemplo n.º 14
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.Password == model.ConfirmPassword)
                {
                    var UserExist = await _userService.IsUserExistAsync(model.Email, model.Password);

                    if (!UserExist)
                    {
                        AddUserDto userDto = new AddUserDto(model.Email, model.Password);
                        await _userService.AddUserAsync(userDto);

                        var PersonId = _userService.GetPersonId(model.Email).ToString();
                        _authenticationService.AuthorizeContext(HttpContext.GetOwinContext(), _authenticationService.CreateClaim(PersonId));
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "User with this Email already exist!");
                    }
                }
            }
            return(View(model));
        }
Exemplo n.º 15
0
        public static ResponseDto <int> ValidateAddUser(AddUserDto userToAdd, User user)
        {
            var response = new ResponseDto <int>();

            if (user != null)
            {
                response.AddError(UserErrors.LoginTaken);
            }
            if (string.IsNullOrEmpty(userToAdd.Login))
            {
                response.AddError(UserErrors.EmptyLogin);
            }
            if (string.IsNullOrEmpty(userToAdd.Email))
            {
                response.AddError(UserErrors.EmptyEmail);
            }
            if (string.IsNullOrEmpty(userToAdd.FirstName))
            {
                response.AddError(UserErrors.EmptyFirstName);
            }
            if (string.IsNullOrEmpty(userToAdd.LastName))
            {
                response.AddError(UserErrors.EmptyLastName);
            }

            if (!new EmailAddressAttribute().IsValid(userToAdd.Email))
            {
                response.AddError(UserErrors.EmailInvalid);
            }

            return(response);
        }
Exemplo n.º 16
0
        public ActionResult UserSignup(UserSignupViewModel model)
        {
            try
            {
                AddUserDto dto = new AddUserDto();


                dto.UserName     = model.UserName;
                dto.UserPassword = CommonTools.ToMd5(model.UserPassword);
                dto.UserRoles    = model.UserRoles;
                dto.UserStatus   = true;


                string  userJsonString = JsonHelper.JsonSerializerBySingleData(dto);
                Message msg            = CMSService.Insert("User", userJsonString);

                // return RedirectTo("/Login/Login", msg.MessageInfo);
                return(RedirectToAction("Login", "Login", new { ac = "SignupSuccess" }));
            }

            catch
            {
                Message msg = new Message();
                msg.MessageStatus = "Error";
                msg.MessageInfo   = "注册失败了";
                ViewBag.Status    = msg.MessageStatus;
                ViewBag.msg       = msg.MessageInfo;
                return(View("Login"));
            }
        }
        public ActionResult <UserDto> AddNewUser(AddUserDto userDto)
        {
            User user = _mapper.Map <User>(userDto);

            _repository.AddUser(user);
            return(Ok(_mapper.Map <UserDto>(user)));
        }
Exemplo n.º 18
0
        public async Task <ApplicationResponse <bool> > AddUser(AddUserDto addUserDto)
        {
            var isValidUser = await _userRepository.GetAsync(x => x.EMail == addUserDto.EMail);

            if (isValidUser is not null)
            {
                return(new ApplicationResponse <bool>(ResponseState.Error, ResponseMessage.Error.ValidUser));
            }

            var company = await _companyRepository.GetAsync(x => x.Id == addUserDto.CompanyId);

            if (company is null)
            {
                return(new ApplicationResponse <bool>(ResponseState.Error, ResponseMessage.Error.CompanyNotFound));
            }

            // test kullanıcı olarak eklendi, kaldırılacaktır
            var salt         = SecurityHelper.GenerateSalt(70);
            var hashPassword = SecurityHelper.HashPassword(addUserDto.Password, salt);

            var mongoUser = new User
            {
                EMail        = addUserDto.EMail,
                Password     = hashPassword,
                PasswordSalt = salt,
                Name         = addUserDto.Name,
                Surname      = addUserDto.Surname,
                Company      = company
            };

            await _userRepository.AddAsync(mongoUser);

            return(new ApplicationResponse <bool>(true));
        }
Exemplo n.º 19
0
        public ActionResult Create(UserAddViewModel model)
        {
            try
            {
                AddUserDto dto = new AddUserDto();


                dto.UserName     = model.UserName;
                dto.UserPassword = CommonTools.ToMd5(model.UserPassword);
                dto.UserRoles    = "45";
                dto.UserStatus   = true;
                string  userJsonString = JsonHelper.JsonSerializerBySingleData(dto);
                Message msg            = CMSService.Insert("User", userJsonString);
                return(RedirectTo("/User/Index", msg.MessageInfo));
            }

            catch
            {
                Message msg = new Message();
                msg.MessageStatus = "Error";
                msg.MessageInfo   = "操作出错了";
                ViewBag.Status    = msg.MessageStatus;
                ViewBag.msg       = msg.MessageInfo;
                return(View());
            }
        }
Exemplo n.º 20
0
        public async Task <ApiUser> GetOrAddAsync(AddUserDto addUserDto)
        {
            var existing = await _users.Value.Find(u => u.Discord.UserId == addUserDto.DiscordUserId).SingleOrDefaultAsync();

            if (existing != null)
            {
                return(existing);
            }

            var apiUser = new ApiUser()
            {
                ApiKey    = Guid.NewGuid().ToString(),
                CreatedAt = 0,
                Discord   = new DiscordAccount()
                {
                    UserId = addUserDto.DiscordUserId
                },
                HardwareIds =
                {
                    addUserDto.HardwareId
                },
                Id       = Guid.NewGuid(),
                IsBanned = false
            };

            await _users.Value.InsertOneAsync(apiUser);

            return(apiUser);
        }
Exemplo n.º 21
0
        public async Task <UserResponse> AddUser(AddUserDto userDto)
        {
            // Check if name already exists
            var exists = await UserExistsByEmail(userDto.Email);

            if (exists != null)
            {
                throw new Exception("Conflict");
            }

            var newUser = new User
            {
                FirstName = userDto.FirstName,
                LastName  = userDto.LastName,
                Email     = userDto.Email,
                Password  = userDto.Password
            };

            newUser.Password = GeneratePasswordHash(newUser, newUser.Password);
            await _context.Users.AddAsync(newUser);

            await _context.SaveChangesAsync();

            return(newUser.ToDTO());
        }
Exemplo n.º 22
0
        public async Task <CreationState> AddUserAsync(AddUserDto addUserDto)
        {
            var creationState = new CreationState {
                IsCreatedSuccessfully = false, CreatedObjectId = null
            };

            try
            {
                //Identity User Mapping
                var newUserIdentity       = _mapper.Map <AddUserDto, IdentityUser>(addUserDto);
                var checkUsersAddedBefore = await _unitOfWork.UserRepository.FindElementAsync(x => x.Email == addUserDto.Email || x.PhoneNumber == addUserDto.PhoneNumber);

                if (checkUsersAddedBefore == null)
                {
                    //Adding User
                    var result = await _userManager.CreateAsync(newUserIdentity, addUserDto.Password);

                    //Check  If User Added
                    if (result.Succeeded)
                    {
                        var userId  = Guid.Parse(await _userManager.GetUserIdAsync(newUserIdentity));
                        var newUser = _mapper.Map <AddUserDto, UsersProfile>(addUserDto);
                        newUser.Id = userId;
                        await _unitOfWork.UserRepository.CreateAsync(newUser);

                        creationState.IsCreatedSuccessfully = await _unitOfWork.SaveAsync() > 0;

                        creationState.CreatedObjectId = newUser.Id;

                        creationState.CreatedObjectId = userId;
                        if (addUserDto.File != null)
                        {
                            string extention = Path.GetExtension(addUserDto.File.FileName);
                            string path      = _hostEnvironment.WebRootPath + "/Uploads/" + newUser.Id + extention;
                            using (var stream = new FileStream(path, FileMode.Create))
                            {
                                await addUserDto.File.CopyToAsync(stream);
                            }
                        }
                    }
                    else
                    {
                        foreach (IdentityError item in result.Errors)
                        {
                            creationState.ErrorMessages.Add(item.Description);
                        }
                    }
                }
                else
                {
                    creationState.ErrorMessages.Add("This user added before");
                }
            }
            catch (Exception ex)
            {
                creationState.ErrorMessages.Add(ex.Message);
            }
            return(creationState);
        }
        public AddUserDto GetAddUser()
        {
            var userGroupSelectItems = GetUserGroupSelectItems(ApplicationUserClient_Id);
            var dto = new AddUserDto(ApplicationUserClient_Id, userGroupSelectItems);

            dto.userGroupIds = new int[] { };
            return(dto);
        }
        public async Task <IdentityResult> CreateUserAsync(AddUserDto dto)
        {
            var user = dto.ToEntity();

            var result = await _userManager.CreateAsync(user, dto.Password);

            return(result);
        }
Exemplo n.º 25
0
        public AddUserDto ToModel(AddUserDto dto)
        {
            dto.Email       = this.Email;
            dto.Password    = this.Password;
            dto.PhoneNumber = this.PhoneNumber;

            return(dto);
        }
Exemplo n.º 26
0
        public async Task <IActionResult> Add(AddUserDto model)
        {
            var vm = new AddUserVM {
                Cities = await _unitOfWork.UserRepo.GetCities(), User = model
            };

            return(View(vm));
        }
Exemplo n.º 27
0
        [HttpPost]  // POST localhost/User
        public async Task <IActionResult> AddUser(AddUserDto newUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            return(Ok(await _userService.AddUser(newUser)));
        }
Exemplo n.º 28
0
        public ResponseDto AddUser(AddUserDto user)
        {
            var entity = user.MapTo <User, AddUserDto>();

            _userRepository.Add(entity);
            return(new ResponseDto {
                Code = 200, Message = "添加用户成功!"
            });
        }
Exemplo n.º 29
0
        public void AddUser(AddUserDto addUserDto)
        {
            addUserDto.Name.ThrowExceptionIfNullOrEmpty("addUserDto.Name");
            addUserDto.Password.ThrowExceptionIfNullOrEmpty("addUserDto.Password");
            addUserDto.Role.ThrowExceptionIfNullOrEmpty("addUserDto.Role");
            addUserDto.ServerParks.ThrowExceptionIfNullOrEmpty("addUserDto.ServerParks");

            _blaiseApi.AddUser(addUserDto.Name, addUserDto.Password, addUserDto.Role, addUserDto.ServerParks, addUserDto.DefaultServerPark);
        }
Exemplo n.º 30
0
        public async Task <List <GetUserDto> > AddUser(AddUserDto newUser)
        {
            User usr = _mapper.Map <User>(newUser);
            await _context.Users.AddAsync(usr);

            await _context.SaveChangesAsync();

            return((_context.Users.Select(u => _mapper.Map <GetUserDto>(u))).ToList());
        }