Beispiel #1
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new CoreWikiUser
                {
                    UserName  = Input.Email,
                    Email     = Input.Email,
                    CanNotify = Input.CanNotify
                };

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

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    await _notificationService.SendConfirmationEmail(Input.Email, user.Id, code);

                    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());
        }
Beispiel #2
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(CoreWikiUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Beispiel #3
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            await Task.Run(async() => await System.Threading.Thread.Sleep(1000))
            .ContinueWith(async t => await Demo.Extensions.StartupExtensions._RestartHost());

            var newAdminUser = new CoreWikiUser
            {
                UserName    = this.FirstStartConfig.AdminUserName,
                DisplayName = this.FirstStartConfig.AdminDisplayName,
                Email       = this.FirstStartConfig.AdminEmail
            };

            var userResult = await UserManager.CreateAsync(newAdminUser, this.FirstStartConfig.AdminPassword);

            if (userResult.Succeeded)
            {
                var result = await UserManager.AddToRoleAsync(newAdminUser, "Administrators");
            }
            else
            {
                Logger.LogError($"Error creating user: {userResult.Errors.First().Description}");
                ModelState.AddModelError("", $"There was an error creating the admin user: {userResult.Errors.First().Description}");
                return(Page());
            }

            if (string.IsNullOrEmpty(FirstStartConfig.ConnectionString))
            {
                FirstStartConfig.ConnectionString = "DataSource=./App_Data/wikiContent.db";
                FirstStartConfig.Database         = "SQLite";
            }

            WriteConfigFileToDisk(this.FirstStartConfig.Database, this.FirstStartConfig.ConnectionString);

            Completed = true;
            return(Page());

            //return RedirectToPage("/Details", new { slug = "home-page" });
        }
Beispiel #4
0
		public async Task<IActionResult> OnPostAsync(string returnUrl = null)
		{
			returnUrl = returnUrl ?? Url.Content("~/");

			if (!ModelState.IsValid)
			{
				return Page();
			}

			var passwordCheck = await _HIBPClient.GetHitsPlainAsync(Input.Password);
			if (passwordCheck > 0)
			{
				ModelState.AddModelError(nameof(Input.Password), "This password is known to hackers, and can lead to your account being compromised, please try another password. For more info goto https://haveibeenpwned.com/Passwords");
				return Page();
			}

			var user = new CoreWikiUser
			{
				UserName = Input.UserName,
				DisplayName = Input.DisplayName,
				Email = Input.Email,
				CanNotify = Input.CanNotify
			};

			var result = await _userManager.CreateAsync(user, Input.Password);
			if (result.Succeeded)
			{
				_logger.LogInformation("User created a new account with password.");

				var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
				await _notificationService.SendConfirmationEmail(Input.Email, user.Id, code);

				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();
		}
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new CoreWikiUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Beispiel #6
0
        public async Task ShouldCreateNewNonExistingArticleAndRedirect_GivenUserIsAuthenticated()
        {
            var user = new CoreWikiUser
            {
                Id          = userId.ToString(),
                DisplayName = "Test User"
            };
            var userStoreMock = new Mock <IUserStore <CoreWikiUser> >();
            var userManager   = new Mock <UserManager <CoreWikiUser> >(
                userStoreMock.Object, null, null, null, null, null, null, null, null);

            userManager.Setup(m => m.GetUserAsync(It.IsAny <ClaimsPrincipal>())).Returns(Task.FromResult(user));


            var expectedCommand = new CreateNewArticleCommand
            {
                Topic      = _topic,
                AuthorId   = userId,
                Content    = _content,
                AuthorName = username
            };

            _mediator.Setup(mediator => mediator.Send(It.IsAny <CreateNewArticleCommand>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(new CommandResult {
                Successful = true, ObjectId = _expectedSlug
            }));

            _mediator.Setup(mediator => mediator.Send(It.IsAny <GetIsTopicAvailableQuery>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(false));

            _mediator.Setup(mediator => mediator.Send(It.IsAny <GetArticlesToCreateFromArticleQuery>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult((_expectedSlug, new string[] { })));

            _sut = new CreateModel(_mediator.Object, _mapper, new NullLoggerFactory(), userManager.Object)
            {
                Article = new ArticleCreate
                {
                    Topic   = _topic,
                    Content = _content
                }
            };

            //we depend on a valid ClaimsPrinciple!! No check on User yet before sending the command
            _sut.AddPageContext(username, userId);
            var result = await _sut.OnPostAsync();

            Assert.IsType <RedirectToPageResult>(result);
            Assert.Equal(_expectedSlug, ((RedirectToPageResult)result).RouteValues["slug"]);
            _mediator.Verify(m => m.Send(
                                 It.Is <GetIsTopicAvailableQuery>(request =>
                                                                  request.ArticleId.Equals(0) &&
                                                                  request.Topic.Equals(_topic)),
                                 It.Is <CancellationToken>(token => token.Equals(CancellationToken.None))), Times.Once
                             );
            _mediator.Verify(m => m.Send(
                                 It.Is <CreateNewArticleCommand>(request =>
                                                                 request.Topic.Equals(expectedCommand.Topic) &&
                                                                 request.AuthorName.Equals(user.DisplayName) &&
                                                                 request.Content.Equals(expectedCommand.Content) &&
                                                                 request.AuthorId.Equals(userId)),
                                 It.Is <CancellationToken>(token => token.Equals(CancellationToken.None))), Times.Once);
        }