ASP NET CORE RAZOR PAGE BAKIM TEKNİK SERVİS PROJE 053 EMAİL DOĞRULAMA İŞLEMLERİ BÖLÜM 2

Email Doğrulama işlemlerine bu dersimizde devam ediyoruz ve mevcut hatalarımızı, eksikliklerimizi gideriyoruz. Amacımız email doğrulama işlemi için gönderilen mailde email doğrulama linkine tıklanana kadar sisteme girişin önüne geçilmesini sağlamak.

Detaylı anlatım ve kod takibi için mutlaka video eğitime bakınız.

ASP.Net Core Identity dosyaları içinde yer alan Login ve Register dosyalarında düzenleme yapacağım.

Areas > Identity >Pages > Account > Login.cshtml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using GursoyCNCBakim.Data;

namespace GursoyCNCBakim.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class LoginModel : PageModel
    {
        private readonly UserManager< IdentityUser > _userManager;
        private readonly SignInManager< IdentityUser > _signInManager;
        private readonly ILogger< LoginModel > _logger;
        private readonly ApplicationDbContext _db;
        

        public LoginModel(SignInManager< IdentityUser > signInManager, 
            ILogger< LoginModel > logger,
            UserManager< IdentityUser > userManager, ApplicationDbContext db)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _db = db;
           
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public IList< AuthenticationScheme > ExternalLogins { get; set; }

        public string ReturnUrl { get; set; }

        [TempData]
        public string ErrorMessage { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public bool RememberMe { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            returnUrl = returnUrl ?? Url.Content("~/");

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            ReturnUrl = returnUrl;
        }

        public async Task< IActionResult > OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true

                var user = _db.Users.FirstOrDefault(a => a.Email == Input.Email);

                if (user != null && !user.EmailConfirmed)
                {
                    return RedirectToPage("EmailDogrula", new { id = Input.Email });
                }
                

                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

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

Areas > Identity >Pages > Account > Register.cshtml.cs kodlarımızı yazalım.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using GursoyCNCBakim.Data;
using GursoyCNCBakim.Models;
using GursoyCNCBakim.Utility;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;

namespace GursoyCNCBakim.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class RegisterModel : PageModel
    {
        private readonly SignInManager< IdentityUser > _signInManager;
        private readonly UserManager< IdentityUser > _userManager;
        private readonly ILogger< RegisterModel > _logger;
        private readonly IEmailSender _emailSender;
        private readonly RoleManager< IdentityRole > _roleManager;
        private readonly ApplicationDbContext _db;

        public RegisterModel(
            UserManager< IdentityUser > userManager,
            SignInManager< IdentityUser > signInManager,
            ILogger< RegisterModel > logger,
            IEmailSender emailSender,
            RoleManager< IdentityRole > roleManager,
            ApplicationDbContext db)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _emailSender = emailSender;
            _db = db;
            _roleManager = roleManager;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public string ReturnUrl { get; set; }

        public IList< AuthenticationScheme > ExternalLogins { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            [Display(Name = "Email")]
            public string Email { get; set; }

            [Required]
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }

            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }

            [Required]
            public string AdSoyad { get; set; }
            public string Adres { get; set; }
            public string Sehir { get; set; }
            public string PostaKodu { get; set; }

            [Required]
            public string PhoneNumber { get; set; }

            public bool AdminMi { get; set; }

        }

        

        public async Task OnGetAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        }

        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,
                    AdSoyad = Input.AdSoyad,
                    Adres = Input.Adres,
                    Sehir = Input.Sehir,
                    PostaKodu = Input.PostaKodu,
                    PhoneNumber = Input.PhoneNumber
                };

                

                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    if (!await _roleManager.RoleExistsAsync(StatikRoller.AdminKullanici))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(StatikRoller.AdminKullanici));
                    }

                    if (!await _roleManager.RoleExistsAsync(StatikRoller.MusteriKullanici))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(StatikRoller.MusteriKullanici));
                    }

                    if (Input.AdminMi)
                    {
                        await _userManager.AddToRoleAsync(user, StatikRoller.AdminKullanici);

                        
                        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 clicking here.");


                        return RedirectToPage("/Kullanicilar/Index");
                    }

                    else
                    {
                        await _userManager.AddToRoleAsync(user, StatikRoller.MusteriKullanici);

                        //await _signInManager.SignInAsync(user, isPersistent: false);

                        if (User.IsInRole(StatikRoller.AdminKullanici))
                        {
                            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 clicking here.");


                            return RedirectToPage("/Kullanicilar/Index");
                        }
                        else
                        {
                            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 clicking here.");


                            return LocalRedirect(returnUrl);
                        }
                            
                        

                        
                    }

                    
                    

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



                    //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();
        }
    }
}

Detaylı anlatım ve kod takibi için videoya bakınız. Bir sonraki derste görüşmek üzere.

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir