From 22086c9ed5ac539f1f723bfdd669241452174c53 Mon Sep 17 00:00:00 2001 From: skrawus Date: Thu, 6 Jun 2024 15:36:00 +0200 Subject: [PATCH 01/23] Create SendActivationEmail method --- .../Controllers/AccountController.cs | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 6390d7eb..2233542c 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -1,5 +1,7 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using System.Net; +using System.Net.Mail; using TutorLizard.BusinessLogic.Enums; using TutorLizard.BusinessLogic.Interfaces.Services; using TutorLizard.Web.Interfaces.Services; @@ -81,7 +83,10 @@ public async Task Register(RegisterUserModel model) if (ModelState.IsValid && await _userAuthenticationService.RegisterUser(model.UserName, UserType.Regular, model.Email, model.Password)) { - _uiMessagesService.ShowSuccessMessage("Użytkownik zarejestrowany."); + string activationCode = GenerateActivationCode(); + SendActivationEmail(model.Email, activationCode); + + _uiMessagesService.ShowSuccessMessage("Wysłano mail aktywacyjny."); return LocalRedirect("/Home/Index"); } } @@ -94,7 +99,40 @@ public async Task Register(RegisterUserModel model) return LocalRedirect("/Home/Index"); } - public IActionResult AccessDenied() + private string GenerateActivationCode() + { + return Guid.NewGuid().ToString(); + } + + public void SendActivationEmail(string userEmail, string activationCode) +{ + var fromAddress = new MailAddress("lizardtutoring@gmail.com", "Tutor Lizard"); + var toAddress = new MailAddress(userEmail); + const string fromPassword = "pvez johg nzwc enjg"; + string subject = "Aktywacja konta"; + string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: \nhttp://localhost:7092/activation/{activationCode}"; + + var smtp = new SmtpClient + { + Host = "smtp.gmail.com", + Port = 587, + EnableSsl = true, + DeliveryMethod = SmtpDeliveryMethod.Network, + UseDefaultCredentials = false, + Credentials = new NetworkCredential(fromAddress.Address, fromPassword) + }; + using (var message = new MailMessage(fromAddress, toAddress) + { + Subject = subject, + Body = body + }) + { + smtp.Send(message); + } +} + + +public IActionResult AccessDenied() { return View(); } From 0a71588e64a631f854e93491cff6593d5e26ba88 Mon Sep 17 00:00:00 2001 From: skrawus Date: Thu, 6 Jun 2024 21:37:46 +0200 Subject: [PATCH 02/23] Create Activation emails --- .../Data/JaszczurContext.cs | 5 + .../Interfaces/Services/IUserService.cs | 2 +- TutorLizard.BusinessLogic/Models/User.cs | 2 + .../Services/UserService.cs | 6 +- .../Controllers/AccountController.cs | 75 ++-- .../Services/IUserAuthenticationService.cs | 5 +- ...06152246_Add-Activation-Emails.Designer.cs | 345 ++++++++++++++++++ .../20240606152246_Add-Activation-Emails.cs | 40 ++ .../JaszczurContextModelSnapshot.cs | 9 + TutorLizard.Web/Program.cs | 12 + .../Services/UserAuthenticationService.cs | 67 +++- .../Views/Account/ActivateAccount.cshtml | 7 + 12 files changed, 534 insertions(+), 41 deletions(-) create mode 100644 TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.Designer.cs create mode 100644 TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.cs create mode 100644 TutorLizard.Web/Views/Account/ActivateAccount.cshtml diff --git a/TutorLizard.BusinessLogic/Data/JaszczurContext.cs b/TutorLizard.BusinessLogic/Data/JaszczurContext.cs index b8de0174..284b26c9 100644 --- a/TutorLizard.BusinessLogic/Data/JaszczurContext.cs +++ b/TutorLizard.BusinessLogic/Data/JaszczurContext.cs @@ -20,6 +20,11 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .Property(user => user.Id) .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(user => user.IsActive) + .HasDefaultValue(false) + .IsRequired(); + modelBuilder.Entity() .Property(user => user.UserType) .HasConversion(); diff --git a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs index 9c1bfa0f..75d14132 100644 --- a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs +++ b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs @@ -6,5 +6,5 @@ namespace TutorLizard.BusinessLogic.Interfaces.Services; public interface IUserService { public Task LogIn(string username, string password); - public Task RegisterUser(string userName, UserType type, string email, string password); + public Task RegisterUser(string userName, UserType type, string email, string password, string activationCode); } diff --git a/TutorLizard.BusinessLogic/Models/User.cs b/TutorLizard.BusinessLogic/Models/User.cs index 59ac7641..0193e4d0 100644 --- a/TutorLizard.BusinessLogic/Models/User.cs +++ b/TutorLizard.BusinessLogic/Models/User.cs @@ -6,6 +6,7 @@ namespace TutorLizard.BusinessLogic.Models; public class User { public int Id { get; set; } + public bool? IsActive { get; set; } [Required] [MinLength(5)] @@ -43,4 +44,5 @@ public User() public ICollection Ads { get; set; } = new List(); public ICollection AdRequests { get; set; } = new List(); public ICollection ScheduleItemRequests { get; set; } = new List(); + public string ActivationCode { get; set; } } diff --git a/TutorLizard.BusinessLogic/Services/UserService.cs b/TutorLizard.BusinessLogic/Services/UserService.cs index 4110ccb5..0c362818 100644 --- a/TutorLizard.BusinessLogic/Services/UserService.cs +++ b/TutorLizard.BusinessLogic/Services/UserService.cs @@ -39,7 +39,7 @@ public UserService(IDbRepository userRepository) return null; } - public async Task RegisterUser(string userName, UserType type, string email, string password) + public async Task RegisterUser(string userName, UserType type, string email, string password, string activationCode) { if (await _userRepository.GetAll().AnyAsync(user => user.Name == userName)) return false; @@ -49,7 +49,9 @@ public async Task RegisterUser(string userName, UserType type, string emai Name = userName, UserType = type, Email = email, - PasswordHash = password + PasswordHash = password, + ActivationCode = activationCode, + IsActive = false }; user.PasswordHash = _passwordHasher.HashPassword(user, password); diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 2233542c..4a1e8251 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -48,12 +48,20 @@ public async Task Login(LoginModel model) { if (ModelState.IsValid && await _userAuthenticationService.LogInAsync(model.UserName, model.Password)) { - _uiMessagesService.ShowSuccessMessage("Jesteś zalogowany/a."); - if (string.IsNullOrEmpty(returnUrl)) + if (await _userAuthenticationService.IsUserActive(model.UserName)) { - return RedirectToAction("Index", "Home"); + _uiMessagesService.ShowSuccessMessage("Jesteś zalogowany/a."); + if (string.IsNullOrEmpty(returnUrl)) + { + return RedirectToAction("Index", "Home"); + } + return Redirect(returnUrl); + } + else + { + _uiMessagesService.ShowFailureMessage("Logowanie nieudane"); + return LocalRedirect("/Home/Index"); } - return Redirect(returnUrl); } } catch @@ -64,6 +72,7 @@ public async Task Login(LoginModel model) _uiMessagesService.ShowFailureMessage("Logowanie nieudane."); return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); } + [Authorize] public async Task Logout() { @@ -74,18 +83,30 @@ public IActionResult Register() { return View(); } + [HttpPost] [ValidateAntiForgeryToken] public async Task Register(RegisterUserModel model) { try { - if (ModelState.IsValid - && await _userAuthenticationService.RegisterUser(model.UserName, UserType.Regular, model.Email, model.Password)) + if (!ModelState.IsValid) { - string activationCode = GenerateActivationCode(); - SendActivationEmail(model.Email, activationCode); + var errors = ModelState.Values.SelectMany(v => v.Errors); + foreach (var error in errors) + { + Console.WriteLine(error.ErrorMessage); + } + return View(model); + } + + string activationCode = GenerateActivationCode(); + bool registrationResult = await _userAuthenticationService.RegisterUser( + model.UserName, UserType.Regular, model.Email, model.Password, activationCode); + if (registrationResult) + { + _userAuthenticationService.SendActivationEmail(model.Email, activationCode); _uiMessagesService.ShowSuccessMessage("Wysłano mail aktywacyjny."); return LocalRedirect("/Home/Index"); } @@ -104,35 +125,21 @@ private string GenerateActivationCode() return Guid.NewGuid().ToString(); } - public void SendActivationEmail(string userEmail, string activationCode) -{ - var fromAddress = new MailAddress("lizardtutoring@gmail.com", "Tutor Lizard"); - var toAddress = new MailAddress(userEmail); - const string fromPassword = "pvez johg nzwc enjg"; - string subject = "Aktywacja konta"; - string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: \nhttp://localhost:7092/activation/{activationCode}"; - - var smtp = new SmtpClient + [HttpGet] + public IActionResult ActivateAccount(string activationCode) { - Host = "smtp.gmail.com", - Port = 587, - EnableSsl = true, - DeliveryMethod = SmtpDeliveryMethod.Network, - UseDefaultCredentials = false, - Credentials = new NetworkCredential(fromAddress.Address, fromPassword) - }; - using (var message = new MailMessage(fromAddress, toAddress) - { - Subject = subject, - Body = body - }) - { - smtp.Send(message); + if (_userAuthenticationService.ActivateUser(activationCode)) + { + return View("Account/ActivateAccount"); + } + else + { + _uiMessagesService.ShowFailureMessage("Wystąpił błąd. Rejestracja nieudana."); + return LocalRedirect("/Home/Index"); + } } -} - -public IActionResult AccessDenied() + public IActionResult AccessDenied() { return View(); } diff --git a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs index 73b079b0..08f8a823 100644 --- a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs +++ b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs @@ -8,5 +8,8 @@ public interface IUserAuthenticationService int? GetLoggedInUserId(); public Task LogInAsync(string username, string password); public Task LogOutAsync(); - public Task RegisterUser(string username, UserType type, string email, string password); + public Task RegisterUser(string username, UserType type, string email, string password, string activationCode); + bool ActivateUser(string activationCode); + Task IsUserActive(string userName); + void SendActivationEmail(string email, string activationCode); } diff --git a/TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.Designer.cs b/TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.Designer.cs new file mode 100644 index 00000000..69e4f217 --- /dev/null +++ b/TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.Designer.cs @@ -0,0 +1,345 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using TutorLizard.BusinessLogic.Data; + +#nullable disable + +namespace TutorLizard.Web.Migrations +{ + [DbContext(typeof(JaszczurContext))] + [Migration("20240606152246_Add-Activation-Emails")] + partial class AddActivationEmails + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.Ad", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("CategoryId") + .HasColumnType("int"); + + b.Property("DateCreated") + .HasColumnType("datetime2"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(3000) + .HasColumnType("nvarchar(3000)"); + + b.Property("IsRemote") + .HasColumnType("bit"); + + b.Property("Location") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Price") + .HasPrecision(7, 2) + .HasColumnType("decimal(7,2)"); + + b.Property("Subject") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("TutorId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("CategoryId"); + + b.HasIndex("TutorId"); + + b.ToTable("Ads"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.AdRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AdId") + .HasColumnType("int"); + + b.Property("DateCreated") + .HasColumnType("datetime2"); + + b.Property("IsAccepted") + .HasColumnType("bit"); + + b.Property("IsRemote") + .HasColumnType("bit"); + + b.Property("Message") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("ReplyMessage") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("ReviewDate") + .HasColumnType("datetime2"); + + b.Property("StudentId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AdId"); + + b.HasIndex("StudentId"); + + b.ToTable("AdRequests"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.Category", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DateCreated") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.HasKey("Id"); + + b.ToTable("Categories"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.ScheduleItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AdId") + .HasColumnType("int"); + + b.Property("DateCreated") + .HasColumnType("datetime2"); + + b.Property("DateTime") + .HasColumnType("datetime2"); + + b.HasKey("Id"); + + b.HasIndex("AdId"); + + b.ToTable("ScheduleItems"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.ScheduleItemRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("DateCreated") + .HasColumnType("datetime2"); + + b.Property("IsAccepted") + .HasColumnType("bit"); + + b.Property("IsRemote") + .HasColumnType("bit"); + + b.Property("ScheduleItemId") + .HasColumnType("int"); + + b.Property("StudentId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ScheduleItemId"); + + b.HasIndex("StudentId"); + + b.ToTable("ScheduleItemRequests"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ActivationCode") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateCreated") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("Name") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UserType") + .HasColumnType("tinyint"); + + b.HasKey("Id"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.Ad", b => + { + b.HasOne("TutorLizard.BusinessLogic.Models.Category", "Category") + .WithMany("Ads") + .HasForeignKey("CategoryId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("TutorLizard.BusinessLogic.Models.User", "User") + .WithMany("Ads") + .HasForeignKey("TutorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Category"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.AdRequest", b => + { + b.HasOne("TutorLizard.BusinessLogic.Models.Ad", "Ad") + .WithMany("AdRequests") + .HasForeignKey("AdId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("TutorLizard.BusinessLogic.Models.User", "User") + .WithMany("AdRequests") + .HasForeignKey("StudentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Ad"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.ScheduleItem", b => + { + b.HasOne("TutorLizard.BusinessLogic.Models.Ad", "Ad") + .WithMany("ScheduleItems") + .HasForeignKey("AdId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Ad"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.ScheduleItemRequest", b => + { + b.HasOne("TutorLizard.BusinessLogic.Models.ScheduleItem", "ScheduleItem") + .WithMany("ScheduleItemRequests") + .HasForeignKey("ScheduleItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("TutorLizard.BusinessLogic.Models.User", "User") + .WithMany("ScheduleItemRequests") + .HasForeignKey("StudentId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ScheduleItem"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.Ad", b => + { + b.Navigation("AdRequests"); + + b.Navigation("ScheduleItems"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.Category", b => + { + b.Navigation("Ads"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.ScheduleItem", b => + { + b.Navigation("ScheduleItemRequests"); + }); + + modelBuilder.Entity("TutorLizard.BusinessLogic.Models.User", b => + { + b.Navigation("AdRequests"); + + b.Navigation("Ads"); + + b.Navigation("ScheduleItemRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.cs b/TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.cs new file mode 100644 index 00000000..14a7d81c --- /dev/null +++ b/TutorLizard.Web/Migrations/20240606152246_Add-Activation-Emails.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace TutorLizard.Web.Migrations +{ + /// + public partial class AddActivationEmails : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ActivationCode", + table: "Users", + type: "nvarchar(max)", + nullable: false, + defaultValue: ""); + + migrationBuilder.AddColumn( + name: "IsActive", + table: "Users", + type: "bit", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "ActivationCode", + table: "Users"); + + migrationBuilder.DropColumn( + name: "IsActive", + table: "Users"); + } + } +} diff --git a/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs b/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs index 146d001c..b113965c 100644 --- a/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs +++ b/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs @@ -208,6 +208,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + b.Property("ActivationCode") + .IsRequired() + .HasColumnType("nvarchar(max)"); + b.Property("DateCreated") .HasColumnType("datetime2"); @@ -216,6 +220,11 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(100) .HasColumnType("nvarchar(100)"); + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + b.Property("Name") .IsRequired() .HasMaxLength(40) diff --git a/TutorLizard.Web/Program.cs b/TutorLizard.Web/Program.cs index c5f558c6..23306a16 100644 --- a/TutorLizard.Web/Program.cs +++ b/TutorLizard.Web/Program.cs @@ -67,6 +67,18 @@ app.UseAuthorization(); +app.UseEndpoints(endpoints => +{ + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapControllerRoute( + name: "ActivateAccount", + pattern: "{controller=Account}/{action=ActivateAccount}/{activationCode?}"); +}); + + + app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index c1c0519a..1543d979 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -1,6 +1,9 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; +using System.Net.Mail; +using System.Net; using System.Security.Claims; +using TutorLizard.BusinessLogic.Data; using TutorLizard.BusinessLogic.Enums; using TutorLizard.BusinessLogic.Interfaces.Services; @@ -10,11 +13,13 @@ public class UserAuthenticationService : IUserAuthenticationService { private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUserService _userService; + private readonly JaszczurContext _dbContext; - public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService) + public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, JaszczurContext dbContext) { _httpContextAccessor = httpContextAccessor; _userService = userService; + _dbContext = dbContext; } public async Task LogInAsync(string username, string password) { @@ -61,9 +66,9 @@ public async Task LogOutAsync() await _httpContextAccessor.HttpContext.SignOutAsync("CookieAuth"); } - public Task RegisterUser(string username, UserType type, string email, string password) + public Task RegisterUser(string username, UserType type, string email, string password, string activationCode) { - return _userService.RegisterUser(username, type, email, password); + return _userService.RegisterUser(username, type, email, password, activationCode); } public int? GetLoggedInUserId() @@ -84,4 +89,60 @@ public Task RegisterUser(string username, UserType type, string email, str } return userId; } + + public void SendActivationEmail(string userEmail, string activationCode) + { + var fromAddress = new MailAddress("lizardtutoring@gmail.com", "Tutor Lizard"); + var toAddress = new MailAddress(userEmail); + const string fromPassword = "pvez johg nzwc enjg"; + string subject = "Aktywacja konta"; + string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: \nhttp://localhost:7092/Account/ActivateAccount/{activationCode}"; + + var smtp = new SmtpClient + { + Host = "smtp.gmail.com", + Port = 587, + EnableSsl = true, + DeliveryMethod = SmtpDeliveryMethod.Network, + UseDefaultCredentials = false, + Credentials = new NetworkCredential(fromAddress.Address, fromPassword) + }; + using (var message = new MailMessage(fromAddress, toAddress) + { + Subject = subject, + Body = body + }) + { + smtp.Send(message); + } + } + + public bool ActivateUser(string activationCode) + { + var user = _dbContext.Users.FirstOrDefault(u => u.ActivationCode == activationCode); + + if (user != null) + { + user.IsActive = true; + user.ActivationCode = null; + _dbContext.SaveChanges(); + return true; + } + return false; + } + + public async Task IsUserActive(string userName) + { + int? userId = GetLoggedInUserId(); + + if (userId.HasValue) + { + var user = await _dbContext.Users.FindAsync(userId.Value); + if (user != null && user.Name == userName) + { + return (bool)user.IsActive; + } + } + return false; + } } diff --git a/TutorLizard.Web/Views/Account/ActivateAccount.cshtml b/TutorLizard.Web/Views/Account/ActivateAccount.cshtml new file mode 100644 index 00000000..b1cdea67 --- /dev/null +++ b/TutorLizard.Web/Views/Account/ActivateAccount.cshtml @@ -0,0 +1,7 @@ +@{ + ViewData["Title"] = "Aktywacja maila"; +} +

@ViewData["Title"]

+ +

Aktywacja konta

+

Twoje konto zostało aktywowane.

\ No newline at end of file From c3b9ba268f45b5bd3263d820ead62fb8e61f8491 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 7 Jun 2024 21:13:06 +0200 Subject: [PATCH 03/23] Make ActivationCode nullable --- TutorLizard.BusinessLogic/Models/User.cs | 2 +- TutorLizard.Web/Services/UserAuthenticationService.cs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/TutorLizard.BusinessLogic/Models/User.cs b/TutorLizard.BusinessLogic/Models/User.cs index 0193e4d0..5633c046 100644 --- a/TutorLizard.BusinessLogic/Models/User.cs +++ b/TutorLizard.BusinessLogic/Models/User.cs @@ -44,5 +44,5 @@ public User() public ICollection Ads { get; set; } = new List(); public ICollection AdRequests { get; set; } = new List(); public ICollection ScheduleItemRequests { get; set; } = new List(); - public string ActivationCode { get; set; } + public string? ActivationCode { get; set; } } diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index 1543d979..45107cb3 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -6,6 +6,7 @@ using TutorLizard.BusinessLogic.Data; using TutorLizard.BusinessLogic.Enums; using TutorLizard.BusinessLogic.Interfaces.Services; +using TutorLizard.BusinessLogic.Interfaces.Data.Repositories; namespace TutorLizard.BusinessLogic.Services; @@ -21,6 +22,7 @@ public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUser _userService = userService; _dbContext = dbContext; } + public async Task LogInAsync(string username, string password) { var user = await _userService.LogIn(username, password); From cf19d581cef1ed531796e7bd85b65e1767c13013 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 7 Jun 2024 22:05:10 +0200 Subject: [PATCH 04/23] Make ActivateUser method async --- TutorLizard.Web/Controllers/AccountController.cs | 7 +++++-- .../Interfaces/Services/IUserAuthenticationService.cs | 2 +- TutorLizard.Web/Services/UserAuthenticationService.cs | 9 ++++++--- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 4a1e8251..61a38379 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -126,9 +126,11 @@ private string GenerateActivationCode() } [HttpGet] - public IActionResult ActivateAccount(string activationCode) + public async Task ActivateAccount(string activationCode) { - if (_userAuthenticationService.ActivateUser(activationCode)) + bool isActivated = await _userAuthenticationService.ActivateUserAsync(activationCode); + + if (isActivated) { return View("Account/ActivateAccount"); } @@ -139,6 +141,7 @@ public IActionResult ActivateAccount(string activationCode) } } + public IActionResult AccessDenied() { return View(); diff --git a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs index 08f8a823..a224ccae 100644 --- a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs +++ b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs @@ -9,7 +9,7 @@ public interface IUserAuthenticationService public Task LogInAsync(string username, string password); public Task LogOutAsync(); public Task RegisterUser(string username, UserType type, string email, string password, string activationCode); - bool ActivateUser(string activationCode); + Task ActivateUserAsync(string activationCode); Task IsUserActive(string userName); void SendActivationEmail(string email, string activationCode); } diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index 45107cb3..e585fcac 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -7,6 +7,7 @@ using TutorLizard.BusinessLogic.Enums; using TutorLizard.BusinessLogic.Interfaces.Services; using TutorLizard.BusinessLogic.Interfaces.Data.Repositories; +using Microsoft.EntityFrameworkCore; namespace TutorLizard.BusinessLogic.Services; @@ -119,20 +120,22 @@ public void SendActivationEmail(string userEmail, string activationCode) } } - public bool ActivateUser(string activationCode) + public async Task ActivateUserAsync(string activationCode) { - var user = _dbContext.Users.FirstOrDefault(u => u.ActivationCode == activationCode); + var user = await _dbContext.Users + .FirstOrDefaultAsync(u => u.ActivationCode == activationCode && u.IsActive == false); if (user != null) { user.IsActive = true; user.ActivationCode = null; - _dbContext.SaveChanges(); + await _dbContext.SaveChangesAsync(); return true; } return false; } + public async Task IsUserActive(string userName) { int? userId = GetLoggedInUserId(); From 9c69231032c344b5cf507db81bc1a561d5bdad5b Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 7 Jun 2024 23:02:34 +0200 Subject: [PATCH 05/23] Correct return view and messages in ActivateAccount method --- TutorLizard.Web/Controllers/AccountController.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 61a38379..045bb123 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -132,11 +132,12 @@ public async Task ActivateAccount(string activationCode) if (isActivated) { - return View("Account/ActivateAccount"); + _uiMessagesService.ShowSuccessMessage("Atywacja udana."); + return View("ActivateAccount"); } else { - _uiMessagesService.ShowFailureMessage("Wystąpił błąd. Rejestracja nieudana."); + _uiMessagesService.ShowFailureMessage("Aktywacja konta nie powiodła się."); return LocalRedirect("/Home/Index"); } } From ce4d98dc44c3db7ca0b0845cbc56ba57659d572b Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 7 Jun 2024 23:04:02 +0200 Subject: [PATCH 06/23] Correct generating URL and change ActivationCode after activation --- TutorLizard.Web/Services/UserAuthenticationService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index e585fcac..9f82bc31 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -99,7 +99,7 @@ public void SendActivationEmail(string userEmail, string activationCode) var toAddress = new MailAddress(userEmail); const string fromPassword = "pvez johg nzwc enjg"; string subject = "Aktywacja konta"; - string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: \nhttp://localhost:7092/Account/ActivateAccount/{activationCode}"; + string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: \nhttp://localhost:7092/Account/ActivateAccount?activationCode={activationCode}"; var smtp = new SmtpClient { @@ -128,7 +128,7 @@ public async Task ActivateUserAsync(string activationCode) if (user != null) { user.IsActive = true; - user.ActivationCode = null; + user.ActivationCode = "DEACTIVATED"; await _dbContext.SaveChangesAsync(); return true; } From 21e66fbe7d59d4490373d6912ca3031aa9c59568 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 7 Jun 2024 23:34:51 +0200 Subject: [PATCH 07/23] Add IsActive to UserDto and edit LogIn It now allows only active users to login --- TutorLizard.BusinessLogic/Models/DTOs/UserDto.cs | 1 + TutorLizard.BusinessLogic/Services/UserService.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/TutorLizard.BusinessLogic/Models/DTOs/UserDto.cs b/TutorLizard.BusinessLogic/Models/DTOs/UserDto.cs index 3002b166..d04a7d69 100644 --- a/TutorLizard.BusinessLogic/Models/DTOs/UserDto.cs +++ b/TutorLizard.BusinessLogic/Models/DTOs/UserDto.cs @@ -5,6 +5,7 @@ namespace TutorLizard.BusinessLogic.Models.DTOs; public class UserDto { public int Id { get; set; } + public bool? IsActive { get; set; } [Required(ErrorMessage = "Podaj nazwę użytkownika.")] [Display(Name = "Nazwa użytkownika")] diff --git a/TutorLizard.BusinessLogic/Services/UserService.cs b/TutorLizard.BusinessLogic/Services/UserService.cs index 0c362818..714c9d5a 100644 --- a/TutorLizard.BusinessLogic/Services/UserService.cs +++ b/TutorLizard.BusinessLogic/Services/UserService.cs @@ -23,7 +23,7 @@ public UserService(IDbRepository userRepository) var user = await _userRepository.GetAll() .FirstOrDefaultAsync(user => user.Name == username); - if (user == null) + if (user == null || user.IsActive == false) { return null; } From 6913c4c7ac62aca5c9ea44380e476958ba353893 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 7 Jun 2024 23:44:35 +0200 Subject: [PATCH 08/23] Change Login method so it shows correct messages --- TutorLizard.Web/Controllers/AccountController.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 045bb123..3c451b20 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -59,18 +59,21 @@ public async Task Login(LoginModel model) } else { - _uiMessagesService.ShowFailureMessage("Logowanie nieudane"); + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Konto nie jest aktywne."); return LocalRedirect("/Home/Index"); } } + else + { + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Nieprawidłowa nazwa użytkownika lub hasło."); + return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); + } } catch { _uiMessagesService.ShowFailureMessage("Logowanie nieudane."); return LocalRedirect("/Home/Index"); } - _uiMessagesService.ShowFailureMessage("Logowanie nieudane."); - return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); } [Authorize] From c76eaa56ede692235f7f3febfe8ef84497b197bf Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 7 Jun 2024 23:47:12 +0200 Subject: [PATCH 09/23] Fix IsUserActive method --- TutorLizard.Web/Services/UserAuthenticationService.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index 9f82bc31..0ef2d4c1 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -138,16 +138,13 @@ public async Task ActivateUserAsync(string activationCode) public async Task IsUserActive(string userName) { - int? userId = GetLoggedInUserId(); + var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Name == userName); - if (userId.HasValue) + if (user != null) { - var user = await _dbContext.Users.FindAsync(userId.Value); - if (user != null && user.Name == userName) - { - return (bool)user.IsActive; - } + return (bool)user.IsActive; } return false; } + } From b708ad677e011eeabb849ad75d0f585153589eae Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 14 Jun 2024 15:32:15 +0200 Subject: [PATCH 10/23] Move sensitive data to userSecrets --- TutorLizard.Web/Controllers/AccountController.cs | 1 - TutorLizard.Web/Models/EmailSettings.cs | 13 +++++++++++++ TutorLizard.Web/Program.cs | 3 +++ .../Services/UserAuthenticationService.cs | 12 +++++++++--- 4 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 TutorLizard.Web/Models/EmailSettings.cs diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 3c451b20..17930a80 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -145,7 +145,6 @@ public async Task ActivateAccount(string activationCode) } } - public IActionResult AccessDenied() { return View(); diff --git a/TutorLizard.Web/Models/EmailSettings.cs b/TutorLizard.Web/Models/EmailSettings.cs new file mode 100644 index 00000000..79c4d3fe --- /dev/null +++ b/TutorLizard.Web/Models/EmailSettings.cs @@ -0,0 +1,13 @@ +namespace TutorLizard.Web.Models +{ + public class EmailSettings + { + public string MailAddress { get; set; } + public string Password { get; set; } + public string SmtpHost { get; set; } + public int SmtpPort { get; set; } + public string FromAddress { get; set; } + public string FromPassword { get; set; } + } + +} diff --git a/TutorLizard.Web/Program.cs b/TutorLizard.Web/Program.cs index 23306a16..072ffb23 100644 --- a/TutorLizard.Web/Program.cs +++ b/TutorLizard.Web/Program.cs @@ -5,6 +5,7 @@ using TutorLizard.BusinessLogic.Options; using TutorLizard.BusinessLogic.Services; using TutorLizard.Web.Interfaces.Services; +using TutorLizard.Web.Models; using TutorLizard.Web.Services; var builder = WebApplication.CreateBuilder(args); @@ -43,7 +44,9 @@ .LogTo(Console.WriteLine, LogLevel.Information); }); + builder.Services.AddTutorLizardDbRepositories(); +builder.Services.Configure(builder.Configuration.GetSection("EmailSettings")); var app = builder.Build(); diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index 0ef2d4c1..a5a1bdf8 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -8,6 +8,9 @@ using TutorLizard.BusinessLogic.Interfaces.Services; using TutorLizard.BusinessLogic.Interfaces.Data.Repositories; using Microsoft.EntityFrameworkCore; +using Newtonsoft.Json; +using TutorLizard.Web.Models; +using Microsoft.Extensions.Options; namespace TutorLizard.BusinessLogic.Services; @@ -16,12 +19,14 @@ public class UserAuthenticationService : IUserAuthenticationService private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUserService _userService; private readonly JaszczurContext _dbContext; + private readonly EmailSettings _emailSettings; - public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, JaszczurContext dbContext) + public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, JaszczurContext dbContext, IOptions emailSettings) { _httpContextAccessor = httpContextAccessor; _userService = userService; _dbContext = dbContext; + _emailSettings = emailSettings.Value; } public async Task LogInAsync(string username, string password) @@ -95,9 +100,10 @@ public Task RegisterUser(string username, UserType type, string email, str public void SendActivationEmail(string userEmail, string activationCode) { - var fromAddress = new MailAddress("lizardtutoring@gmail.com", "Tutor Lizard"); + var fromAddress = new MailAddress(_emailSettings.FromAddress, "Tutor Lizard"); var toAddress = new MailAddress(userEmail); - const string fromPassword = "pvez johg nzwc enjg"; + var fromPassword = _emailSettings.FromPassword; + string subject = "Aktywacja konta"; string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: \nhttp://localhost:7092/Account/ActivateAccount?activationCode={activationCode}"; From 026eb475a29cfb7d9fd5261def04b307edf8c4f2 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 14 Jun 2024 15:43:41 +0200 Subject: [PATCH 11/23] Add ActivationResult model --- TutorLizard.Web/Controllers/AccountController.cs | 4 ++-- .../Services/IUserAuthenticationService.cs | 3 ++- TutorLizard.Web/Models/ActivationResult.cs | 8 ++++++++ .../Services/UserAuthenticationService.cs | 14 +++++++++++--- 4 files changed, 23 insertions(+), 6 deletions(-) create mode 100644 TutorLizard.Web/Models/ActivationResult.cs diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 17930a80..9f1a56c9 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -131,9 +131,9 @@ private string GenerateActivationCode() [HttpGet] public async Task ActivateAccount(string activationCode) { - bool isActivated = await _userAuthenticationService.ActivateUserAsync(activationCode); + var result = await _userAuthenticationService.ActivateUserAsync(activationCode); - if (isActivated) + if (result.IsActivated) { _uiMessagesService.ShowSuccessMessage("Atywacja udana."); return View("ActivateAccount"); diff --git a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs index a224ccae..6ab53fe4 100644 --- a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs +++ b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs @@ -1,4 +1,5 @@ using TutorLizard.BusinessLogic.Enums; +using TutorLizard.Web.Models; namespace TutorLizard.BusinessLogic.Interfaces.Services; @@ -9,7 +10,7 @@ public interface IUserAuthenticationService public Task LogInAsync(string username, string password); public Task LogOutAsync(); public Task RegisterUser(string username, UserType type, string email, string password, string activationCode); - Task ActivateUserAsync(string activationCode); + Task ActivateUserAsync(string activationCode); Task IsUserActive(string userName); void SendActivationEmail(string email, string activationCode); } diff --git a/TutorLizard.Web/Models/ActivationResult.cs b/TutorLizard.Web/Models/ActivationResult.cs new file mode 100644 index 00000000..8569ff2f --- /dev/null +++ b/TutorLizard.Web/Models/ActivationResult.cs @@ -0,0 +1,8 @@ +namespace TutorLizard.Web.Models +{ + public class ActivationResult + { + public bool IsActivated { get; set; } + public string ActivationCode { get; set; } + } +} diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index a5a1bdf8..bdc1b652 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -126,7 +126,7 @@ public void SendActivationEmail(string userEmail, string activationCode) } } - public async Task ActivateUserAsync(string activationCode) + public async Task ActivateUserAsync(string activationCode) { var user = await _dbContext.Users .FirstOrDefaultAsync(u => u.ActivationCode == activationCode && u.IsActive == false); @@ -136,9 +136,17 @@ public async Task ActivateUserAsync(string activationCode) user.IsActive = true; user.ActivationCode = "DEACTIVATED"; await _dbContext.SaveChangesAsync(); - return true; + return new ActivationResult + { + IsActivated = true, + ActivationCode = activationCode + }; } - return false; + return new ActivationResult + { + IsActivated = false, + ActivationCode = activationCode + }; } From b1a35127af9605869b36a30bf726c2fc4daa1167 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 14 Jun 2024 16:23:00 +0200 Subject: [PATCH 12/23] Move link to secrets --- TutorLizard.Web/Models/EmailSettings.cs | 1 + TutorLizard.Web/Services/UserAuthenticationService.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/TutorLizard.Web/Models/EmailSettings.cs b/TutorLizard.Web/Models/EmailSettings.cs index 79c4d3fe..dc5bd751 100644 --- a/TutorLizard.Web/Models/EmailSettings.cs +++ b/TutorLizard.Web/Models/EmailSettings.cs @@ -8,6 +8,7 @@ public class EmailSettings public int SmtpPort { get; set; } public string FromAddress { get; set; } public string FromPassword { get; set; } + public string ActivationLink { get; set; } } } diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index bdc1b652..b0960f00 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -105,7 +105,7 @@ public void SendActivationEmail(string userEmail, string activationCode) var fromPassword = _emailSettings.FromPassword; string subject = "Aktywacja konta"; - string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: \nhttp://localhost:7092/Account/ActivateAccount?activationCode={activationCode}"; + string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: {_emailSettings.ActivationLink}{activationCode}"; var smtp = new SmtpClient { From 5d8d35eae82f2ea88cef4718fd2b84e45b37babd Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 14 Jun 2024 16:56:59 +0200 Subject: [PATCH 13/23] Move activationCode generation to Service --- TutorLizard.Web/Controllers/AccountController.cs | 10 ++-------- .../Services/IUserAuthenticationService.cs | 2 +- .../Services/UserAuthenticationService.cs | 12 ++++++++++-- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 9f1a56c9..f7e308c9 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -103,9 +103,8 @@ public async Task Register(RegisterUserModel model) return View(model); } - string activationCode = GenerateActivationCode(); - bool registrationResult = await _userAuthenticationService.RegisterUser( - model.UserName, UserType.Regular, model.Email, model.Password, activationCode); + var (registrationResult, activationCode) = await _userAuthenticationService.RegisterUser( + model.UserName, UserType.Regular, model.Email, model.Password); if (registrationResult) { @@ -123,11 +122,6 @@ public async Task Register(RegisterUserModel model) return LocalRedirect("/Home/Index"); } - private string GenerateActivationCode() - { - return Guid.NewGuid().ToString(); - } - [HttpGet] public async Task ActivateAccount(string activationCode) { diff --git a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs index 6ab53fe4..e17a6c19 100644 --- a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs +++ b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs @@ -9,7 +9,7 @@ public interface IUserAuthenticationService int? GetLoggedInUserId(); public Task LogInAsync(string username, string password); public Task LogOutAsync(); - public Task RegisterUser(string username, UserType type, string email, string password, string activationCode); + Task<(bool, string)> RegisterUser(string username, UserType type, string email, string password); Task ActivateUserAsync(string activationCode); Task IsUserActive(string userName); void SendActivationEmail(string email, string activationCode); diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index b0960f00..33fa0cff 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -74,9 +74,17 @@ public async Task LogOutAsync() await _httpContextAccessor.HttpContext.SignOutAsync("CookieAuth"); } - public Task RegisterUser(string username, UserType type, string email, string password, string activationCode) + public async Task<(bool, string)> RegisterUser(string username, UserType type, string email, string password) { - return _userService.RegisterUser(username, type, email, password, activationCode); + string activationCode = GenerateActivationCode(); + bool result = await _userService.RegisterUser(username, type, email, password, activationCode); + + return (result, activationCode); + } + + private string GenerateActivationCode() + { + return Guid.NewGuid().ToString(); } public int? GetLoggedInUserId() From b02f9e255ab45cf54834a9976907eac57976be98 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 14 Jun 2024 16:57:22 +0200 Subject: [PATCH 14/23] Change Activation page view --- TutorLizard.Web/Views/Account/ActivateAccount.cshtml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/TutorLizard.Web/Views/Account/ActivateAccount.cshtml b/TutorLizard.Web/Views/Account/ActivateAccount.cshtml index b1cdea67..c11389f5 100644 --- a/TutorLizard.Web/Views/Account/ActivateAccount.cshtml +++ b/TutorLizard.Web/Views/Account/ActivateAccount.cshtml @@ -1,7 +1,6 @@ @{ - ViewData["Title"] = "Aktywacja maila"; + ViewData["Title"] = "Aktywacja konta"; }

