public async Task <IActionResult> OnGetAsync()
        {
            NetBookUser user = await this.userManager.GetUserAsync(this.User);

            if (user == null)
            {
                return(this.NotFound($"Грешка при намиране на потребителя '{user.FullName}'."));
            }

            string userName = this.User.FindFirst("FullName").Value;
            string email    = await this.userManager.GetEmailAsync(user);

            string phoneNumber = await this.userManager.GetPhoneNumberAsync(user);

            this.Username = userName;

            this.Input = new InputModel
            {
                Email       = email,
                PhoneNumber = phoneNumber,
            };

            this.IsEmailConfirmed = await this.userManager.IsEmailConfirmedAsync(user);

            return(this.Page());
        }
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Page());
            }

            NetBookUser user = await this.userManager.GetUserAsync(this.User);

            if (user == null)
            {
                return(this.NotFound($"Грешка при намиране на потребителя '{user.FullName}'."));
            }

            string userId = await this.userManager.GetUserIdAsync(user);

            string email = await this.userManager.GetEmailAsync(user);

            string code = await this.userManager.GenerateEmailConfirmationTokenAsync(user);

            string callbackUrl = this.Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId = userId, code = code },
                protocol: this.Request.Scheme);

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

            this.StatusMessage = "Verification email sent. Please check your email.";
            return(this.RedirectToPage());
        }
Esempio n. 3
0
 protected override IdentityUserLogin <string> CreateUserLogin(NetBookUser user, UserLoginInfo login) =>
 new IdentityUserLogin <string>
 {
     UserId              = user.Id,
     ProviderKey         = login.ProviderKey,
     LoginProvider       = login.LoginProvider,
     ProviderDisplayName = login.ProviderDisplayName,
 };
Esempio n. 4
0
        protected override IdentityUserClaim <string> CreateUserClaim(NetBookUser user, Claim claim)
        {
            var identityUserClaim = new IdentityUserClaim <string> {
                UserId = user.Id
            };

            identityUserClaim.InitializeFromClaim(claim);
            return(identityUserClaim);
        }
Esempio n. 5
0
        protected override IdentityUserToken <string> CreateUserToken(
            NetBookUser user,
            string loginProvider,
            string name,
            string value)
        {
            var token = new IdentityUserToken <string>
            {
                UserId        = user.Id,
                LoginProvider = loginProvider,
                Name          = name,
                Value         = value,
            };

            return(token);
        }
        public async Task <IActionResult> OnPostAsync()
        {
            if (!this.ModelState.IsValid)
            {
                return(this.Page());
            }

            NetBookUser user = await this.userManager.GetUserAsync(this.User);

            if (user == null)
            {
                return(this.NotFound($"Грешка при намиране на потребителя '{user.FullName}'."));
            }

            string email = await this.userManager.GetEmailAsync(user);

            if (this.Input.Email != email)
            {
                var setEmailResult = await this.userManager.SetEmailAsync(user, this.Input.Email);

                var setUserNameResult = await this.userManager.SetUserNameAsync(user, this.Input.Email);

                if (!setEmailResult.Succeeded || !setUserNameResult.Succeeded)
                {
                    string userId = await this.userManager.GetUserIdAsync(user);

                    throw new InvalidOperationException($"Възникна неочаквана грешка при смяната на електронната поща/името.");
                }
            }

            string phoneNumber = await this.userManager.GetPhoneNumberAsync(user);

            if (this.Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await this.userManager.SetPhoneNumberAsync(user, this.Input.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    throw new InvalidOperationException($"Възникна неочаквана грешка при смяната на телефона на потребителя {user.FullName}.");
                }
            }

            await this.signInManager.RefreshSignInAsync(user);

            this.StatusMessage = "Промените се запазиха!";
            return(this.RedirectToPage());
        }
Esempio n. 7
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? this.Url.Content("~/");

            // Get the information about the user from the external login provider
            var info = await this.signInManager.GetExternalLoginInfoAsync();

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

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

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

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

                        this.logger.LogInformation(
                            "User created an account using {Name} provider.",
                            info.LoginProvider);
                        return(this.LocalRedirect(returnUrl));
                    }
                }

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

            this.LoginProvider = info.LoginProvider;
            this.ReturnUrl     = returnUrl;
            return(this.Page());
        }
        private async Task LoadSharedKeyAndQrCodeUriAsync(NetBookUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await this.userManager.GetAuthenticatorKeyAsync(user);

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

                unformattedKey = await this.userManager.GetAuthenticatorKeyAsync(user);
            }

            this.SharedKey = this.FormatKey(unformattedKey);

            var email = await this.userManager.GetEmailAsync(user);

            this.AuthenticatorUri = this.GenerateQrCodeUri(email, unformattedKey);
        }
Esempio n. 9
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? this.Url.Content("~/");

            if (this.ModelState.IsValid && (this.Input.RegisterCode == GlobalConstants.RegisterTeacherCode || this.Input.RegisterCode == GlobalConstants.RegisterAdministratorCode))
            {
                var user = new NetBookUser {
                    UserName = this.Input.Email, Email = this.Input.Email, FullName = this.Input.FullName, PhoneNumber = this.Input.PhoneNumber
                };

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

                if (result.Succeeded)
                {
                    if (this.Input.RegisterCode == GlobalConstants.RegisterTeacherCode)
                    {
                        var roleResult = await this.userManager.AddToRoleAsync(user, GlobalConstants.TeacherRoleName);

                        await this.userService.AddUserAsTeacherAsync(user.Id);
                    }
                    else if (this.Input.RegisterCode == GlobalConstants.RegisterAdministratorCode)
                    {
                        var roleResult =
                            await this.userManager.AddToRoleAsync(user, GlobalConstants.AdministratorRoleName);
                    }

                    this.logger.LogInformation("User created a new account with password.");

                    returnUrl = "/Identity/Account/Home";

                    await this.signInManager.SignInAsync(user, isPersistent : false);

                    return(this.LocalRedirect(returnUrl));
                }

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

            // If we got this far, something failed, redisplay form
            return(this.Page());
        }
        public async Task CreateClass_WithCorrectData_ShouldSuccessfullyCreateClass()
        {
            string errorMessagePrefix = "ClassService CreateClassAsync() does not work properly.";

            var context = NetBookDbContextInMemoryFactory.InitializeContext();

            await this.SeedData(context);

            this.classService = new ClassService(context);

            var testTeacher = new NetBookUser
            {
                Id        = "test",
                FullName  = "TestTeacher",
                IsTeacher = false,
            };

            await context.Users.AddAsync(testTeacher);

            await context.SaveChangesAsync();

            var testClass = new ClassServiceModel
            {
                Id             = "testClass",
                ClassTeacherId = testTeacher.Id,
                ClassTeacher   = testTeacher.To <UserServiceModel>(),
            };

            var actualResult = await this.classService.CreateClassAsync(testClass);

            var updatedTeacher = context.Users.Find("test");
            var classId        = updatedTeacher.ClassId;
            var isClassTeacher = updatedTeacher.IsClassTeacher;

            Assert.True(actualResult, errorMessagePrefix);
            Assert.True(isClassTeacher, errorMessagePrefix + " " + "IsClassTeacher is not set properly");
            Assert.True(classId == "testClass", errorMessagePrefix + " " + "ClassId is not set properly to Teacher.");
        }
Esempio n. 11
0
 protected override IdentityUserRole <string> CreateUserRole(NetBookUser user, NetBookRole role)
 {
     return(new IdentityUserRole <string> {
         RoleId = role.Id, UserId = user.Id
     });
 }