Пример #1
0
        public async Task <IActionResult> CreateUser([ModelBinder(typeof(JsonModelBinder <UserDto>))] Delta <UserDto> userDelta)
        {
            if (!ModelState.IsValid)
            {
                return(await Error());
            }

            var newUser = _factory.Initialize();

            userDelta.Merge(newUser);

            await UserService.InsertUserAsync(newUser);

            await InsertFirstAndLastNameGenericAttributes(userDelta.Dto.FirstName, userDelta.Dto.LastName, newUser);

            //password
            if (!string.IsNullOrWhiteSpace(userDelta.Dto.Password))
            {
                await AddPassword(userDelta.Dto.Password, newUser);
            }

            //roles
            if (userDelta.Dto.RoleIds.Count > 0)
            {
                AddValidRoles(userDelta, newUser);
            }

            //stores
            if (userDelta.Dto.StoreIds.Count > 0)
            {
                await AddValidStores(userDelta, newUser);
            }

            await UserService.UpdateUserAsync(newUser);

            var newUserDto = newUser.ToDto();

            newUserDto.FirstName    = userDelta.Dto.FirstName;
            newUserDto.LastName     = userDelta.Dto.LastName;
            newUserDto.UserPassword = _userApiService.GetUserPassword(newUserDto.Id);

            //activity log
            await UserActivityService.InsertActivityAsync("AddNewUser", $"Added a new user (ID = {newUser.Id})", newUser);

            var usersRootObject = new UsersRootObject();

            usersRootObject.Users.Add(newUserDto);

            var json = JsonFieldsSerializer.Serialize(usersRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
Пример #2
0
        public async Task <User[]> TrendingDevelopers()
        {
            string apiUrl = "https://api.github.com/search/users?q=+followers:%3E0&sort=followers&order=desc";

            UsersRootObject usersRootObject = await GetObjectAsync <UsersRootObject>(apiUrl);

            var usersTasks = usersRootObject.Items.Select(u => GetObjectAsync <UserFromApi>(u.url)).ToArray();

            var users = await Task.WhenAll(usersTasks);

            var result = await GetUsersAsync(users);

            return(result);
        }
Пример #3
0
        public async Task <UsersRootObject> GetPopularUsers(string language, string date)
        {
            using (HttpResponseMessage response = await client.GetAsync($"{baseUrl}/user_search_url/q=language:{language}+sort:followers"))
            {
                if (response.IsSuccessStatusCode)
                {
                    string usersAsString = await response.Content.ReadAsStringAsync();

                    UsersRootObject users = JsonConvert.DeserializeObject <UsersRootObject>(usersAsString);
                    return(users);
                }
            }

            return(null);
        }
Пример #4
0
        public void Should_call_serializer_when_no_parameters_passed_and_no_user_exists()
        {
            var expectedUsersCollection = new List <UserDto>();

            var expectedRootObject = new UsersRootObject
            {
                Users = expectedUsersCollection
            };

            var defaultParameters = new UsersSearchParametersModel();

            _jsonFieldsSerializer.Setup(x => x.Serialize(expectedRootObject, defaultParameters.Fields, null));
            _userApiService.Setup(x => x.Search(null, null, 1, 50)).Returns(expectedUsersCollection);

            _usersController.Search(defaultParameters).GetAwaiter().GetResult();

            _jsonFieldsSerializer.Verify(x =>
                                         x.Serialize(It.IsAny <UsersRootObject>(), It.IsIn(defaultParameters.Fields), null));
        }
Пример #5
0
        public async Task <IActionResult> GetUserById(int id, string fields = "")
        {
            if (id <= 0)
            {
                return(await Error(HttpStatusCode.BadRequest, "id", "invalid id"));
            }

            var user = _userApiService.GetUserById(id);

            if (user == null)
            {
                return(await Error(HttpStatusCode.NotFound, "user", "not found"));
            }

            var usersRootObject = new UsersRootObject();

            usersRootObject.Users.Add(user);

            var json = JsonFieldsSerializer.Serialize(usersRootObject, fields);

            return(new RawJsonActionResult(json));
        }
Пример #6
0
        public async Task <IActionResult> Search(UsersSearchParametersModel parameters)
        {
            if (parameters.Limit <= Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit)
            {
                return(await Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"));
            }

            if (parameters.Page <= 0)
            {
                return(await Error(HttpStatusCode.BadRequest, "page", "Invalid page parameter"));
            }

            var usersDto = _userApiService.Search(parameters.Query, parameters.Order, parameters.Page, parameters.Limit);

            var usersRootObject = new UsersRootObject()
            {
                Users = usersDto
            };

            var json = JsonFieldsSerializer.Serialize(usersRootObject, parameters.Fields);

            return(new RawJsonActionResult(json));
        }
Пример #7
0
        public async Task <IActionResult> GetUsers(UsersParametersModel parameters)
        {
            if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit)
            {
                return(await Error(HttpStatusCode.BadRequest, "limit", "Invalid limit parameter"));
            }

            if (parameters.Page < Configurations.DefaultPageValue)
            {
                return(await Error(HttpStatusCode.BadRequest, "page", "Invalid request parameters"));
            }

            var users = _userApiService.GetUserDtos(parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.Limit,
                                                    parameters.Page, parameters.SinceId, parameters.RoleIds, parameters.StoreIds);

            var usersRootObject = new UsersRootObject
            {
                Users = users
            };

            var json = JsonFieldsSerializer.Serialize(usersRootObject, parameters.Fields);

            return(new RawJsonActionResult(json));
        }
Пример #8
0
        public async Task <IActionResult> UpdateUser([ModelBinder(typeof(JsonModelBinder <UserDto>))] Delta <UserDto> userDelta)
        {
            if (!ModelState.IsValid)
            {
                return(await Error());
            }

            var currentUser = _userApiService.GetUserEntityById(userDelta.Dto.Id);

            if (currentUser == null)
            {
                return(await Error(HttpStatusCode.NotFound, "user", "not found"));
            }

            userDelta.Merge(currentUser);

            //password
            if (!string.IsNullOrWhiteSpace(userDelta.Dto.Password))
            {
                await AddPassword(userDelta.Dto.Password, currentUser);
            }

            //roles
            if (userDelta.Dto.RoleIds.Count > 0)
            {
                AddValidRoles(userDelta, currentUser);
            }

            //stores
            if (userDelta.Dto.StoreIds.Count > 0)
            {
                await AddValidStores(userDelta, currentUser);
            }

            await UserService.UpdateUserAsync(currentUser);

            await InsertFirstAndLastNameGenericAttributes(userDelta.Dto.FirstName, userDelta.Dto.LastName, currentUser);

            // Preparing the result dto of the new user
            var updatedUser = currentUser.ToDto();

            var firstNameGenericAttribute =
                (await _genericAttributeService.GetAttributesForEntityAsync(currentUser.Id, typeof(User).Name))
                .FirstOrDefault(x => x.Key == "FirstName");

            if (firstNameGenericAttribute != null)
            {
                updatedUser.FirstName = firstNameGenericAttribute.Value;
            }

            var lastNameGenericAttribute =
                (await _genericAttributeService.GetAttributesForEntityAsync(currentUser.Id, typeof(User).Name))
                .FirstOrDefault(x => x.Key == "LastName");

            if (lastNameGenericAttribute != null)
            {
                updatedUser.LastName = lastNameGenericAttribute.Value;
            }

            updatedUser.UserPassword = _userApiService.GetUserPassword(updatedUser.Id);

            //activity log
            await UserActivityService.InsertActivityAsync("EditUser", $"Edited a user (ID = {currentUser.Id})", currentUser);

            var usersRootObject = new UsersRootObject();

            usersRootObject.Users.Add(updatedUser);

            var json = JsonFieldsSerializer.Serialize(usersRootObject, String.Empty);

            return(new RawJsonActionResult(json));
        }
Пример #9
0
        // Accepts username and password as parameters. Encrypts passwords and stores in a JSON file.
        // Creates an account; checks if the username already exists
        public Boolean createAccount(string username, string password)
        {
            User            newUser   = new User();            // User object for new user
            UsersRootObject usersObj  = new UsersRootObject(); // Object of user
            List <User>     usersList = new List <User>();     // List of users to read in existing data and add new users
            string          json;                              // for the final JSON formatted list of users
            Boolean         exists  = false;                   // boolean value to check if the username exists
            Boolean         created = false;                   // boolean value to return

            byte[] pwd;                                        // byte array to store the encrypted password into
            string encryptedPass = "";                         // string to store the encrypted password into


            string path = HttpRuntime.AppDomainAppPath + "\\user_credentials.json"; // File path to user credentials

            try
            {
                string jsonData = File.ReadAllText(path);                             // reads in the JSON file into a string

                usersObj = JsonConvert.DeserializeObject <UsersRootObject>(jsonData); // transfers jsonData to the usersObj

                if (usersObj.users != null)                                           // makes sure that there is at least one existing user to iterate through accounts
                {
                    usersList = usersObj.users.ToList <User>();                       // transfers users to a List<User>

                    foreach (User user in usersList)                                  // iterates through the users
                    {
                        if (user.username == username)                                // checks if the username already exists
                        {
                            exists = true;
                        }
                    }
                }

                if (!exists)                                 // If username doesn't already exist
                {
                    pwd = Encoding.ASCII.GetBytes(password); // Encrypts the password

                    // Loop converts byte array to a string
                    foreach (byte digit in pwd)
                    {
                        encryptedPass += digit;
                    }

                    newUser.username = username;
                    newUser.password = encryptedPass;
                    usersList.Add(newUser);                                                      // adds the new user to the user list

                    usersObj.users = usersList.ToArray <User>();                                 // Converts the list to a User object array
                    json           = JsonConvert.SerializeObject(usersObj, Formatting.Indented); // Converts object to JSON string
                    File.WriteAllText(path, json);                                               // Writes JSON data to the file

                    created = true;
                }
            }
            finally
            {
            }

            return(created); // Returns creation confirmation
        }