@ViewData["Title"]

-

Aktywacja konta

-

Twoje konto zostało aktywowane.

\ No newline at end of file +

Twoje konto zostało aktywowane.

\ No newline at end of file From af3d37fd4fddc10ed1af729155d1bd2b131b482e Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 14 Jun 2024 18:56:28 +0200 Subject: [PATCH 15/23] Fix logging in so only active user can log in --- .../Interfaces/Services/IUserService.cs | 2 +- .../Models/DTOs/LogInResult.cs | 16 +++++ .../Services/UserService.cs | 35 ++++++++--- .../Controllers/AccountController.cs | 40 +++++++----- .../Services/IUserAuthenticationService.cs | 3 +- TutorLizard.Web/Models/LogInResult.cs | 18 ++++++ .../Services/UserAuthenticationService.cs | 61 ++++++++----------- 7 files changed, 113 insertions(+), 62 deletions(-) create mode 100644 TutorLizard.BusinessLogic/Models/DTOs/LogInResult.cs create mode 100644 TutorLizard.Web/Models/LogInResult.cs diff --git a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs index 75d14132..71517f0d 100644 --- a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs +++ b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs @@ -5,6 +5,6 @@ namespace TutorLizard.BusinessLogic.Interfaces.Services; public interface IUserService { - public Task LogIn(string username, string password); + public Task LogIn(string username, string password); public Task RegisterUser(string userName, UserType type, string email, string password, string activationCode); } diff --git a/TutorLizard.BusinessLogic/Models/DTOs/LogInResult.cs b/TutorLizard.BusinessLogic/Models/DTOs/LogInResult.cs new file mode 100644 index 00000000..d59490a7 --- /dev/null +++ b/TutorLizard.BusinessLogic/Models/DTOs/LogInResult.cs @@ -0,0 +1,16 @@ +namespace TutorLizard.BusinessLogic.Models.DTOs +{ + public class LogInResult + { + public LogInResultCode ResultCode { get; set; } + public UserDto? User { get; set; } + } + + public enum LogInResultCode + { + Success, + UserNotFound, + InactiveAccount, + InvalidPassword + } +} diff --git a/TutorLizard.BusinessLogic/Services/UserService.cs b/TutorLizard.BusinessLogic/Services/UserService.cs index 714c9d5a..99bb4024 100644 --- a/TutorLizard.BusinessLogic/Services/UserService.cs +++ b/TutorLizard.BusinessLogic/Services/UserService.cs @@ -18,25 +18,42 @@ public UserService(IDbRepository userRepository) { _userRepository = userRepository; } - public async Task LogIn(string username, string password) + public async Task LogIn(string username, string password) { var user = await _userRepository.GetAll() .FirstOrDefaultAsync(user => user.Name == username); - if (user == null || user.IsActive == false) + if (user == null) { - return null; + return new LogInResult + { + ResultCode = LogInResultCode.UserNotFound + }; } - var result = _passwordHasher - .VerifyHashedPassword(user, - user.PasswordHash, - password); + if (!user.IsActive.HasValue || !user.IsActive.Value) + { + return new LogInResult + { + ResultCode = LogInResultCode.InactiveAccount + }; + } + + var result = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password); if (result == PasswordVerificationResult.Success) - return user.ToDto(); + { + return new LogInResult + { + ResultCode = LogInResultCode.Success, + User = user.ToDto() + }; + } - return null; + return new LogInResult + { + ResultCode = LogInResultCode.InvalidPassword + }; } public async Task RegisterUser(string userName, UserType type, string email, string password, string activationCode) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index f7e308c9..3d0b1f44 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -4,9 +4,11 @@ using System.Net.Mail; using TutorLizard.BusinessLogic.Enums; using TutorLizard.BusinessLogic.Interfaces.Services; +using TutorLizard.BusinessLogic.Models.DTOs; using TutorLizard.Web.Interfaces.Services; using TutorLizard.Web.Models; + namespace TutorLizard.Web.Controllers; public class AccountController : Controller { @@ -46,26 +48,36 @@ public async Task Login(LoginModel model) try { - if (ModelState.IsValid && await _userAuthenticationService.LogInAsync(model.UserName, model.Password)) + if (ModelState.IsValid) { - if (await _userAuthenticationService.IsUserActive(model.UserName)) - { - _uiMessagesService.ShowSuccessMessage("Jesteś zalogowany/a."); - if (string.IsNullOrEmpty(returnUrl)) - { - return RedirectToAction("Index", "Home"); - } - return Redirect(returnUrl); - } - else + var logInResult = await _userAuthenticationService.LogInAsync(model.UserName, model.Password); + + switch (logInResult.ResultCode) { - _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Konto nie jest aktywne."); - return LocalRedirect("/Home/Index"); + case BusinessLogic.Models.DTOs.LogInResultCode.Success: + _uiMessagesService.ShowSuccessMessage("Jesteś zalogowany/a."); + if (string.IsNullOrEmpty(returnUrl)) + { + return RedirectToAction("Index", "Home"); + } + return Redirect(returnUrl); + + case BusinessLogic.Models.DTOs.LogInResultCode.UserNotFound: + case BusinessLogic.Models.DTOs.LogInResultCode.InvalidPassword: + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Nieprawidłowa nazwa użytkownika lub hasło."); + return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); + + case BusinessLogic.Models.DTOs.LogInResultCode.InactiveAccount: + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Konto nie jest aktywne."); + return LocalRedirect("/Home/Index"); + + default: + throw new ArgumentOutOfRangeException(); } } else { - _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Nieprawidłowa nazwa użytkownika lub hasło."); + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Proszę wypełnić poprawnie formularz."); return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); } } diff --git a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs index e17a6c19..a000b8ec 100644 --- a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs +++ b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs @@ -7,10 +7,9 @@ public interface IUserAuthenticationService { int? GetLoggedInUserId(); - public Task LogInAsync(string username, string password); + Task LogInAsync(string username, string password); public Task LogOutAsync(); Task<(bool, string)> RegisterUser(string username, UserType type, string email, string password); Task ActivateUserAsync(string activationCode); - Task IsUserActive(string userName); void SendActivationEmail(string email, string activationCode); } diff --git a/TutorLizard.Web/Models/LogInResult.cs b/TutorLizard.Web/Models/LogInResult.cs new file mode 100644 index 00000000..f1ce5bec --- /dev/null +++ b/TutorLizard.Web/Models/LogInResult.cs @@ -0,0 +1,18 @@ +using TutorLizard.BusinessLogic.Models.DTOs; + +namespace TutorLizard.Web.Models +{ + public class LogInResult + { + public LogInResultCode ResultCode { get; set; } + public UserDto? User { get; set; } + } + + public enum LogInResultCode + { + Success, + UserNotFound, + InactiveAccount, + InvalidPassword + } +} diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index 33fa0cff..d2dc2eea 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -11,6 +11,7 @@ using Newtonsoft.Json; using TutorLizard.Web.Models; using Microsoft.Extensions.Options; +using TutorLizard.BusinessLogic.Models.DTOs; namespace TutorLizard.BusinessLogic.Services; @@ -29,41 +30,39 @@ public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUser _emailSettings = emailSettings.Value; } - public async Task LogInAsync(string username, string password) + public async Task LogInAsync(string username, string password) { - var user = await _userService.LogIn(username, password); + var logInResult = await _userService.LogIn(username, password); - if (user is null) + if (logInResult.ResultCode == Models.DTOs.LogInResultCode.Success && logInResult.User != null) { - return false; - } - - var claims = new List + var claims = new List { - new Claim(ClaimTypes.Email, user.Email), - new Claim(ClaimTypes.Name, user.Name), - new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), - new Claim(ClaimTypes.Role, user.UserType.ToString()) + new Claim(ClaimTypes.Email, logInResult.User.Email), + new Claim(ClaimTypes.Name, logInResult.User.Name), + new Claim(ClaimTypes.NameIdentifier, logInResult.User.Id.ToString()), + new Claim(ClaimTypes.Role, logInResult.User.UserType.ToString()) }; - var claimsIdentity = new ClaimsIdentity( - claims, CookieAuthenticationDefaults.AuthenticationScheme); - - var authProperties = new AuthenticationProperties - { - AllowRefresh = true, - ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10), - IsPersistent = true, - }; + var claimsIdentity = new ClaimsIdentity( + claims, CookieAuthenticationDefaults.AuthenticationScheme); - if (_httpContextAccessor.HttpContext is null) - return false; + var authProperties = new AuthenticationProperties + { + AllowRefresh = true, + ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10), + IsPersistent = true, + }; - await _httpContextAccessor.HttpContext.SignInAsync("CookieAuth", - new ClaimsPrincipal(claimsIdentity), - authProperties); + if (_httpContextAccessor.HttpContext != null) + { + await _httpContextAccessor.HttpContext.SignInAsync("CookieAuth", + new ClaimsPrincipal(claimsIdentity), + authProperties); + } + } - return true; + return logInResult; } public async Task LogOutAsync() @@ -158,15 +157,5 @@ public async Task ActivateUserAsync(string activationCode) } - public async Task IsUserActive(string userName) - { - var user = await _dbContext.Users.FirstOrDefaultAsync(u => u.Name == userName); - - if (user != null) - { - return (bool)user.IsActive; - } - return false; - } } From 76dab34b0c90821a6227add12f73536c6b80bde4 Mon Sep 17 00:00:00 2001 From: skrawus Date: Fri, 14 Jun 2024 19:14:40 +0200 Subject: [PATCH 16/23] Change repository --- .../Services/UserAuthenticationService.cs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index d2dc2eea..c794727c 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -1,17 +1,16 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; -using System.Net.Mail; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; using System.Net; +using System.Net.Mail; using System.Security.Claims; using TutorLizard.BusinessLogic.Data; using TutorLizard.BusinessLogic.Enums; -using TutorLizard.BusinessLogic.Interfaces.Services; using TutorLizard.BusinessLogic.Interfaces.Data.Repositories; -using Microsoft.EntityFrameworkCore; -using Newtonsoft.Json; +using TutorLizard.BusinessLogic.Interfaces.Services; +using TutorLizard.BusinessLogic.Models; using TutorLizard.Web.Models; -using Microsoft.Extensions.Options; -using TutorLizard.BusinessLogic.Models.DTOs; namespace TutorLizard.BusinessLogic.Services; @@ -21,13 +20,15 @@ public class UserAuthenticationService : IUserAuthenticationService private readonly IUserService _userService; private readonly JaszczurContext _dbContext; private readonly EmailSettings _emailSettings; + private readonly IDbRepository _userRepository; - public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, JaszczurContext dbContext, IOptions emailSettings) + public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, JaszczurContext dbContext, IOptions emailSettings, IDbRepository userRepository) { _httpContextAccessor = httpContextAccessor; _userService = userService; _dbContext = dbContext; _emailSettings = emailSettings.Value; + _userRepository = userRepository; } public async Task LogInAsync(string username, string password) @@ -135,7 +136,8 @@ public void SendActivationEmail(string userEmail, string activationCode) public async Task ActivateUserAsync(string activationCode) { - var user = await _dbContext.Users + + var user = await _userRepository.GetAll() .FirstOrDefaultAsync(u => u.ActivationCode == activationCode && u.IsActive == false); if (user != null) From c88c3a4b7fbadfc7280d432f7513192f3d1d0d93 Mon Sep 17 00:00:00 2001 From: skrawus Date: Sat, 15 Jun 2024 10:26:20 +0200 Subject: [PATCH 17/23] Make LogIn method in IUserService not-nullable --- TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs index 71517f0d..b902a7dc 100644 --- a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs +++ b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs @@ -5,6 +5,6 @@ namespace TutorLizard.BusinessLogic.Interfaces.Services; public interface IUserService { - public Task LogIn(string username, string password); + public Task LogIn(string username, string password); public Task RegisterUser(string userName, UserType type, string email, string password, string activationCode); } From b919b95684f1093c318def7da4f565f6c7a52666 Mon Sep 17 00:00:00 2001 From: skrawus Date: Sat, 15 Jun 2024 10:29:08 +0200 Subject: [PATCH 18/23] Change Exception in AccountController --- TutorLizard.Web/Controllers/AccountController.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index 3d0b1f44..beda58b9 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using System.ComponentModel; using System.Net; using System.Net.Mail; using TutorLizard.BusinessLogic.Enums; @@ -72,7 +73,9 @@ public async Task Login(LoginModel model) return LocalRedirect("/Home/Index"); default: - throw new ArgumentOutOfRangeException(); + throw new InvalidEnumArgumentException(argumentName: nameof(BusinessLogic.Models.DTOs.LogInResult.ResultCode), + invalidValue: (int)logInResult.ResultCode, + enumClass: typeof(BusinessLogic.Models.DTOs.LogInResult)); } } else From 5642e2f2c11e41fe4ff3c69705aed4e494c041fb Mon Sep 17 00:00:00 2001 From: skrawus Date: Sat, 15 Jun 2024 10:32:34 +0200 Subject: [PATCH 19/23] Delete duplicated class --- TutorLizard.Web/Models/LogInResult.cs | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 TutorLizard.Web/Models/LogInResult.cs diff --git a/TutorLizard.Web/Models/LogInResult.cs b/TutorLizard.Web/Models/LogInResult.cs deleted file mode 100644 index f1ce5bec..00000000 --- a/TutorLizard.Web/Models/LogInResult.cs +++ /dev/null @@ -1,18 +0,0 @@ -using TutorLizard.BusinessLogic.Models.DTOs; - -namespace TutorLizard.Web.Models -{ - public class LogInResult - { - public LogInResultCode ResultCode { get; set; } - public UserDto? User { get; set; } - } - - public enum LogInResultCode - { - Success, - UserNotFound, - InactiveAccount, - InvalidPassword - } -} From f53ed17c84efaff3e374b829a950f99ec15cb8a2 Mon Sep 17 00:00:00 2001 From: skrawus Date: Sat, 15 Jun 2024 10:35:51 +0200 Subject: [PATCH 20/23] Make IsActive not nullable & update LogIn method --- TutorLizard.BusinessLogic/Models/User.cs | 2 +- TutorLizard.BusinessLogic/Services/UserService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/TutorLizard.BusinessLogic/Models/User.cs b/TutorLizard.BusinessLogic/Models/User.cs index 5633c046..1331a883 100644 --- a/TutorLizard.BusinessLogic/Models/User.cs +++ b/TutorLizard.BusinessLogic/Models/User.cs @@ -6,7 +6,7 @@ namespace TutorLizard.BusinessLogic.Models; public class User { public int Id { get; set; } - public bool? IsActive { get; set; } + public bool IsActive { get; set; } [Required] [MinLength(5)] diff --git a/TutorLizard.BusinessLogic/Services/UserService.cs b/TutorLizard.BusinessLogic/Services/UserService.cs index 99bb4024..435e71bc 100644 --- a/TutorLizard.BusinessLogic/Services/UserService.cs +++ b/TutorLizard.BusinessLogic/Services/UserService.cs @@ -31,7 +31,7 @@ public async Task LogIn(string username, string password) }; } - if (!user.IsActive.HasValue || !user.IsActive.Value) + if (!user.IsActive) { return new LogInResult { From dfe0c00435d43bedad7383e8024451a34b1f1151 Mon Sep 17 00:00:00 2001 From: skrawus Date: Sun, 16 Jun 2024 19:03:18 +0200 Subject: [PATCH 21/23] Change the way of saving changes in ActivateUserAsync method --- .../Services/UserAuthenticationService.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index c794727c..526d563b 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -18,15 +18,13 @@ public class UserAuthenticationService : IUserAuthenticationService { private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUserService _userService; - private readonly JaszczurContext _dbContext; private readonly EmailSettings _emailSettings; private readonly IDbRepository _userRepository; - public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, JaszczurContext dbContext, IOptions emailSettings, IDbRepository userRepository) + public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, IOptions emailSettings, IDbRepository userRepository) { _httpContextAccessor = httpContextAccessor; _userService = userService; - _dbContext = dbContext; _emailSettings = emailSettings.Value; _userRepository = userRepository; } @@ -144,7 +142,13 @@ public async Task ActivateUserAsync(string activationCode) { user.IsActive = true; user.ActivationCode = "DEACTIVATED"; - await _dbContext.SaveChangesAsync(); + + await _userRepository.Update(user.Id, u => + { + u.IsActive = user.IsActive; + u.ActivationCode = user.ActivationCode; + }); + return new ActivationResult { IsActivated = true, From df071c998f64ef67286bc5e063125873b589bfeb Mon Sep 17 00:00:00 2001 From: skrawus Date: Sun, 23 Jun 2024 13:04:59 +0200 Subject: [PATCH 22/23] Move ActivateUserAsync method to UserService From UserAuthenticationService --- .../Interfaces/Services/IUserService.cs | 2 ++ .../Models/ActivationResult.cs | 14 ++++++++ .../Services/UserService.cs | 30 ++++++++++++++++ .../Services/IUserAuthenticationService.cs | 2 -- TutorLizard.Web/Models/ActivationResult.cs | 8 ----- .../Services/UserAuthenticationService.cs | 36 ++----------------- 6 files changed, 49 insertions(+), 43 deletions(-) create mode 100644 TutorLizard.BusinessLogic/Models/ActivationResult.cs delete mode 100644 TutorLizard.Web/Models/ActivationResult.cs diff --git a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs index b902a7dc..81e07622 100644 --- a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs +++ b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs @@ -1,4 +1,5 @@ using TutorLizard.BusinessLogic.Enums; +using TutorLizard.BusinessLogic.Models; using TutorLizard.BusinessLogic.Models.DTOs; namespace TutorLizard.BusinessLogic.Interfaces.Services; @@ -7,4 +8,5 @@ public interface IUserService { public Task LogIn(string username, string password); public Task RegisterUser(string userName, UserType type, string email, string password, string activationCode); + Task ActivateUserAsync(string activationCode); } diff --git a/TutorLizard.BusinessLogic/Models/ActivationResult.cs b/TutorLizard.BusinessLogic/Models/ActivationResult.cs new file mode 100644 index 00000000..62a197bb --- /dev/null +++ b/TutorLizard.BusinessLogic/Models/ActivationResult.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TutorLizard.BusinessLogic.Models +{ + public class ActivationResult + { + public bool IsActivated { get; set; } + public string ActivationCode { get; set; } + } +} diff --git a/TutorLizard.BusinessLogic/Services/UserService.cs b/TutorLizard.BusinessLogic/Services/UserService.cs index 435e71bc..90c0b4d0 100644 --- a/TutorLizard.BusinessLogic/Services/UserService.cs +++ b/TutorLizard.BusinessLogic/Services/UserService.cs @@ -77,4 +77,34 @@ public async Task RegisterUser(string userName, UserType type, string emai return true; } + + public async Task ActivateUserAsync(string activationCode) + { + + var user = await _userRepository.GetAll() + .FirstOrDefaultAsync(u => u.ActivationCode == activationCode && u.IsActive == false); + + if (user != null) + { + user.IsActive = true; + user.ActivationCode = "ACTIVATED"; + + await _userRepository.Update(user.Id, u => + { + u.IsActive = user.IsActive; + u.ActivationCode = user.ActivationCode; + }); + + return new ActivationResult + { + IsActivated = true, + ActivationCode = activationCode + }; + } + return new ActivationResult + { + IsActivated = false, + ActivationCode = activationCode + }; + } } \ No newline at end of file diff --git a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs index a000b8ec..08a52b89 100644 --- a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs +++ b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs @@ -1,5 +1,4 @@ using TutorLizard.BusinessLogic.Enums; -using TutorLizard.Web.Models; namespace TutorLizard.BusinessLogic.Interfaces.Services; @@ -10,6 +9,5 @@ public interface IUserAuthenticationService Task LogInAsync(string username, string password); public Task LogOutAsync(); Task<(bool, string)> RegisterUser(string username, UserType type, string email, string password); - Task ActivateUserAsync(string activationCode); void SendActivationEmail(string email, string activationCode); } diff --git a/TutorLizard.Web/Models/ActivationResult.cs b/TutorLizard.Web/Models/ActivationResult.cs deleted file mode 100644 index 8569ff2f..00000000 --- a/TutorLizard.Web/Models/ActivationResult.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace TutorLizard.Web.Models -{ - public class ActivationResult - { - public bool IsActivated { get; set; } - public string ActivationCode { get; set; } - } -} diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index 526d563b..08af83c4 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -115,9 +115,11 @@ public void SendActivationEmail(string userEmail, string activationCode) var smtp = new SmtpClient { + // TODO przenieś do appsettingsów / secretsów Host = "smtp.gmail.com", Port = 587, EnableSsl = true, + // koniec - przenieś do appsettingsów / secretsów DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) @@ -131,37 +133,5 @@ public void SendActivationEmail(string userEmail, string activationCode) smtp.Send(message); } } - - public async Task ActivateUserAsync(string activationCode) - { - - var user = await _userRepository.GetAll() - .FirstOrDefaultAsync(u => u.ActivationCode == activationCode && u.IsActive == false); - - if (user != null) - { - user.IsActive = true; - user.ActivationCode = "DEACTIVATED"; - - await _userRepository.Update(user.Id, u => - { - u.IsActive = user.IsActive; - u.ActivationCode = user.ActivationCode; - }); - - return new ActivationResult - { - IsActivated = true, - ActivationCode = activationCode - }; - } - return new ActivationResult - { - IsActivated = false, - ActivationCode = activationCode - }; - } - - - + } From c51b51054ff773a29c2698f82bc4db863fad4821 Mon Sep 17 00:00:00 2001 From: skrawus Date: Sun, 23 Jun 2024 15:51:22 +0200 Subject: [PATCH 23/23] Move data to secrets --- TutorLizard.Web/Controllers/AccountController.cs | 7 +++++-- TutorLizard.Web/Models/EmailSettings.cs | 7 +++---- TutorLizard.Web/Services/UserAuthenticationService.cs | 8 +++----- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index beda58b9..97b60604 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -15,12 +15,15 @@ public class AccountController : Controller { private readonly IUserAuthenticationService _userAuthenticationService; private readonly IUiMessagesService _uiMessagesService; + private readonly IUserService _userService; public AccountController(IUserAuthenticationService userAuthenticationService, - IUiMessagesService uiMessagesService) + IUiMessagesService uiMessagesService, + IUserService userService) { _userAuthenticationService = userAuthenticationService; _uiMessagesService = uiMessagesService; + _userService = userService; } public IActionResult Index() @@ -140,7 +143,7 @@ public async Task Register(RegisterUserModel model) [HttpGet] public async Task ActivateAccount(string activationCode) { - var result = await _userAuthenticationService.ActivateUserAsync(activationCode); + var result = await _userService.ActivateUserAsync(activationCode); if (result.IsActivated) { diff --git a/TutorLizard.Web/Models/EmailSettings.cs b/TutorLizard.Web/Models/EmailSettings.cs index dc5bd751..481bb807 100644 --- a/TutorLizard.Web/Models/EmailSettings.cs +++ b/TutorLizard.Web/Models/EmailSettings.cs @@ -2,13 +2,12 @@ { public class EmailSettings { - public string MailAddress { get; set; } - public string Password { get; set; } - public string SmtpHost { get; set; } - public int SmtpPort { get; set; } public string FromAddress { get; set; } public string FromPassword { get; set; } public string ActivationLink { get; set; } + public string Host { get; set; } + public int Port { get; set; } + public bool EnableSsl { get; set; } } } diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index 08af83c4..8371bcfc 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -115,11 +115,9 @@ public void SendActivationEmail(string userEmail, string activationCode) var smtp = new SmtpClient { - // TODO przenieś do appsettingsów / secretsów - Host = "smtp.gmail.com", - Port = 587, - EnableSsl = true, - // koniec - przenieś do appsettingsów / secretsów + Host = _emailSettings.Host, + Port = _emailSettings.Port, + EnableSsl = _emailSettings.EnableSsl, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword)