public async Task PostTest(int expectedStatus)
        {
            var strongPassword = true;
            Mock <IRepository <UserData> >       mockRepoistory = new Mock <IRepository <UserData> >();
            Mock <IPasswordStrengthValidator>    mockValidator  = new Mock <IPasswordStrengthValidator>();
            Mock <ILogger <UserDataController> > mockLogger     = new Mock <ILogger <UserDataController> >();
            var controller   = new UserDataController(mockLogger.Object, mockRepoistory.Object, mockValidator.Object);
            var email        = "*****@*****.**";
            var password     = "******";
            var passwordHash = "";
            var request      = new AddUserRequest {
                Email = email, Password = password
            };

            switch (expectedStatus)
            {
            case StatusCodes.Status201Created:
                var userData = new UserData {
                    Email = email, PasswordHash = passwordHash
                };
                mockRepoistory.Setup(repository => repository.Insert(It.IsAny <UserData>())).Verifiable();
                break;

            case StatusCodes.Status400BadRequest:
                strongPassword = false;
                break;

            case StatusCodes.Status500InternalServerError:
                mockRepoistory.Setup(repository => repository.Insert(It.IsAny <UserData>())).Throws(new Exception("Already exists"));
                break;
            }

            mockValidator.Setup(validator => validator.IsStrongPassword(password)).Returns(strongPassword).Verifiable();

            var result = await controller.Post(request);

            Assert.IsAssignableFrom <ActionResult <PostResponse> >(result);
            var objectResult = result.Result as ObjectResult;
            var postResponse = objectResult.Value as PostResponse;

            Assert.Equal(expectedStatus, objectResult.StatusCode);

            switch (expectedStatus)
            {
            case StatusCodes.Status201Created:
                Assert.True(postResponse.Success);
                Assert.Equal($"User {email} added", postResponse.Message);
                break;

            case StatusCodes.Status400BadRequest:
                Assert.False(postResponse.Success);
                Assert.Equal("Invalid Password", postResponse.Message);
                break;

            case StatusCodes.Status500InternalServerError:
                Assert.False(postResponse.Success);
                Assert.Equal("Already exists", postResponse.Message);
                break;
            }
        }
Esempio n. 2
0
        public void GetUsers()
        {
            UsersFacade usersFacade = new UsersFacade();

            AddUserRequest addUserRequest = new AddUserRequest()
            {
                Username        = AlphaNumericStringGenerator.GetString(10),
                Password        = AlphaNumericStringGenerator.GetString(10),
                PasswordConfirm = AlphaNumericStringGenerator.GetString(10)
            };

            AddUserResponse addUserResponse = usersFacade.AddUser(addUserRequest);

            Assert.AreEqual(HttpStatusCode.OK, addUserResponse.Status);

            GetUsersResponse getUsersResponse = usersFacade.GetUsers();

            Assert.AreEqual(HttpStatusCode.OK, getUsersResponse.Status);
            Assert.IsNotNull(getUsersResponse.Users.Find(u => u.UserId == addUserResponse.UserId));

            using (helpdesksystemContext context = new helpdesksystemContext())
            {
                var users = context.User.ToList();

                Assert.IsNotNull(users);
            }
        }
Esempio n. 3
0
        public void UpdateUserUsernameExists()
        {
            UsersFacade usersFacade = new UsersFacade();

            AddUserRequest addUserRequest = new AddUserRequest()
            {
                Username        = AlphaNumericStringGenerator.GetString(10),
                Password        = AlphaNumericStringGenerator.GetString(10),
                PasswordConfirm = AlphaNumericStringGenerator.GetString(10)
            };

            AddUserRequest addUserRequest2 = new AddUserRequest()
            {
                Username        = AlphaNumericStringGenerator.GetString(10),
                Password        = AlphaNumericStringGenerator.GetString(10),
                PasswordConfirm = AlphaNumericStringGenerator.GetString(10)
            };

            AddUserResponse addUserResponse  = usersFacade.AddUser(addUserRequest);
            AddUserResponse addUserResponse2 = usersFacade.AddUser(addUserRequest2);

            Assert.AreEqual(HttpStatusCode.OK, addUserResponse.Status);

            UpdateUserRequest updateUserRequest = new UpdateUserRequest()
            {
                Username = addUserResponse.Username,
                Password = AlphaNumericStringGenerator.GetString(10)
            };

            UpdateUserResponse updateUserResponse = usersFacade.UpdateUser(addUserResponse2.UserId, updateUserRequest);

            Assert.AreEqual(HttpStatusCode.BadRequest, updateUserResponse.Status);
        }
Esempio n. 4
0
        public ResultJson AddUserInfo(AddUserRequest request)
        {
            if (request.Discount > 100)
            {
                return(new ResultJson {
                    HttpCode = 300, Message = "请输入0~100的数字!"
                });
            }
            var result = UserFunc.Instance.InsertModel(new DbOpertion.Models.User
            {
                Name         = request.NickName,
                Email        = request.Email,
                Discount     = (float)(request.Discount / 100),
                Phone        = request.Phone,
                Sex          = request.Sex,
                CreateTime   = DateTime.Now,
                CompanyName  = request.CompanyName,
                CompanyAddr  = request.CompanyAddr,
                ZipCode      = request.ZipCode,
                CompanyPhone = request.CompanyPhone
            });

            if (result == "成功!")
            {
                return(new ResultJson {
                    HttpCode = 200, Message = "添加成功!"
                });
            }
            else
            {
                return(new ResultJson {
                    HttpCode = 300, Message = result
                });
            }
        }
Esempio n. 5
0
        private UserApp buildUserFromRequest(AddUserRequest request, int HomeAddressId)
        {
            UserApp user = new UserApp();

            user.userName     = request.name;
            user.userEmail    = request.emailUser;
            user.userLastname = request.lastname;
            user.userNicname  = request.nickname;

            /*
             * En caso de no tener un número de documento de identificación
             * el sistema le asigna el número de consumidor final;
             */
            if (string.IsNullOrEmpty(request.numDocument))
            {
                user.userNumDocument = "9999999999";
            }
            else
            {
                user.userNumDocument = request.numDocument;
            }

            user.userPhone     = request.phone;
            user.userType      = request.type;
            user.Disability    = null;
            user.userPassword  = this.createTempPass();
            user.CreateAt      = DateTime.Now;
            user.ModifiedAt    = DateTime.Now;
            user.HomeAddressId = HomeAddressId;
            return(_userModelServices.save(user));
        }
Esempio n. 6
0
        public async Task <bool> Handle(AddUserRequest message, IOutputPort <AddUserResponse> outputPort)
        {
            var response = await _userRepository.Create(new User(message.Id, message.Name, message.Birthdate, message.Username), message.Password);

            outputPort.Handle(response.Success ? new AddUserResponse(response.Id, true) : new AddUserResponse(response.Errors.Select(e => e.Description)));
            return(response.Success);
        }
Esempio n. 7
0
        public AddUserResponse AddUser(AddUserRequest request)
        {
            var response = new AddUserResponse {
                Errors = new List <string>()
            };

            //TODO: validari

            if (request.Age < 10)
            {
                response.Success = false;
                response.Errors.Add("Age is lower than 10");
                return(response);
            }

            _userRepository.Add(new User
            {
                Name      = request.Name,
                Age       = request.Age,
                Username  = request.Username,
                Password  = Sha.Encrypt(request.Password),
                UserImage = request.UserImage
            });

            response.Success = true;
            return(response);
        }
Esempio n. 8
0
        public ActionResult Add(AddUserRequest request, string enableFlag, string isChangePwd)
        {
            var flag = false;
            var msg  = string.Empty;

            if (request == null)
            {
                request = new AddUserRequest();
            }
            request.EnableFlag  = !enableFlag.IsNullOrEmpty() ? true : false;
            request.IsChangePwd = !isChangePwd.IsNullOrEmpty() ? true : false;

            using (var factory = new ChannelFactory <IRightsUserService>("*"))
            {
                var client = factory.CreateChannel();
                var rs     = client.AddUser(request, loginInfo);
                if (rs.ReturnCode == ReturnCodeType.Success && rs.Content == true)
                {
                    flag = true;
                    msg  = "新增成功!";
                }
                else
                {
                    msg = rs.Message;
                }
            }

            return(Json(new { success = flag, msg = msg }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 9
0
 public static Command AddUser(this Command command, AddUserRequest userRequest)
 {
     command.User    = true;
     command.Method  = HttpMethod.POST;
     command.Payload = userRequest;
     return(command);
 }
Esempio n. 10
0
        public async Task AddUserUnitTests(
            AddUserRequest request,
            Type exceptionType)
        {
            var userDbHandler = new Mock <IUserDbHandler>();

            userDbHandler.Setup(h => h.GetUsersAsync()).ReturnsAsync(
                new List <User>()
            {
                new User()
                {
                    Id = 1, Name = "N1", Email = "[email protected]"
                },
                new User()
                {
                    Id = 2, Name = "M1", Email = "[email protected]"
                }
            });

            var userService = new UserService(userDbHandler.Object);

            if (exceptionType == null)
            {
                await userService.AddUserAsync(request);

                userDbHandler.Verify(h => h.AddUserAsync(It.IsAny <User>()), Times.Once);
            }
            else
            {
                await Assert.ThrowsAsync(exceptionType, () => userService.AddUserAsync(request));

                userDbHandler.Verify(h => h.AddUserAsync(It.IsAny <User>()), Times.Never);
            }
        }
Esempio n. 11
0
        public IActionResult Register([FromBody] AddUserRequest request)
        {
            if (request == null)
            {
                return(BadRequest());
            }

            var isEmailTaken = _usersDataService.IsEmailTaken(request.Email);

            if (!isEmailTaken.IsSuccess)
            {
                return(new OkObjectResult(Models.Common.Response.Failed()));
            }

            if (isEmailTaken.Data)
            {
                return(new OkObjectResult(Response <bool> .Succeeded(false)));
            }

            var registerResult = _usersDataService.AddUser(request);

            if (!registerResult.IsSuccess)
            {
                return(new OkObjectResult(Models.Common.Response.Failed()));
            }

            return(new OkObjectResult(Response <bool> .Succeeded(true)));
        }
Esempio n. 12
0
        private void HandleMembers(Activity activity)
        {
            if (activity.Action == ContactRelationUpdateActionTypes.Add)
            {
                if (activity.MembersAdded != null &&
                    activity.MembersAdded.Any())
                {
                    var users = activity.MembersAdded.Select(x => new AddUserRequest
                    {
                        UserId   = x.Id,
                        UserName = x.Name
                    })
                                .ToArray();
                    dataService.AddUserForApprovalQueue(users);
                }

                if (activity.From != null &&
                    !String.IsNullOrEmpty(activity.From.Name))
                {
                    var newUser = new AddUserRequest
                    {
                        UserId   = activity.From.Id,
                        UserName = activity.From.Name
                    };
                    dataService.AddUserForApprovalQueue(new[] { newUser });
                }
            }
        }
Esempio n. 13
0
        public AddUserResponse AddUser(AddUserRequest request)
        {
            var response = new AddUserResponse {
                ResponseStatus = ResponseStatus.Success
            };

            var usersProvider = new UsersProvider();

            try
            {
                if (request.ActionType == ActionType.Insert)
                {
                    response.isSuccessful = usersProvider.InsertUser(request);
                }
                else
                {
                    response.ResponseStatus      = ResponseStatus.Failure;
                    response.ResponseDescription = "Not update action";
                }
            }
            catch (Exception ex)
            {
                response.ResponseStatus      = ResponseStatus.Failure;
                response.ResponseDescription = ex.Message;
            }
            return(response);
        }
        public async Task AddUserAsync(AddUserRequest request)
        {
            var entity = _mapper.Map <Entities.User>(request);

            DbContext.Users.Add(entity);
            await DbContext.SaveChangesAsync();
        }
        public BaseResponse AddEditUser(AddUserRequest request)
        {
            try
            {
                using (DDS_Context dbContext = new DDS_Context())
                {
                    BaseResponse response = new BaseResponse();
                    if (request.Id == 0)
                    {
                        User temp = new User();

                        temp.Name         = request.Name;
                        temp.Surname      = request.Surname;
                        temp.Email        = request.Email;
                        temp.Password     = request.Password;
                        temp.InterestId   = request.InterestId;
                        temp.Role         = request.Role;
                        temp.CreatedDaate = DateTime.Now;
                        temp.UpdatedDate  = DateTime.Now;

                        dbContext.User.Add(temp);
                        dbContext.SaveChanges();


                        response.Message   = "Kullanıcı Eklendi";
                        response.IsSucceed = true;
                    }
                    else
                    {
                        var entity = dbContext.User.FirstOrDefault(x => x.Id == request.Id);

                        if (entity != null)
                        {
                            entity.Name        = request.Name;
                            entity.Surname     = request.Surname;
                            entity.Email       = request.Email;
                            entity.Password    = request.Password;
                            entity.InterestId  = request.InterestId;
                            entity.Role        = request.Role;
                            entity.UpdatedDate = DateTime.Now;

                            dbContext.SaveChanges();

                            response.Message   = "Kullanıcı Güncellendi";
                            response.IsSucceed = true;
                        }
                        else
                        {
                            response.Message   = "KULLANICI BULUNAMADI";
                            response.IsSucceed = false;
                        }
                    }
                    return(response);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 16
0
        public override async Task <AddUserResponse> AddUser(AddUserRequest request, ServerCallContext context)
        {
            bool exist = false;

            if (request.Force)
            { // 무조건 kick
                await KickUser(new KickUserRequest { UserId = request.UserId }, context);
            }

            lock (sessions)
            {
                exist = sessions.ContainsKey(request.UserId);
                if (exist)
                {
                    if (request.Force)
                    {
                        logger.LogWarning($"{request.UserId} already exist." + (request.Force ? " EVEN AFTER KICKED" : ""));
                    }
                    return(new AddUserResponse {
                        Result = AddUserResponse.Types.ResultType.AlreadyConnected
                    });
                }
                sessions.Add(request.UserId, request.BackendListeningAddress);
            }
            return(new AddUserResponse
            {
                Result = exist ? AddUserResponse.Types.ResultType.ForceAdded : AddUserResponse.Types.ResultType.Ok
            });
        }
Esempio n. 17
0
        public AddUserMessage Add(AddUserRequest request)
        {
            if (users.Values.Select(u => u.Name).Contains(request.Name))
            {
                return new AddUserMessage
                       {
                           Success = false,
                           Message = "User name already exists."
                       }
            }
            ;

            var id = users.Keys.Max() + 1;

            users.Add(id, new User {
                Id = id, Name = request.Name, Currency = request.Currency
            });

            return(new AddUserMessage
            {
                UserId = id,
                Success = true,
                Message = $"User created successfully with id {id}."
            });
        }
Esempio n. 18
0
        public async Task <ActionResult <PostResponse> > Post([FromBody] AddUserRequest value)
        {
            try
            {
                if (passwordStrengthValidator.IsStrongPassword(value.Password))
                {
                    var passwordHash = BCrypt.Net.BCrypt.HashPassword(value.Password);
                    var userData     = new UserData {
                        Email = value.Email, PasswordHash = passwordHash
                    };
                    await repository.Insert(userData);

                    return(StatusCode(StatusCodes.Status201Created, new PostResponse {
                        Success = true, Message = $"User {value.Email} added"
                    }));
                }
                else
                {
                    return(BadRequest(new PostResponse {
                        Success = false, Message = "Invalid Password"
                    }));
                }
            }
            catch (Exception exception)
            {
                // ToDo: make the error messages more end user friendly
                return(StatusCode(StatusCodes.Status500InternalServerError, new PostResponse {
                    Success = false, Message = exception.Message
                }));
            }
        }
        public ActionResult AddEditUser(AddUserRequest request)
        {
            Account_Service _accountService = new Account_Service();
            BaseResponse    response        = _accountService.AddEditUser(request);

            return(Json(response));
        }
Esempio n. 20
0
 public override Task <EmptyMessagee> DeleteUser(AddUserRequest request, ServerCallContext context)
 {
     _userRepository.Delete(request.UserEmail);
     _logSenderService.SendMessages("user " + request.UserEmail + " was deleted");
     return(Task.FromResult(new EmptyMessagee {
     }));
 }
Esempio n. 21
0
        public async Task <UserIdentityResult> AddNewUserAsync(AddUserRequest addUser, string password)
        {
            try
            {
                if (addUser.isActive.ToLower() != "true")
                {
                    addUser.isActive = "false";
                }
                var userId = await _usersData.AddNewUserAsync(addUser, password);

                return(new UserIdentityResult
                {
                    Id = userId,
                    Succeeded = true,
                    Errors = null
                });
            }
            catch (Exception e)
            {
                return(new UserIdentityResult
                {
                    Id = 0,
                    Succeeded = false,
                    Errors = new[] { e.Message }
                });
            }
        }
Esempio n. 22
0
        public Client AddUser(AddUserRequest iur)
        {
            try
            {
                var cl = new Client
                {
                    FirstName   = iur.FirstName,
                    LastName    = iur.LastName,
                    Email       = iur.Email,
                    Phone       = iur.Phone,
                    Login       = iur.Login,
                    Hash        = AuthHandler.Create(iur.Password, AuthHandler.CreateSalt()),
                    TokenString = "xxx"
                };


                _advertContext.SaveChanges();


                return(cl);
            }
            catch (SqlException ex)
            {
                return(null);
            }
        }
Esempio n. 23
0
        public async Task<AuthenticationResult> AddNewRegisterAsync(AddUserRequest user, string password)
        {
            var users = await _userService.FindByUsernameAsync(user.userName);
            if (users != null)
            {
                return new AuthenticationResult
                {
                    errors = new[] { "User with this Username / Email already exist" }
                };
            }

            var hashPassword = BCrypt.Net.BCrypt.HashPassword(password);

            var createUser = await _userService.AddNewUserAsync(user, hashPassword);

            var newUser = new Users()
            {
                email = user.email,
                userName = user.userName,
            };
            if (!createUser.Succeeded)
            {
                return new AuthenticationResult
                {
                    errors = createUser.Errors.Select(x => x)
                };
            }

            newUser.id = createUser.Id;
            return GenerateAuthenticationResult(newUser);
        }
Esempio n. 24
0
 public AddUserRequestResource(AddUserRequest invite)
 {
     this.InviteeEmail = invite.InviteeEmail;
     this.InviterEmail = invite.InviterEmail;
     this.TeamId       = invite.DestinationTeamId;
     this.IsAuthorized = invite.IsAuthorized;
 }
Esempio n. 25
0
        public async Task <UserResponse> AddUser(AddUserRequest request)
        {
            // Get user
            var user = await _userRepository.GetSingle(request.UserId);

            // Check if it exists
            if (user != null)
            {
                throw new ConflictException(UserMessage.UserAlreadyExists);
            }

            // Create
            user = new User(request.UserId);

            // Add user
            _userRepository.Add(user);

            // Save
            await _mainDbContext.SaveChangesAsync();

            // Log into Splunk
            _logger.LogSplunkRequest(request);

            // Response
            var response = _mapper.Map <UserResponse>(user);

            // Return
            return(response);
        }
Esempio n. 26
0
        public AddUserResponse AddUser(AddUserRequest request)
        {
            if (request == null)
            {
                AddNotification("AddUserRequest",
                                MSG.OBJETO_X0_E_OBRIGATORIO.ToFormat("AddUserRequest"));

                return(null);
            }

            //Create values objects
            Name  name  = new Name(request.FirstName, request.LastName);
            Email email = new Email(request.Email);

            //Create entity
            User user = new User(name, email, request.Password);

            AddNotifications(user);

            if (this.IsInvalid())
            {
                return(null);
            }

            //There is no database
            _repositoryUser.ToSave(user);

            return(new AddUserResponse(user.Id));
        }
        public AddUserResponse AddUser(AddUserRequest request)
        {
            Platform.CheckForNullReference(request, "request");
            Platform.CheckMemberIsSet(request.UserDetail, "UserDetail");

            var userDetail = request.UserDetail;
            var settings   = new AuthenticationSettings();

            // create new user
            var userInfo =
                new UserInfo(userDetail.UserName, userDetail.DisplayName, userDetail.EmailAddress, userDetail.ValidFrom, userDetail.ValidUntil);

            var user = User.CreateNewUser(userInfo, settings.DefaultTemporaryPassword);

            // copy other info such as authority groups from request
            var assembler = new UserAssembler();

            assembler.UpdateUser(user, request.UserDetail, PersistenceContext);

            // save
            PersistenceContext.Lock(user, DirtyState.New);
            PersistenceContext.SynchState();

            return(new AddUserResponse(user.GetRef(), assembler.GetUserSummary(user)));
        }
Esempio n. 28
0
        private async Task <AddUserResponse> AddUserAsync(AddUserRequest request)
        {
            var response = await _fixture
                           .PostAsync <AddUserResponse, AddUserRequest>("/api/users", request, _cancellation.Token);

            return(response);
        }
Esempio n. 29
0
        public IActionResult Add([FromBody] AddUserRequest request)
        {
            request.CommanderID = User.GetUserId();
            var response = _userService.AddUser(request);

            return(new ObjectResult(response));
        }
Esempio n. 30
0
    public IEnumerator AddUser(User user, Action <User> callback)
    {
        AddUserRequest request = new AddUserRequest();

        request.user          = user;
        request.securityToken = HashKey.apiKey;

        var jsonString = JsonUtility.ToJson(request);

        byte[] byteData = System.Text.Encoding.ASCII.GetBytes(jsonString.ToCharArray());

        //UnityWebRequest unityWebRequest = UnityWebRequest.Post(apiURL + "/user", jsonString);
        UnityWebRequest unityWebRequest = new UnityWebRequest(apiURL + "/user", "POST");

        unityWebRequest.uploadHandler             = new UploadHandlerRaw(byteData);
        unityWebRequest.uploadHandler.contentType = "application/json";
        unityWebRequest.SetRequestHeader("Content-Type", "application/json");


        DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer();

        unityWebRequest.downloadHandler = downloadHandlerBuffer;

        yield return(unityWebRequest.SendWebRequest());

        if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
        {
            Debug.Log(unityWebRequest.error);
        }
        else
        {
            string response = unityWebRequest.downloadHandler.text;
            callback(JsonUtility.FromJson <User>(response));
        }
    }
Esempio n. 31
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     User = this.CollectData<FullUser>(User);
     AddUserRequest request = new AddUserRequest();
     request.token = Token;
     request.Form = User;
     request.Form.Roles = GetCheckedRoles();
     SDKSync<AddUserResponse>.CreateInstance(this).Execute(request, Add_Callback);
 }
        public User AddUser(AddUserRequest request)
        {
            var user = new User
            {
                Id = Guid.NewGuid(),
                Name = request.Name,
                Surname = request.Surname,
                Birthday = request.Birthday
            };

            return _userAdapter.AddUser(user);
        }