コード例 #1
0
        public async Task <IActionResult> AddDocument(string userId, [FromForm] DocumentForCreateDto documentForCreateDto)
        {
            var uploadRes = await _uploadService.UploadFileToLocal(
                documentForCreateDto.File,
                userId,
                _env.WebRootPath,
                $"{Request.Scheme ?? ""}://{Request.Host.Value ?? ""}{Request.PathBase.Value ?? ""}",
                "Files\\Documents\\" + DateTime.Now.Year + "\\" + DateTime.Now.Month + "\\" + DateTime.Now.Day
                );

            if (uploadRes.Status)
            {
                UserForDetailedDto userProfileDto = new UserForDetailedDto();
                //return CreatedAtRoute("GetDocument", new { id = userId }, userProfileDto);
                //return CreatedAtRoute("GetDocument", new { version = "v1", controller = "Token", id = userId }, userProfileDto);

                //return CreatedAtAction("GetDocument", new { id = userId }, userProfileDto);
                return(CreatedAtAction(nameof(GetDocument), new { id = userId }, userProfileDto));


                //return await GetDocument(userId);
            }

            return(BadRequest());
        }
コード例 #2
0
        public async Task CallGetRequest_WhenCalledWithId_ReturnsTheUserWithTheSameId()
        {
            getUsersHelper     getUsersHelper     = new getUsersHelper();
            List <TblUser>     userList           = getUsersHelper.getUserFromList();
            var                user               = getUsersHelper.userById(3);
            UserForDetailedDto userForDetailedDto = new UserForDetailedDto();

            userForDetailedDto.Aname       = user.Aname;
            userForDetailedDto.ACustomerId = user.ACustomerId;
            userForDetailedDto.AUsername   = user.AUsername;
            userForDetailedDto.AEmail      = user.AEmail;
            _mockUserRepository            = new Mock <IUserRepository>();
            _mockUserMapper = new Mock <IMapper>();
            //_mockUserMapper.Setup(mapper => mapper.Map<TblUser>(It.IsAny<UserForDetailedDto>()))
            //    .Returns(getUsersHelper.userById(3));
            _mockUserMapper.Setup(mapper => mapper.Map <UserForDetailedDto>(It.IsAny <TblUser>())).Returns(userForDetailedDto);
            _mockUserRepository.Setup(repo => repo.GetUser(It.IsAny <int>()))
            .ReturnsAsync(getUsersHelper.userById(3));
            _usersController = new UsersController(_mockUserRepository.Object, _mockUserMapper.Object);
            var tblUser = await _usersController.GetUser(3);

            var okResult = tblUser as OkObjectResult;

            //Assert.AreEqual(200, okResult.StatusCode);
            Assert.NotNull(tblUser);
            Assert.IsAssignableFrom <OkObjectResult>(tblUser);
            var result = ((OkObjectResult)tblUser).Value;

            Assert.AreEqual(result, userForDetailedDto);
            Assert.NotNull(result);
            Assert.IsAssignableFrom <UserForDetailedDto>(result);
        }
コード例 #3
0
        protected async Task <string> LoginUser(UserForLoginDto userForLoginDto)
        {
            var result = await UserService.LoginAsync(userForLoginDto);

            var s = result.EnsureSuccessStatusCode();

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                try
                {
                    var content = result.Content.ReadFromJsonAsync <UserForDetailedDto>();

                    await LocalStorageService.SetItemAsync("User", await content);

                    UserForDetailed = (await content);

                    return(UserForDetailed.Username);

                    var something = System.Text.Json.JsonSerializer.Serialize(content);
                    return(something);
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }

                return("OK");
            }
            else
            {
                return(result.StatusCode.ToString());
            }
        }
コード例 #4
0
        public async Task <IActionResult> GetUser(Guid id)
        {
            try
            {
                if (id == Guid.Empty)
                {
                    return(BadRequest("invalid id"));
                }
                var user = await _userManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return(BadRequest("User doesn't exist."));
                }

                var userViewModel = new UserForDetailedDto()
                {
                    Id           = user.Id,
                    FirstName    = user.FirstName,
                    LastName     = user.LastName,
                    FullName     = user.FullName,
                    Email        = user.Email,
                    NIN          = user.NIN,
                    PhoneNumber  = user.PhoneNumber,
                    Gender       = user.Gender,
                    CreatedOnUtc = user.CreatedOnUtc
                };
                return(Ok(userViewModel));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
コード例 #5
0
        public async Task <IActionResult> GetUser(int id)
        {
            User user = await repository.GetUser(id);

            UserForDetailedDto userToReturn = mapper.Map <UserForDetailedDto>(user);

            return(Ok(userToReturn));
        }
コード例 #6
0
        public UserForDetailedDto AddRoleToUser(UserForDetailedDto user)
        {
            var role = user.UserRoles.ElementAtOrDefault(0);

            user.Role = role.Name;

            return(user);
        }
コード例 #7
0
        public async Task <IActionResult> GetUser(string id)
        {
            var user = await _db.UserRepository.GetManyAsync(p => p.Id == id, null, "Photos");

            UserForDetailedDto userToReturn = _mapper.Map <UserForDetailedDto>(user.SingleOrDefault());

            return(Ok(userToReturn));
        }
コード例 #8
0
        private async void LoadData()
        {
            try
            {
                DiaglogService.ShowLoading(this);
                var userResponse = await apiService.GetAsync <UserForDetailedDto>(Settings.ApiUrl, Settings.Prefix, "/Users/GetUser/" + userId, "Bearer", Settings.Token);

                if (!userResponse.IsSuccess)
                {
                    DiaglogService.StopLoading();
                    DiaglogService.ShowMessage(this, "Error loading user", userResponse.Message, "Accept");
                    return;
                }
                userInformation = JsonConvert.DeserializeObject <UserForDetailedDto>(userResponse.Result.ToString());
                if (userInformation != null)
                {
                    nameEditText.Text     = userInformation.Name;
                    lastNameEditText.Text = userInformation.LastName;
                    idNumberEditText.Text = userInformation.IdNumber;
                    emailEditText.Text    = userInformation.Email;
                }


                var response = await apiService.GetListAsync <IdTypeForDetailedDto>(Settings.ApiUrl, Settings.Prefix, "/Users/GetUserIdTypes", "Bearer", Settings.Token);

                if (!response.IsSuccess)
                {
                    DiaglogService.StopLoading();
                    DiaglogService.ShowMessage(this, "Error loading id types", response.Message, "Accept");
                    return;
                }
                idTypesList = new List <IdTypeForDetailedDto>();
                idTypesList = JsonConvert.DeserializeObject <List <IdTypeForDetailedDto> >(response.Result.ToString());

                if (idTypesList.Count > 0)
                {
                    var usersAdapter = new ArrayAdapter <string>(this, global::Android.Resource.Layout.SimpleDropDownItem1Line, idTypesList.Select(x => x.Name).ToList());
                    idTypeSelected               = idTypesList.FirstOrDefault(x => x.Id == userInformation.IdTypeID);
                    idTypesSpinner.Adapter       = usersAdapter;
                    idTypesSpinner.ItemSelected += IdTypesSpinner_ItemSelected;

                    int spinnerPosition = usersAdapter.GetPosition(idTypeSelected.Name);
                    idTypesSpinner.SetSelection(spinnerPosition);
                }
                else
                {
                    DiaglogService.ShowMessage(this, "Error", "Please add a category", "Accept");
                    Finish();
                }

                DiaglogService.StopLoading();
            }
            catch (System.Exception ex)
            {
                DiaglogService.StopLoading();
                DiaglogService.ShowMessage(this, "Error", CommonHelpers.GetErrorMessage("Error loading users", ex), "Ok");
            }
        }
コード例 #9
0
        public async Task <UserForDetailedDto> AddRoleToUser(UserForDetailedDto userToReturn, User user)
        {
            var roles = await _userManager.GetRolesAsync(user);

            foreach (var role in roles)
            {
                userToReturn.Role = role;
            }

            return(userToReturn);
        }
コード例 #10
0
        public async Task <IActionResult> UpdateUser(int id, UserForDetailedDto userForUpdateDto)
        {
            var userFromRepo = await _repo.GetUser(id);

            _mapper.Map(userForUpdateDto, userFromRepo);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }


            throw new Exception($"Updating user {id} failed on save.");
        }
コード例 #11
0
        public async Task GivenAValidUser_WhenIRegisterANewUser_ThenItReturnsOkWithResponse()
        {
            _mockAuthRepository = new Mock <IAuthRepository>();
            _mockAuthMapper     = new Mock <IMapper>();
            _mockConfig         = new Mock <IConfiguration>();
            UserForRegisterDto expectedUser = new UserForRegisterDto
            {
                Aname     = "Luffy",
                AUsername = "******",
                AEmail    = "*****@*****.**",
                Password  = "******",
                ADob      = new DateTime(2000, 12, 12)
            };
            TblUser user = new TblUser
            {
                Aname       = "Luffy",
                AUsername   = "******",
                AEmail      = "*****@*****.**",
                ACustomerId = 4,
                ADob        = new DateTime(2000, 12, 12)
            };
            UserForDetailedDto userForDetailedDto = new UserForDetailedDto
            {
                Aname       = "Luffy",
                AUsername   = "******",
                AEmail      = "*****@*****.**",
                ACustomerId = 4
            };

            _mockAuthMapper.Setup(mapper => mapper.Map <TblUser>(It.IsAny <UserForRegisterDto>()))
            .Returns(user);
            _mockAuthMapper.Setup(mapper => mapper.Map <UserForDetailedDto>(user))
            .Returns(userForDetailedDto);
            _mockAuthRepository.Setup(repo => repo.Register(It.IsAny <TblUser>(), It.IsAny <string>()))
            .ReturnsAsync((TblUser user, string password) => user);

            _authController = new AuthController(_mockAuthRepository.Object, _mockConfig.Object, _mockAuthMapper.Object);
            var tblUser = await _authController.Register(expectedUser);

            Assert.NotNull(tblUser);
            Assert.IsAssignableFrom <CreatedAtRouteResult>(tblUser);
            var result = ((CreatedAtRouteResult)tblUser).Value;

            Assert.NotNull(result);
            Assert.IsAssignableFrom <UserForDetailedDto>(result);
        }
コード例 #12
0
ファイル: AuthController.cs プロジェクト: jechev/Exercises
        public async Task <IActionResult> Register(UserRegisterDto userForRegisterDto)
        {
            userForRegisterDto.Username = userForRegisterDto.Username.ToLower();

            if (await _repo.UserExist(userForRegisterDto.Username))
            {
                return(BadRequest("Username already exists"));
            }

            User newUser = _mapper.Map <User>(userForRegisterDto);

            User createdUser = await _repo.Register(newUser, userForRegisterDto.Password);

            UserForDetailedDto userToReturn = _mapper.Map <UserForDetailedDto>(createdUser);

            return(CreatedAtRoute("GetUser", new { controller = "Users", id = createdUser.Id }, userToReturn));
        }
コード例 #13
0
        public async Task <IActionResult> UpdateUser(int id, UserForDetailedDto userForDetailedDto)
        {
            if (id != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var userFromRepo = await _repo.GetUser(id);

            _mapper.Map(userForDetailedDto, userForDetailedDto);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            throw new System.Exception($"Updating user {id} failed on save");
        }
コード例 #14
0
        public async Task <IActionResult> Register(UserForRegisterDto userForRegisterDto)
        {
            //validate request -- Only use it if there is no [ApiController] tag, and add [FromBody] tag in front of UserForRegisterDto
            //if (!ModelState.IsValid) return BadRequest(ModelState);

            User userToCreate = _mapper.Map <User>(userForRegisterDto);

            var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);

            UserForDetailedDto userToReturn = _mapper.Map <UserForDetailedDto>(userToCreate);

            if (result.Succeeded)
            {
                return(CreatedAtRoute("GetUser", new { controller = "Users", id = userToCreate.Id }, userToReturn));
            }

            return(BadRequest(result.Errors));
        }
コード例 #15
0
        public async Task <IActionResult> Register(UserForRegisterDto userForRegisterDto)
        {
            //Validate request

            userForRegisterDto.Username = userForRegisterDto.Username.ToLower();

            if (await _authRepository.UserExists(userForRegisterDto.Username))
            {
                return(BadRequest("¡El nombre de usuario ya existe!"));
            }

            User userToCreate = _mapper.Map <User>(userForRegisterDto);

            User createdUser = await _authRepository.Register(userToCreate, userForRegisterDto.Password);

            UserForDetailedDto userToReturn = _mapper.Map <UserForDetailedDto>(createdUser);

            return(CreatedAtRoute("GetUser", new { controller = "Users", id = createdUser.Id }, userToReturn));
        }
コード例 #16
0
        public async Task <IActionResult> Register(UserForRegisterDto userForRegisterDto)
        {
            var userToCreate = new ApplicationUser()
            {
                UserName   = userForRegisterDto.UserName,
                Created    = userForRegisterDto.Created,
                LastActive = userForRegisterDto.LastActive
            };

            var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);

            var userToReturn = new UserForDetailedDto()
            {
                Id          = userToCreate.Id,
                UserName    = userToCreate.UserName,
                FirstName   = userToCreate.FirstName,
                MiddleName  = userToCreate.MiddleName,
                LastName    = userToCreate.LastName,
                Email       = userToCreate.Email,
                PhoneNumber = userToCreate.PhoneNumber,
                Created     = userToCreate.Created,
                LastActive  = userToCreate.LastActive
            };

            if (result.Succeeded)
            {
                IEnumerable <string> defaultRolesList = new List <string>()
                {
                    "Member"
                };

                var resultForRole = await _userManager.AddToRolesAsync(userToCreate, defaultRolesList);

                if (!resultForRole.Succeeded)
                {
                    return(BadRequest(resultForRole.Errors));
                }

                return(CreatedAtRoute("GetUser", new { controller = "Users", Id = userToCreate.Id }, userToReturn));
            }

            return(BadRequest(result.Errors));
        }
コード例 #17
0
        public async Task <IActionResult> GetUser(string id)
        {
            var user = await _userManager.FindByIdAsync(id);

            var userToReturn = new UserForDetailedDto()
            {
                Id          = user.Id,
                UserName    = user.UserName,
                FirstName   = user.FirstName,
                MiddleName  = user.MiddleName,
                LastName    = user.LastName,
                Email       = user.Email,
                PhoneNumber = user.PhoneNumber,
                Created     = user.Created,
                LastActive  = user.LastActive
            };

            return(Ok(userToReturn));
        }
コード例 #18
0
        public async Task Handle_WhenCalled_AttemptToSendProperNotificationExpected()
        {
            // ARRANGE
            var userEmail            = "*****@*****.**";
            var configuration        = Substitute.For <IConfiguration>();
            var configurationSection = Substitute.For <IConfigurationSection>();

            configurationSection.Value = "http://server.com/ResetPassword/{token}";
            configuration.GetSection("AppSettings:ResetPasswordUriFormat").Returns(configurationSection);

            var userService = Substitute.For <IUserService>();
            var user        = new UserForDetailedDto {
                Email = userEmail, ResetPasswordToken = "reset_password_token", Username = "******"
            };

            userService.GetUser(default(string)).ReturnsForAnyArgs(user);

            var notificationService = Substitute.For <INotificationService>();
            INotificationTemplateData actualNotificationTemplateData = null;
            string actualRecipient = string.Empty;

            notificationService.When(x => x.SendAsync(Arg.Any <string>(), Arg.Any <INotificationTemplateData>())).Do(x =>
            {
                actualRecipient = x.ArgAt <string>(0);
                actualNotificationTemplateData = x.ArgAt <INotificationTemplateData>(1);
            });
            var expectedNotificationTemplateData =
                new ResetPasswordNotificationTemplateData("http://server.com/ResetPassword/reset_password_token",
                                                          user.Username);

            var sut = new ResetPasswordRequestNotificationHandler(notificationService, userService, configuration);
            var resetPasswordRequestNotificationEvent = new ResetPasswordRequestNotificationEvent(userEmail);

            // ACT
            await sut.Handle(resetPasswordRequestNotificationEvent, new CancellationToken());

            // ASSERT
            actualRecipient.Should().BeEquivalentTo(userEmail);
            actualNotificationTemplateData.Should().BeEquivalentTo(expectedNotificationTemplateData);
        }
コード例 #19
0
        public async Task Handle_WhenCalled_AttemptToSendProperNotificationExpected()
        {
            // ARRANGE
            var userEmail            = "*****@*****.**";
            var configuration        = Substitute.For <IConfiguration>();
            var configurationSection = Substitute.For <IConfigurationSection>();

            configurationSection.Value = "http://localhost:4200/AccountActivate/{token}";
            configuration.GetSection("AppSettings:AccountActivationUriFormat").Returns(configurationSection);

            var userService = Substitute.For <IUserService>();
            var user        = new UserForDetailedDto {
                Email = userEmail, ActivationToken = "activation_token"
            };

            userService.GetUser(default(string)).ReturnsForAnyArgs(user);

            var notificationService = Substitute.For <INotificationService>();
            INotificationTemplateData actualNotificationTemplateData = null;
            string actualRecipient = string.Empty;

            notificationService.When(x => x.SendAsync(Arg.Any <string>(), Arg.Any <INotificationTemplateData>())).Do(x =>
            {
                actualRecipient = x.ArgAt <string>(0);
                actualNotificationTemplateData = x.ArgAt <INotificationTemplateData>(1);
            });
            var expectedNotificationTemplateData =
                new UserRegisteredNotificationTemplateData($"http://localhost:4200/AccountActivate/{user.ActivationToken}",
                                                           user.Username);

            var sut = new UserRegisteredNotificationHandler(notificationService, userService, configuration);
            var userRegisteredNotificationEvent = new UserRegisteredNotificationEvent(userEmail);

            // ACT
            await sut.Handle(userRegisteredNotificationEvent, new CancellationToken());

            // ASSERT
            actualRecipient.Should().BeEquivalentTo(userEmail);
            actualNotificationTemplateData.Should().BeEquivalentTo(expectedNotificationTemplateData);
        }
コード例 #20
0
        public async Task GetUserAsync_ExistingIdPassed_ReturnsOkResult()
        {
            var user = new User
            {
                Id = 1
            };
            var repositoryMock = new Mock <IRepositoryWrapper>();

            repositoryMock.Setup(r => r.UserRepository.GetUserAsync(1)).ReturnsAsync(() => user);
            var mapperMock   = new Mock <IMapper>();
            var userToReturn = new UserForDetailedDto {
                Id = 1
            };

            mapperMock.Setup(m => m.Map <UserForDetailedDto>(user)).Returns(() => userToReturn);
            var controllerMock = new UsersController(repositoryMock.Object, mapperMock.Object);

            var result = await controllerMock.GetUserAsync(1) as OkObjectResult;

            Assert.IsType <OkObjectResult>(result);
            Assert.Equal(userToReturn, result.Value);
        }
コード例 #21
0
        public async Task <IActionResult> UpdateUser([FromRoute] int id, [FromBody] UserForDetailedDto userForUpdateDto)
        {
            if (id != userForUpdateDto.Id)
            {
                return(BadRequest());
            }

            var userFromRepo = await _repo.GetUser(id);

            userFromRepo.UserName = userForUpdateDto.Username;
            userFromRepo.City     = userForUpdateDto.City;
            userFromRepo.Country  = userForUpdateDto.Country;
            //var user = _mapper.Map<User>(userForUpdateDto);
            var temp = await _repo.UpdateUser(userFromRepo);

            if (temp)
            {
                return(Ok(await _repo.GetUser(id)));
            }
            else
            {
                return(BadRequest());
            }
        }
コード例 #22
0
        public void AddUserToDivisions(UserForRegisterDto userForRegister, User user, UserForDetailedDto userForDetailed)
        {
            if (userForRegister.Year != 0)
            {
                var specialization = _specializationsRepo.GetSpecializationByName(userForRegister.Specialization);

                var group = _groupsRepo.GetGroupByName(userForRegister.Group);

                var subGroup = _subGroupsRepo.GetSubGroupByName(userForRegister.SubGroup);

                UserSpecialization userSpecialization = new UserSpecialization
                {
                    UserId           = user.Id,
                    SpecializationId = specialization.Id
                };

                _genericsRepo.Add(userSpecialization);

                UserGroup userGroup = new UserGroup
                {
                    UserId  = user.Id,
                    GroupId = group.Id
                };

                _genericsRepo.Add(userGroup);

                UserSubGroup userSubGroup = new UserSubGroup
                {
                    UserId     = user.Id,
                    SubGroupId = subGroup.Id
                };

                _genericsRepo.Add(userSubGroup);

                userForDetailed.Specialization = specialization.Name;
                userForDetailed.Group          = group.Name;
                userForDetailed.SubGroup       = subGroup.Name;

                _genericsRepo.SaveAll();
            }
        }