示例#1
0
        public async Task <bool> CreateCoachAsync(CreateCoachInputModel input, ApplicationUser user)
        {
            string folderName   = "coach_images";
            var    inputPicture = input.UserImage;
            var    pictureUrl   = await this.cloudinaryService.UploadPhotoAsync(inputPicture, inputPicture.FileName, folderName);

            var coach = new Coach
            {
                Name        = input.FullName,
                Email       = input.Email,
                Description = input.Description,
                Phone       = input.Phone,
                Experience  = input.Experience,
                Picture     = new Picture {
                    Url = pictureUrl
                },
                User   = user,
                UserId = user.Id,
            };

            if (coach != null && coach.Experience > 0)
            {
                await this.coachRepository.AddAsync(coach);

                await this.coachRepository.SaveChangesAsync();

                return(true);
            }

            throw new InvalidOperationException(GlobalConstants.InvalidOperationExceptionWhileCreatingCoach);
        }
        public async Task CreateCoachShouldWorkWithCorrectData()
        {
            var coaches = new List <Coach>();

            this.coachRepository.Setup(r => r.AllAsNoTracking()).Returns(() => coaches.AsQueryable());

            this.coachRepository.Setup(r => r.AddAsync(It.IsAny <Coach>())).Callback((Coach coach) => coaches.Add(coach));

            // Arrange
            var fileMock = new Mock <IFormFile>();

            // Setup mock file using a memory stream
            var content  = "Hello World from a Fake File";
            var fileName = "test.pdf";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);

            var file = fileMock.Object;

            var model = new CreateCoachInputModel
            {
                FullName    = "Coach One",
                Email       = "*****@*****.**",
                Experience  = 5,
                Description = "test description for coach",
                Phone       = "088",
                UserImage   = file,
            };

            var appUser = new ApplicationUser {
                Id = "coachuserId", Email = "*****@*****.**"
            };

            var result = await this.coachesService.CreateCoachAsync(model, appUser);

            Assert.Contains(coaches, x => x.Name == "Coach One");
            Assert.Single(coaches);
            Assert.True(result);
            this.coachRepository.Verify(x => x.AllAsNoTracking(), Times.Never);
        }
        public async Task CreateCoachShouldThrowIOEWithInvalidData()
        {
            var coaches = new List <Coach>();

            this.coachRepository.Setup(r => r.AllAsNoTracking()).Returns(() => coaches.AsQueryable());

            this.coachRepository.Setup(r => r.AddAsync(It.IsAny <Coach>())).Callback((Coach coach) => coaches.Add(coach));

            // Arrange
            var fileMock = new Mock <IFormFile>();

            // Setup mock file using a memory stream
            var content  = "Hello World from a Fake File";
            var fileName = "test.pdf";
            var ms       = new MemoryStream();
            var writer   = new StreamWriter(ms);

            writer.Write(content);
            writer.Flush();
            ms.Position = 0;
            fileMock.Setup(_ => _.OpenReadStream()).Returns(ms);
            fileMock.Setup(_ => _.FileName).Returns(fileName);
            fileMock.Setup(_ => _.Length).Returns(ms.Length);

            var file = fileMock.Object;

            var model = new CreateCoachInputModel
            {
                FullName    = string.Empty,
                Email       = string.Empty,
                Experience  = 0,
                Description = string.Empty,
                Phone       = string.Empty,
                UserImage   = file,
            };

            var appUser = new ApplicationUser {
                Id = string.Empty, Email = string.Empty
            };

            await Assert.ThrowsAsync <InvalidOperationException>(() => this.coachesService.CreateCoachAsync(model, appUser));
        }
示例#4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (Input.SelectedRole == "Coach")
                {
                    var coachInputModel = new CreateCoachInputModel
                    {
                        FullName    = Input.FullName,
                        Email       = Input.Email,
                        Description = Input.Description,
                        Experience  = Input.Experience.HasValue ? Input.Experience.Value : 1,
                        Phone       = Input.Phone,
                        UserImage   = Input.UserImage,
                    };

                    var coachUser = _userManager.FindByEmailAsync(coachInputModel.Email).Result;
                    await _coachService.CreateCoachAsync(coachInputModel, coachUser);

                    await _userManager.AddToRoleAsync(user, GlobalConstants.CoachRoleName);
                }
                else
                {
                    var clientInputModel = new CreateClientInputModel
                    {
                        FullName       = Input.FullName,
                        Email          = Input.Email,
                        PositionPlayed = Input.PositionPlayed,
                        HasExperience  = Input.HasExperience,
                        Phone          = Input.Phone,
                    };

                    var clientUser = _userManager.FindByEmailAsync(clientInputModel.Email).Result;
                    await _clientService.CreateClientAsync(clientInputModel, clientUser);

                    await _userManager.AddToRoleAsync(user, GlobalConstants.ClientRoleName);
                }

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }