diff --git a/Tests/TutorLizard.BusinessLogic.Tests/Services/Student/StudentServiceScheduleItemRequestTests.cs b/Tests/TutorLizard.BusinessLogic.Tests/Services/Student/StudentServiceScheduleItemRequestTests.cs new file mode 100644 index 00000000..a1cdacea --- /dev/null +++ b/Tests/TutorLizard.BusinessLogic.Tests/Services/Student/StudentServiceScheduleItemRequestTests.cs @@ -0,0 +1,77 @@ +using Moq; +using TutorLizard.BusinessLogic.Models; +using TutorLizard.Shared.Models.DTOs.Requests; +using TutorLizard.BusinessLogic.Services; + +namespace TutorLizard.BusinessLogic.Tests.Services.Student +{ + public class StudentServiceScheduleItemRequestTests : StudentServiceTestBase + { + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task CreateScheduleItemRequest_ShouldSetIsRemoteCorrectly(bool isRemote) + { + // Arrange + var ad = new Ad + { + Description = "Test Description", + Location = "Test Location", + Subject = "Test Subject", + Title = "Test Title", + TutorId = 2 + }; + var scheduleItem = new ScheduleItem { Id = 1, Ad = ad }; + + SetupMockGetScheduleItemById(scheduleItem); + SetupMockGetAllScheduleItems(new List { scheduleItem }); + + var request = new CreateScheduleItemRequestRequest + { + StudentId = 3, + ScheduleItemId = 1, + IsRemote = isRemote + }; + + MockScheduleItemRequestRepository + .Setup(x => x.Create(It.Is(req => req.IsRemote == isRemote))) + .Returns((ScheduleItemRequest req) => Task.FromResult(req)) + .Verifiable(Times.Once); + + // Act + await StudentService.CreateScheduleItemRequest(request); + + // Assert + MockScheduleItemRequestRepository.VerifyAll(); + } + + [Fact] + public async Task CreateScheduleItemRequest_WhenRequestSent_ShouldReturnSuccess() + { + // Arrange + var scheduleItem = new ScheduleItem { Id = 1 }; + var studentId = 1; + var isRemote = true; + + SetupMockGetScheduleItemById(scheduleItem); + + var request = new CreateScheduleItemRequestRequest + { + StudentId = studentId, + ScheduleItemId = scheduleItem.Id, + IsRemote = isRemote + }; + + // Act + var response = await StudentService.CreateScheduleItemRequest(request); + + // Assert + Assert.True(response.Success); + } + + + + + + } +} diff --git a/Tests/TutorLizard.BusinessLogic.Tests/Services/Student/StudentServiceTestBase.cs b/Tests/TutorLizard.BusinessLogic.Tests/Services/Student/StudentServiceTestBase.cs new file mode 100644 index 00000000..98408524 --- /dev/null +++ b/Tests/TutorLizard.BusinessLogic.Tests/Services/Student/StudentServiceTestBase.cs @@ -0,0 +1,55 @@ +using AutoFixture; +using Moq; +using TutorLizard.BusinessLogic.Interfaces.Data.Repositories; +using TutorLizard.BusinessLogic.Models; +using TutorLizard.BusinessLogic.Services; + +namespace TutorLizard.BusinessLogic.Tests.Services.Student +{ + public class StudentServiceTestBase : TestsWithInMemoryDbBase + { + protected StudentService StudentService; + protected Fixture Fixture = new(); + protected Mock> MockAdRepository = new(); + protected Mock> MockAdRequestRepository = new(); + protected Mock> MockScheduleItemRepository = new(); + protected Mock> MockScheduleItemRequestRepository = new(); + + + protected StudentServiceTestBase() : base() + { + StudentService = new StudentService(MockAdRepository.Object, + MockAdRequestRepository.Object, + MockScheduleItemRepository.Object, + MockScheduleItemRequestRepository.Object); + } + + protected void SetupMockGetScheduleItemById(ScheduleItem? scheduleItem) + { + MockScheduleItemRepository + .Setup(x => x.GetById(It.IsAny())) + .Returns(Task.FromResult(scheduleItem)); + } + + protected void SetupMockGetAllScheduleItems(List scheduleItems) + { + var scheduleItemsInDb = AddEntitiesToInMemoryDb(scheduleItems); + MockScheduleItemRepository + .Setup(x => x.GetAll()) + .Returns(scheduleItemsInDb); + } + + protected IQueryable AddEntitiesToInMemoryDb(List entities) + where TEntity : class + { + DbContext + .Set() + .AddRange(entities); + DbContext.SaveChanges(); + + return DbContext + .Set() + .AsQueryable(); + } + } +} 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/Data/Repositories/Json/UserJsonRepository.cs b/TutorLizard.BusinessLogic/Data/Repositories/Json/UserJsonRepository.cs index 983e9b2e..128d95ee 100644 --- a/TutorLizard.BusinessLogic/Data/Repositories/Json/UserJsonRepository.cs +++ b/TutorLizard.BusinessLogic/Data/Repositories/Json/UserJsonRepository.cs @@ -15,9 +15,9 @@ public UserJsonRepository(IOptions options) : base(options.Va } - public User CreateUser(string name, UserType type, string email, string passwordHash) + public User CreateUser(string name, UserType type, string email, string passwordHash, string googleid) { - User newUser = new(GetNewId(), name, type, email, passwordHash); + User newUser = new(GetNewId(), name, type, email, passwordHash, googleid); Data.Add(newUser); SaveToJson(); diff --git a/TutorLizard.BusinessLogic/Extensions/DtoExtensions.cs b/TutorLizard.BusinessLogic/Extensions/DtoExtensions.cs index e968dece..513ca581 100644 --- a/TutorLizard.BusinessLogic/Extensions/DtoExtensions.cs +++ b/TutorLizard.BusinessLogic/Extensions/DtoExtensions.cs @@ -14,5 +14,6 @@ public static UserDto ToDto(this User user) user.Name, user.UserType, user.Email, - user.DateCreated); + user.DateCreated, + user.GoogleId); } diff --git a/TutorLizard.BusinessLogic/Interfaces/Data/Repositories/IUserRepository.cs b/TutorLizard.BusinessLogic/Interfaces/Data/Repositories/IUserRepository.cs index 1e1c07f1..f5062402 100644 --- a/TutorLizard.BusinessLogic/Interfaces/Data/Repositories/IUserRepository.cs +++ b/TutorLizard.BusinessLogic/Interfaces/Data/Repositories/IUserRepository.cs @@ -4,7 +4,7 @@ namespace TutorLizard.BusinessLogic.Interfaces.Data.Repositories; public interface IUserRepository { - User CreateUser(string name, UserType type, string email, string passwordHash); + User CreateUser(string name, UserType type, string email, string passwordHash, string googleId); void DeleteUserById(int id); List GetAllUsers(); User? GetUserById(int id); diff --git a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs index 5b58aad6..970fde6f 100644 --- a/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs +++ b/TutorLizard.BusinessLogic/Interfaces/Services/IUserService.cs @@ -5,6 +5,10 @@ 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 LogIn(string username, string password); + public Task RegisterUser(string userName, UserType type, string email, string password, string activationCode); + Task ActivateUserAsync(string activationCode); + public Task RegisterUserWithGoogle(string username, string email, string googleId); + public Task IsTheGoogleUserRegistered(string googleId); + public Task LogInWithGoogle(string username, string googleId); } diff --git a/TutorLizard.BusinessLogic/Models/User.cs b/TutorLizard.BusinessLogic/Models/User.cs index f06d9590..f8848b2a 100644 --- a/TutorLizard.BusinessLogic/Models/User.cs +++ b/TutorLizard.BusinessLogic/Models/User.cs @@ -3,9 +3,10 @@ namespace TutorLizard.BusinessLogic.Models; -public class User +public class User { public int Id { get; set; } + public bool IsActive { get; set; } [Required] [MinLength(5)] @@ -19,21 +20,23 @@ public class User [MaxLength(100)] public string Email { get; set; } - [Required] [DataType(DataType.Password)] [MinLength(8)] [MaxLength(100)] - public string PasswordHash { get; set; } + public string? PasswordHash { get; set; } public DateTime DateCreated { get; set; } = DateTime.Now; - public User(int id, string name, UserType userType, string email, string passwordHash) + public string? GoogleId { get; set; } + + public User(int id, string name, UserType userType, string email, string passwordHash, string? googleId) { Id = id; Name = name; UserType = userType; Email = email; PasswordHash = passwordHash; + GoogleId = googleId; } public User() { @@ -43,4 +46,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/StudentService.cs b/TutorLizard.BusinessLogic/Services/StudentService.cs index 27938f87..9dc04452 100644 --- a/TutorLizard.BusinessLogic/Services/StudentService.cs +++ b/TutorLizard.BusinessLogic/Services/StudentService.cs @@ -24,6 +24,7 @@ public class StudentService : IStudentService _scheduleItemRequestRepository = scheduleItemRequestRepository; } + #region Schedule public async Task CreateScheduleItemRequest(CreateScheduleItemRequestRequest request) { int studentId = request.StudentId; @@ -47,18 +48,57 @@ public async Task CreateScheduleItemRequest(C ScheduleItemId = scheduleItemId, DateCreated = DateTime.UtcNow, StudentId = studentId, - IsAccepted = false + IsAccepted = false, + IsRemote = request.IsRemote }; await _scheduleItemRequestRepository.Create(scheduleItemRequest); - return new CreateScheduleItemRequestResponse - { + + return new CreateScheduleItemRequestResponse + { Success = true, - CreatedScheduleItemRequestId = scheduleItemRequest.Id, + CreatedScheduleItemRequestId = scheduleItemRequest.Id }; } + public async Task GetAvailableScheduleForAd(GetAvailableScheduleForAdRequest request) + { + List items = await _scheduleItemRepository.GetAll() + .Where(si => si.Ad.AdRequests.Any(ar => ar.StudentId == request.StudentId && ar.IsAccepted)) + .Select(si => new ScheduleItemDto() + { + AdId = si.AdId, + DateTime = si.DateTime, + Id = si.Id, + Status = si.ScheduleItemRequests.Any(sir => sir.StudentId == request.StudentId && sir.IsAccepted) ? ScheduleItemDto.ScheduleItemRequestStatus.Accepted + : si.ScheduleItemRequests.Any(sir => sir.StudentId == request.StudentId) ? ScheduleItemDto.ScheduleItemRequestStatus.Pending + : ScheduleItemDto.ScheduleItemRequestStatus.RequestNotSent + }) + .ToListAsync(); + + bool isAccepted = await _adRequestRepository.GetAll() + .Where(ar => ar.AdId == request.AdId) + .AnyAsync(ar => ar.StudentId == request.StudentId && ar.IsAccepted); + + bool isRemote = await _adRepository.GetAll() + .Where(ad => ad.Id == request.AdId) + .Select(ad => ad.IsRemote) + .FirstOrDefaultAsync(); + + GetAvailableScheduleForAdResponse response = new() + { + AdId = request.AdId, + IsAccepted = isAccepted, + IsRemote = isRemote, + Items = items + }; + + return response; + } + + #endregion + #region Ads public async Task GetStudentsAcceptedAds(GetStudentsAcceptedAdsRequest request) { var studentId = request.StudentId; @@ -141,7 +181,7 @@ public async Task GetAdRequestStatus(GetAdRequestSta .FirstOrDefaultAsync(); if (adRequestDetails is null) - return new GetAdRequestStatusResponse() { IsSuccessful = false }; + return new GetAdRequestStatusResponse() { IsSuccessful = false }; GetAdRequestStatusResponse response = new GetAdRequestStatusResponse() { @@ -231,33 +271,5 @@ public async Task CreateAdRequest(CreateAdRequestReques Success = true }; } - - public async Task GetAvailableScheduleForAd(GetAvailableScheduleForAdRequest request) - { - List items = await _scheduleItemRepository.GetAll() - .Where(si => si.Ad.AdRequests.Any(ar => ar.StudentId == request.StudentId && ar.IsAccepted) && si.AdId == request.AdId) - .Select(si => new ScheduleItemDto() - { - AdId = si.AdId, - DateTime = si.DateTime, - Id = si.Id, - Status = si.ScheduleItemRequests.Any(sir => sir.StudentId == request.StudentId && sir.IsAccepted) ? ScheduleItemDto.ScheduleItemRequestStatus.Accepted - : si.ScheduleItemRequests.Any(sir => sir.StudentId == request.StudentId) ? ScheduleItemDto.ScheduleItemRequestStatus.Pending - : ScheduleItemDto.ScheduleItemRequestStatus.RequestNotSent - }) - .ToListAsync(); - - bool isAccepted = await _adRequestRepository.GetAll() - .Where(ar => ar.AdId == request.AdId) - .AnyAsync(ar => ar.StudentId == request.StudentId && ar.IsAccepted); - - GetAvailableScheduleForAdResponse response = new() - { - AdId = request.AdId, - IsAccepted = isAccepted, - Items = items - }; - - return response; - } } +#endregion \ No newline at end of file diff --git a/TutorLizard.BusinessLogic/Services/UserService.cs b/TutorLizard.BusinessLogic/Services/UserService.cs index fb3a3c87..a8d3beb2 100644 --- a/TutorLizard.BusinessLogic/Services/UserService.cs +++ b/TutorLizard.BusinessLogic/Services/UserService.cs @@ -18,28 +18,63 @@ 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) { - return null; + return new LogInResult + { + ResultCode = LogInResultCode.UserNotFound + }; + } + + if (!user.IsActive) + { + return new LogInResult + { + ResultCode = LogInResultCode.InactiveAccount + }; } - var result = _passwordHasher - .VerifyHashedPassword(user, - user.PasswordHash, - password); + var result = _passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password); if (result == PasswordVerificationResult.Success) + { + return new LogInResult + { + ResultCode = LogInResultCode.Success, + User = user.ToDto() + }; + } + + return new LogInResult + { + ResultCode = LogInResultCode.InvalidPassword + }; + } + + public async Task LogInWithGoogle(string username, string googleId) + { + var user = await _userRepository.GetAll() + .FirstOrDefaultAsync(user => user.GoogleId == googleId); + + if (user == null) + { + return null; + } + + if (user.GoogleId == googleId) return user.ToDto(); 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 +84,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); @@ -58,4 +95,60 @@ public async Task RegisterUser(string userName, UserType type, string emai return true; } + + public async Task RegisterUserWithGoogle(string username, string email, string googleId) + { + if (await _userRepository.GetAll().AnyAsync(user => user.Name == username)) + return false; + + User user = new() + { + Name = username, + UserType = UserType.Regular, + Email = email, + GoogleId = googleId + }; + + await _userRepository.Create(user); + + return true; + } + + public async Task IsTheGoogleUserRegistered(string googleId) + { + if (await _userRepository.GetAll().AnyAsync(user => user.GoogleId == googleId)) + return true; + + return false; + } + + 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 ActivationResultDto + { + IsActivated = true, + ActivationCode = activationCode + }; + } + return new ActivationResultDto + { + IsActivated = false, + ActivationCode = activationCode + }; + } } \ No newline at end of file diff --git a/TutorLizard.BusinessLogic/TutorLizard.BusinessLogic.csproj b/TutorLizard.BusinessLogic/TutorLizard.BusinessLogic.csproj index 41ea8726..9864666e 100644 --- a/TutorLizard.BusinessLogic/TutorLizard.BusinessLogic.csproj +++ b/TutorLizard.BusinessLogic/TutorLizard.BusinessLogic.csproj @@ -7,7 +7,7 @@ - + diff --git a/TutorLizard.Shared/Enums/LogInResultCode.cs b/TutorLizard.Shared/Enums/LogInResultCode.cs new file mode 100644 index 00000000..9cfa7036 --- /dev/null +++ b/TutorLizard.Shared/Enums/LogInResultCode.cs @@ -0,0 +1,10 @@ +namespace TutorLizard.Shared.Enums +{ + public enum LogInResultCode + { + Success, + UserNotFound, + InactiveAccount, + InvalidPassword + } +} diff --git a/TutorLizard.Shared/Models/DTOs/ActivationResultDto.cs b/TutorLizard.Shared/Models/DTOs/ActivationResultDto.cs new file mode 100644 index 00000000..db3d3e89 --- /dev/null +++ b/TutorLizard.Shared/Models/DTOs/ActivationResultDto.cs @@ -0,0 +1,8 @@ +namespace TutorLizard.Shared.Models.DTOs +{ + public class ActivationResultDto + { + public bool IsActivated { get; set; } + public string ActivationCode { get; set; } + } +} diff --git a/TutorLizard.Shared/Models/DTOs/LogInResult.cs b/TutorLizard.Shared/Models/DTOs/LogInResult.cs new file mode 100644 index 00000000..4e6bf696 --- /dev/null +++ b/TutorLizard.Shared/Models/DTOs/LogInResult.cs @@ -0,0 +1,10 @@ +using TutorLizard.Shared.Enums; + +namespace TutorLizard.Shared.Models.DTOs +{ + public class LogInResult + { + public LogInResultCode ResultCode { get; set; } + public UserDto? User { get; set; } + } +} diff --git a/TutorLizard.Shared/Models/DTOs/Requests/CreateScheduleItemRequestRequest.cs b/TutorLizard.Shared/Models/DTOs/Requests/CreateScheduleItemRequestRequest.cs index 45768f97..ed7f7a05 100644 --- a/TutorLizard.Shared/Models/DTOs/Requests/CreateScheduleItemRequestRequest.cs +++ b/TutorLizard.Shared/Models/DTOs/Requests/CreateScheduleItemRequestRequest.cs @@ -10,5 +10,6 @@ public class CreateScheduleItemRequestRequest { public int StudentId { get; set; } public int ScheduleItemId { get; set; } + public bool IsRemote { get; set; } } } diff --git a/TutorLizard.Shared/Models/DTOs/Responses/CreateScheduleItemRequestResponse.cs b/TutorLizard.Shared/Models/DTOs/Responses/CreateScheduleItemRequestResponse.cs index be5dea53..1c740620 100644 --- a/TutorLizard.Shared/Models/DTOs/Responses/CreateScheduleItemRequestResponse.cs +++ b/TutorLizard.Shared/Models/DTOs/Responses/CreateScheduleItemRequestResponse.cs @@ -10,5 +10,6 @@ public class CreateScheduleItemRequestResponse { public bool Success { get; set; } public int CreatedScheduleItemRequestId { get; set; } + public bool IsRemote { get; set; } } } diff --git a/TutorLizard.Shared/Models/DTOs/Responses/GetAvailableScheduleForAdResponse.cs b/TutorLizard.Shared/Models/DTOs/Responses/GetAvailableScheduleForAdResponse.cs index 233fad54..53dec57d 100644 --- a/TutorLizard.Shared/Models/DTOs/Responses/GetAvailableScheduleForAdResponse.cs +++ b/TutorLizard.Shared/Models/DTOs/Responses/GetAvailableScheduleForAdResponse.cs @@ -10,6 +10,7 @@ public class GetAvailableScheduleForAdResponse { public List Items { get; set; } = new(); public bool IsAccepted { get; set; } = true; + public bool IsRemote { get; set; } public int AdId { get; set; } } } diff --git a/TutorLizard.Shared/Models/DTOs/UserDto.cs b/TutorLizard.Shared/Models/DTOs/UserDto.cs index 3f8237ce..0ed1a072 100644 --- a/TutorLizard.Shared/Models/DTOs/UserDto.cs +++ b/TutorLizard.Shared/Models/DTOs/UserDto.cs @@ -5,17 +5,20 @@ namespace TutorLizard.Shared.Models.DTOs; public class UserDto { public int Id { get; set; } + public bool? IsActive { get; set; } public string Name { get; set; } public UserType UserType { get; set; } public string Email { get; set; } public DateTime DateCreated { get; set; } = DateTime.Now; + public string? GoogleId { get; set; } - public UserDto(int id, string name, UserType userType, string email, DateTime dateCreated) + public UserDto(int id, string name, UserType userType, string email, DateTime dateCreated, string? googleId) { Id = id; Name = name; UserType = userType; Email = email; DateCreated = dateCreated; + GoogleId = googleId; } } diff --git a/TutorLizard.Web/Controllers/AccountController.cs b/TutorLizard.Web/Controllers/AccountController.cs index fd3da6e7..4fe21c65 100644 --- a/TutorLizard.Web/Controllers/AccountController.cs +++ b/TutorLizard.Web/Controllers/AccountController.cs @@ -1,21 +1,35 @@ -using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Authentication.Google; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using System.Security.Authentication; +using System.Security.Claims; +using System.ComponentModel; +using System.Net; +using System.Net.Mail; using TutorLizard.BusinessLogic.Interfaces.Services; using TutorLizard.Shared.Enums; using TutorLizard.Web.Interfaces.Services; using TutorLizard.Web.Models; +using TutorLizard.Shared.Models.DTOs; + namespace TutorLizard.Web.Controllers; + 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() @@ -23,15 +37,76 @@ public IActionResult Index() return View(); } - public IActionResult Login([FromQuery] string? returnUrl) + public async Task Login([FromQuery] string? returnUrl) { if (returnUrl is not null) { TempData["returnUrl"] = returnUrl; } + return View(); } + public async Task GoogleLogin() + { + await HttpContext.ChallengeAsync(GoogleDefaults.AuthenticationScheme, + new AuthenticationProperties + { + RedirectUri = Url.Action("GoogleResponse"), + Items = + { + { "prompt", "select_account" } + } + }); + } + + public async Task GoogleResponse() + { + try + { + var result = await HttpContext.AuthenticateAsync(GoogleDefaults.AuthenticationScheme); + + if (result?.Succeeded != true) + { + return RedirectToAction("Login"); + } + + var claims = result.Principal.Identities.FirstOrDefault()?.Claims.ToList(); + + var claimNameIdentifier = claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value; + var claimName = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value; + var claimEmail = claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value; + + if(!(await _userAuthenticationService.IsGoogleUserRegistered(claimNameIdentifier))) + { + try + { + await _userAuthenticationService.RegisterUserWithGoogle(claimName, claimEmail, claimNameIdentifier); + } + catch (Exception ex) + { + _uiMessagesService.ShowFailureMessage("Rejestracja użytkownika za pomocą konta google się nie powiodła"); + return RedirectToAction("Login"); + } + } + + var loggedIn = await _userAuthenticationService.LogInWithGoogleAsync(claimName,claimNameIdentifier); + + if (!loggedIn) + { + _uiMessagesService.ShowFailureMessage("Logowanie nieudane."); + return RedirectToAction("Login"); + } + + return RedirectToAction("Index", "Home"); + } + catch (Exception ex) + { + _uiMessagesService.ShowFailureMessage("Logowanie nieudane."); + return RedirectToAction("Login"); + } + } + [HttpPost] [ValidateAntiForgeryToken] public async Task Login(LoginModel model) @@ -44,14 +119,39 @@ public async Task Login(LoginModel model) try { - if (ModelState.IsValid && await _userAuthenticationService.LogInAsync(model.UserName, model.Password)) + if (ModelState.IsValid) { - _uiMessagesService.ShowSuccessMessage("Jesteś zalogowany/a."); - if (string.IsNullOrEmpty(returnUrl)) + var logInResult = await _userAuthenticationService.LogInAsync(model.UserName, model.Password); + + switch (logInResult.ResultCode) { - return RedirectToAction("Index", "Home"); + case LogInResultCode.Success: + _uiMessagesService.ShowSuccessMessage("Jesteś zalogowany/a."); + if (string.IsNullOrEmpty(returnUrl)) + { + return RedirectToAction("Index", "Home"); + } + return Redirect(returnUrl); + + case LogInResultCode.UserNotFound: + case LogInResultCode.InvalidPassword: + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Nieprawidłowa nazwa użytkownika lub hasło."); + return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); + + case LogInResultCode.InactiveAccount: + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Konto nie jest aktywne."); + return LocalRedirect("/Home/Index"); + + default: + throw new InvalidEnumArgumentException(argumentName: nameof(LogInResult.ResultCode), + invalidValue: (int)logInResult.ResultCode, + enumClass: typeof(LogInResult)); } - return Redirect(returnUrl); + } + else + { + _uiMessagesService.ShowFailureMessage("Logowanie nieudane. Proszę wypełnić poprawnie formularz."); + return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); } } catch @@ -59,29 +159,43 @@ public async Task Login(LoginModel model) _uiMessagesService.ShowFailureMessage("Logowanie nieudane."); return LocalRedirect("/Home/Index"); } - _uiMessagesService.ShowFailureMessage("Logowanie nieudane."); - return RedirectToAction(nameof(Login), new { returnUrl = returnUrl }); } + [Authorize] public async Task Logout() { await _userAuthenticationService.LogOutAsync(); + return RedirectToAction("Index", "Home"); } 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) { - _uiMessagesService.ShowSuccessMessage("Użytkownik zarejestrowany."); + var errors = ModelState.Values.SelectMany(v => v.Errors); + foreach (var error in errors) + { + Console.WriteLine(error.ErrorMessage); + } + return View(model); + } + + var (registrationResult, activationCode) = await _userAuthenticationService.RegisterUser( + model.UserName, UserType.Regular, model.Email, model.Password); + + if (registrationResult) + { + _userAuthenticationService.SendActivationEmail(model.Email, activationCode); + _uiMessagesService.ShowSuccessMessage("Wysłano mail aktywacyjny."); return LocalRedirect("/Home/Index"); } } @@ -94,6 +208,23 @@ public async Task Register(RegisterUserModel model) return LocalRedirect("/Home/Index"); } + [HttpGet] + public async Task ActivateAccount(string activationCode) + { + var result = await _userService.ActivateUserAsync(activationCode); + + if (result.IsActivated) + { + _uiMessagesService.ShowSuccessMessage("Atywacja udana."); + return View("ActivateAccount"); + } + else + { + _uiMessagesService.ShowFailureMessage("Aktywacja konta nie powiodła się."); + return LocalRedirect("/Home/Index"); + } + } + public IActionResult AccessDenied() { return View(); diff --git a/TutorLizard.Web/Controllers/StudentController.cs b/TutorLizard.Web/Controllers/StudentController.cs index c85cbfcd..0c87ea23 100644 --- a/TutorLizard.Web/Controllers/StudentController.cs +++ b/TutorLizard.Web/Controllers/StudentController.cs @@ -74,7 +74,7 @@ public async Task AdRequests(IFormCollection buttonAction) [HttpPost] [ValidateAntiForgeryToken] - public async Task CreateScheduleItemRequest(int scheduleItemId, int adId) + public async Task CreateScheduleItemRequest(int scheduleItemId, int adId, bool isRemote) { int? studentId = _userAuthenticationService.GetLoggedInUserId(); @@ -86,7 +86,8 @@ public async Task CreateScheduleItemRequest(int scheduleItemId, i CreateScheduleItemRequestRequest request = new() { StudentId = (int)studentId, - ScheduleItemId = scheduleItemId + ScheduleItemId = scheduleItemId, + IsRemote = isRemote }; CreateScheduleItemRequestResponse response = await _studentService.CreateScheduleItemRequest(request); diff --git a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs index e4974d5a..c82ae73f 100644 --- a/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs +++ b/TutorLizard.Web/Interfaces/Services/IUserAuthenticationService.cs @@ -1,4 +1,5 @@ using TutorLizard.Shared.Enums; +using TutorLizard.Shared.Models.DTOs; namespace TutorLizard.BusinessLogic.Interfaces.Services; @@ -6,7 +7,11 @@ public interface IUserAuthenticationService { int? GetLoggedInUserId(); - public Task LogInAsync(string username, string password); + Task LogInAsync(string username, string password); public Task LogOutAsync(); - public Task RegisterUser(string username, UserType type, string email, string password); + public Task IsGoogleUserRegistered(string googleid); + public Task RegisterUserWithGoogle(string username, string email, string googleId); + public Task LogInWithGoogleAsync(string username, string googleId); + Task<(bool, string)> RegisterUser(string username, UserType type, string email, string password); + void SendActivationEmail(string email, string activationCode); } diff --git a/TutorLizard.Web/Migrations/20240602175824_Add-IsRemote-In-StudentService.Designer.cs b/TutorLizard.Web/Migrations/20240602175824_Add-IsRemote-In-StudentService.Designer.cs new file mode 100644 index 00000000..b2e7a1bd --- /dev/null +++ b/TutorLizard.Web/Migrations/20240602175824_Add-IsRemote-In-StudentService.Designer.cs @@ -0,0 +1,336 @@ +// +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("20240602175824_Add-IsRemote-In-StudentService")] + partial class AddIsRemoteInStudentService + { + /// + 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("DateCreated") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + 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/20240602175824_Add-IsRemote-In-StudentService.cs b/TutorLizard.Web/Migrations/20240602175824_Add-IsRemote-In-StudentService.cs new file mode 100644 index 00000000..a9856426 --- /dev/null +++ b/TutorLizard.Web/Migrations/20240602175824_Add-IsRemote-In-StudentService.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace TutorLizard.Web.Migrations +{ + /// + public partial class AddIsRemoteInStudentService : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} 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/20240614131623_AddGoogleIdToUser.Designer.cs b/TutorLizard.Web/Migrations/20240614131623_AddGoogleIdToUser.Designer.cs new file mode 100644 index 00000000..1c53d805 --- /dev/null +++ b/TutorLizard.Web/Migrations/20240614131623_AddGoogleIdToUser.Designer.cs @@ -0,0 +1,339 @@ +// +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("20240614131623_AddGoogleIdToUser")] + partial class AddGoogleIdToUser + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.6") + .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("DateCreated") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("GoogleId") + .HasColumnType("nvarchar(max)"); + + 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/20240614131623_AddGoogleIdToUser.cs b/TutorLizard.Web/Migrations/20240614131623_AddGoogleIdToUser.cs new file mode 100644 index 00000000..7d4bf0cf --- /dev/null +++ b/TutorLizard.Web/Migrations/20240614131623_AddGoogleIdToUser.cs @@ -0,0 +1,28 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace TutorLizard.Web.Migrations +{ + /// + public partial class AddGoogleIdToUser : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "GoogleId", + table: "Users", + type: "nvarchar(max)", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "GoogleId", + table: "Users"); + } + } +} diff --git a/TutorLizard.Web/Migrations/20240616164044_ChangePasswordHashToNullable.Designer.cs b/TutorLizard.Web/Migrations/20240616164044_ChangePasswordHashToNullable.Designer.cs new file mode 100644 index 00000000..002c703e --- /dev/null +++ b/TutorLizard.Web/Migrations/20240616164044_ChangePasswordHashToNullable.Designer.cs @@ -0,0 +1,339 @@ +// +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("20240616164044_ChangePasswordHashToNullable")] + partial class ChangePasswordHashToNullable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.6") + .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("DateCreated") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("GoogleId") + .HasColumnType("nvarchar(max)"); + + 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/20240616164044_ChangePasswordHashToNullable.cs b/TutorLizard.Web/Migrations/20240616164044_ChangePasswordHashToNullable.cs new file mode 100644 index 00000000..fdd6bff9 --- /dev/null +++ b/TutorLizard.Web/Migrations/20240616164044_ChangePasswordHashToNullable.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace TutorLizard.Web.Migrations +{ + /// + public partial class ChangePasswordHashToNullable : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} diff --git a/TutorLizard.Web/Migrations/20240616164645_PasswordHashToNullable.Designer.cs b/TutorLizard.Web/Migrations/20240616164645_PasswordHashToNullable.Designer.cs new file mode 100644 index 00000000..a0b51d4c --- /dev/null +++ b/TutorLizard.Web/Migrations/20240616164645_PasswordHashToNullable.Designer.cs @@ -0,0 +1,338 @@ +// +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("20240616164645_PasswordHashToNullable")] + partial class PasswordHashToNullable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.6") + .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("DateCreated") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("GoogleId") + .HasColumnType("nvarchar(max)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("nvarchar(40)"); + + b.Property("PasswordHash") + .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/20240616164645_PasswordHashToNullable.cs b/TutorLizard.Web/Migrations/20240616164645_PasswordHashToNullable.cs new file mode 100644 index 00000000..5073e0fd --- /dev/null +++ b/TutorLizard.Web/Migrations/20240616164645_PasswordHashToNullable.cs @@ -0,0 +1,40 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace TutorLizard.Web.Migrations +{ + /// + public partial class PasswordHashToNullable : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "PasswordHash", + table: "Users", + type: "nvarchar(100)", + maxLength: 100, + nullable: true, + oldClrType: typeof(string), + oldType: "nvarchar(100)", + oldMaxLength: 100); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterColumn( + name: "PasswordHash", + table: "Users", + type: "nvarchar(100)", + maxLength: 100, + nullable: false, + defaultValue: "", + oldClrType: typeof(string), + oldType: "nvarchar(100)", + oldMaxLength: 100, + oldNullable: true); + } + } +} diff --git a/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs b/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs index 146d001c..ba34cd76 100644 --- a/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs +++ b/TutorLizard.Web/Migrations/JaszczurContextModelSnapshot.cs @@ -17,7 +17,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder - .HasAnnotation("ProductVersion", "8.0.4") + .HasAnnotation("ProductVersion", "8.0.6") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); @@ -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,13 +220,20 @@ protected override void BuildModel(ModelBuilder modelBuilder) .HasMaxLength(100) .HasColumnType("nvarchar(100)"); + b.Property("IsActive") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("GoogleId") + .HasColumnType("nvarchar(max)"); + b.Property("Name") .IsRequired() .HasMaxLength(40) .HasColumnType("nvarchar(40)"); b.Property("PasswordHash") - .IsRequired() .HasMaxLength(100) .HasColumnType("nvarchar(100)"); diff --git a/TutorLizard.Web/Models/EmailSettings.cs b/TutorLizard.Web/Models/EmailSettings.cs new file mode 100644 index 00000000..481bb807 --- /dev/null +++ b/TutorLizard.Web/Models/EmailSettings.cs @@ -0,0 +1,13 @@ +namespace TutorLizard.Web.Models +{ + public class EmailSettings + { + 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/Models/LoginModel.cs b/TutorLizard.Web/Models/LoginModel.cs index 01f686c3..3fca4cf6 100644 --- a/TutorLizard.Web/Models/LoginModel.cs +++ b/TutorLizard.Web/Models/LoginModel.cs @@ -1,8 +1,9 @@ -using System.ComponentModel.DataAnnotations; +using Microsoft.AspNetCore.Authentication; +using System.ComponentModel.DataAnnotations; namespace TutorLizard.Web.Models; -public class LoginModel +public class LoginModel { [Required] public string UserName { get; set; } diff --git a/TutorLizard.Web/Program.cs b/TutorLizard.Web/Program.cs index b2112ff4..cc66a7b9 100644 --- a/TutorLizard.Web/Program.cs +++ b/TutorLizard.Web/Program.cs @@ -1,3 +1,4 @@ +using Microsoft.AspNetCore.Authentication.Google; using Microsoft.EntityFrameworkCore; using Serilog; using TutorLizard.BusinessLogic.Data; @@ -6,6 +7,7 @@ using TutorLizard.BusinessLogic.Options; using TutorLizard.BusinessLogic.Services; using TutorLizard.Web.Interfaces.Services; +using TutorLizard.Web.Models; using TutorLizard.Web.Services; using TutorLizard.Web.Components; @@ -35,7 +37,25 @@ builder.Services.AddScoped(); builder.Services.AddScoped(); -builder.Services.AddAuthentication("CookieAuth") +builder.Services.AddAuthentication(options => + { + options.DefaultScheme = "CookieAuth"; + }) + .AddGoogle(options => + { + options.ClientId = builder.Configuration["Auth:Google:ClientId"]; + options.ClientSecret = builder.Configuration["Auth:Google:ClientSecret"]; + options.SaveTokens = true; + options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents + { + OnRemoteFailure = context => + { + context.HandleResponse(); + context.Response.Redirect("/Account/Login"); + return Task.FromResult(0); + } + }; + }) .AddCookie("CookieAuth", options => { options.ExpireTimeSpan = TimeSpan.FromDays(1); @@ -54,6 +74,7 @@ }); builder.Services.AddTutorLizardDbRepositories(); +builder.Services.Configure(builder.Configuration.GetSection("EmailSettings")); var app = builder.Build(); @@ -70,12 +91,26 @@ app.UseCookiePolicy(new CookiePolicyOptions { - MinimumSameSitePolicy = SameSiteMode.Strict + MinimumSameSitePolicy = SameSiteMode.None, + Secure = CookieSecurePolicy.Always }); app.UseRouting(); +app.UseAuthentication(); app.UseAuthorization(); +app.UseHttpsRedirection(); + +app.UseEndpoints(endpoints => +{ + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + endpoints.MapControllerRoute( + name: "ActivateAccount", + pattern: "{controller=Account}/{action=ActivateAccount}/{activationCode?}"); +}); + app.UseAntiforgery(); app.MapControllerRoute( diff --git a/TutorLizard.Web/Services/UserAuthenticationService.cs b/TutorLizard.Web/Services/UserAuthenticationService.cs index ad502e91..d63e1d57 100644 --- a/TutorLizard.Web/Services/UserAuthenticationService.cs +++ b/TutorLizard.Web/Services/UserAuthenticationService.cs @@ -1,8 +1,15 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.Extensions.Options; +using System.Net; +using System.Net.Mail; using System.Security.Claims; -using TutorLizard.Shared.Enums; +using TutorLizard.BusinessLogic.Interfaces.Data.Repositories; using TutorLizard.BusinessLogic.Interfaces.Services; +using TutorLizard.BusinessLogic.Models; +using TutorLizard.Shared.Enums; +using TutorLizard.Shared.Models.DTOs; +using TutorLizard.Web.Models; namespace TutorLizard.BusinessLogic.Services; @@ -10,15 +17,55 @@ public class UserAuthenticationService : IUserAuthenticationService { private readonly IHttpContextAccessor _httpContextAccessor; private readonly IUserService _userService; + private readonly EmailSettings _emailSettings; + private readonly IDbRepository _userRepository; - public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService) + public UserAuthenticationService(IHttpContextAccessor httpContextAccessor, IUserService userService, IOptions emailSettings, IDbRepository userRepository) { _httpContextAccessor = httpContextAccessor; _userService = userService; + _emailSettings = emailSettings.Value; + _userRepository = userRepository; } - 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 (logInResult.ResultCode == LogInResultCode.Success && logInResult.User != null) + { + var claims = new List + { + 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, + }; + + if (_httpContextAccessor.HttpContext != null) + { + await _httpContextAccessor.HttpContext.SignInAsync("CookieAuth", + new ClaimsPrincipal(claimsIdentity), + authProperties); + } + } + + return logInResult; + } + + public async Task LogInWithGoogleAsync(string username, string googleId) + { + var user = await _userService.LogInWithGoogle(username, googleId); if (user is null) { @@ -46,6 +93,7 @@ public async Task LogInAsync(string username, string password) if (_httpContextAccessor.HttpContext is null) return false; + await _httpContextAccessor.HttpContext.SignOutAsync(); await _httpContextAccessor.HttpContext.SignInAsync("CookieAuth", new ClaimsPrincipal(claimsIdentity), authProperties); @@ -61,9 +109,27 @@ public async Task LogOutAsync() await _httpContextAccessor.HttpContext.SignOutAsync("CookieAuth"); } - public Task RegisterUser(string username, UserType type, string email, string password) + public async Task<(bool, string)> RegisterUser(string username, UserType type, string email, string password) + { + string activationCode = GenerateActivationCode(); + bool result = await _userService.RegisterUser(username, type, email, password, activationCode); + + return (result, activationCode); + } + + private string GenerateActivationCode() { - return _userService.RegisterUser(username, type, email, password); + return Guid.NewGuid().ToString(); + } + + public Task RegisterUserWithGoogle(string username, string email, string googleId) + { + return _userService.RegisterUserWithGoogle(username, email, googleId); + } + + public async Task IsGoogleUserRegistered(string googleid) + { + return await _userService.IsTheGoogleUserRegistered(googleid); } public int? GetLoggedInUserId() @@ -84,4 +150,33 @@ public Task RegisterUser(string username, UserType type, string email, str } return userId; } + + public void SendActivationEmail(string userEmail, string activationCode) + { + var fromAddress = new MailAddress(_emailSettings.FromAddress, "Tutor Lizard"); + var toAddress = new MailAddress(userEmail); + var fromPassword = _emailSettings.FromPassword; + + string subject = "Aktywacja konta"; + string body = $"Cześć tu zespół Tutor Lizard, \naby aktywować swoje konto, kliknij poniższy link: {_emailSettings.ActivationLink}{activationCode}"; + + var smtp = new SmtpClient + { + Host = _emailSettings.Host, + Port = _emailSettings.Port, + EnableSsl = _emailSettings.EnableSsl, + 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); + } + } + } diff --git a/TutorLizard.Web/TutorLizard.Web.csproj b/TutorLizard.Web/TutorLizard.Web.csproj index eb2bdcae..33e87095 100644 --- a/TutorLizard.Web/TutorLizard.Web.csproj +++ b/TutorLizard.Web/TutorLizard.Web.csproj @@ -8,11 +8,13 @@ + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/TutorLizard.Web/Views/Account/ActivateAccount.cshtml b/TutorLizard.Web/Views/Account/ActivateAccount.cshtml new file mode 100644 index 00000000..c11389f5 --- /dev/null +++ b/TutorLizard.Web/Views/Account/ActivateAccount.cshtml @@ -0,0 +1,6 @@ +@{ + ViewData["Title"] = "Aktywacja konta"; +} +

@ViewData["Title"]

+ +

Twoje konto zostało aktywowane.

\ No newline at end of file diff --git a/TutorLizard.Web/Views/Account/Login.cshtml b/TutorLizard.Web/Views/Account/Login.cshtml index 432986fd..8d831391 100644 --- a/TutorLizard.Web/Views/Account/Login.cshtml +++ b/TutorLizard.Web/Views/Account/Login.cshtml @@ -27,6 +27,14 @@ +
+
+

Login using Google

+
+ +
diff --git a/TutorLizard.Web/Views/Account/Register.cshtml b/TutorLizard.Web/Views/Account/Register.cshtml index 778877b6..16a771bb 100644 --- a/TutorLizard.Web/Views/Account/Register.cshtml +++ b/TutorLizard.Web/Views/Account/Register.cshtml @@ -32,6 +32,14 @@
+
+
+

Register using Google

+
+ +
diff --git a/TutorLizard.Web/Views/Shared/Components/AvailableScheduleForAd/Default.cshtml b/TutorLizard.Web/Views/Shared/Components/AvailableScheduleForAd/Default.cshtml index 471200c7..78510ae8 100644 --- a/TutorLizard.Web/Views/Shared/Components/AvailableScheduleForAd/Default.cshtml +++ b/TutorLizard.Web/Views/Shared/Components/AvailableScheduleForAd/Default.cshtml @@ -29,15 +29,21 @@ { Nie wysłano
- @if (item.Status == ScheduleItemRequestStatus.RequestNotSent) - { -
- + + @if (Model.IsRemote) + { +
+ +
+ } + +
- }
}
diff --git a/TutorLizard.Web/appsettings.json b/TutorLizard.Web/appsettings.json index 91103fa9..816d75ab 100644 --- a/TutorLizard.Web/appsettings.json +++ b/TutorLizard.Web/appsettings.json @@ -28,5 +28,11 @@ }, "ConnectionStrings": { "Default": "" + }, + "Auth": { + "Google": { + "ClientId": "placeholder", + "ClientSecret": "placeholder" + } } }