Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

7 feature user authentication and authorization #21

Merged
merged 13 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 164 additions & 0 deletions GameLibrary.Tests/Pages/Account/LoginModelTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Copyright 2024 Web.Tech. Group17
//
// Licensed under the Apache License, Version 2.0 (the "License"):
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using GameLibrary.Models;
using GameLibrary.Pages.Account;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;

namespace GameLibrary.Tests.Pages.Account;

public class LoginModelTests
{
private readonly Mock<SignInManager<User>> _mockSignInManager;
private readonly Mock<ILogger<LoginModel>> _mockLogger;
private readonly LoginModel _loginModel;

public LoginModelTests()
{
_mockSignInManager = MockSignInManager();
_mockLogger = new Mock<ILogger<LoginModel>>();
_loginModel = new LoginModel(_mockSignInManager.Object, _mockLogger.Object);
}

private static Mock<SignInManager<User>> MockSignInManager()
{
var userManager = new Mock<UserManager<User>>(
Mock.Of<IUserStore<User>>(), null!, null!, null!, null!, null!, null!, null!, null!);

return new Mock<SignInManager<User>>(
userManager.Object,
Mock.Of<IHttpContextAccessor>(),
Mock.Of<IUserClaimsPrincipalFactory<User>>(),
null!, null!, null!, null!);
}

[Fact]
public async Task OnPostAsync_ValidCredentials_RedirectsToReturnUrl()
{
// Arrange
_loginModel.Input = new LoginModel.InputModel
{
Email = "[email protected]",
Password = "Password123!",
RememberMe = false
};
_mockSignInManager.Setup(s => s.PasswordSignInAsync(
_loginModel.Input.Email,
_loginModel.Input.Password,
_loginModel.Input.RememberMe,
false))
.ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success);

// Act
var result = await _loginModel.OnPostAsync("~/");

// Assert
var redirectResult = Assert.IsType<LocalRedirectResult>(result);
Assert.Equal("~/", redirectResult.Url);
_mockLogger.Verify(
l => l.Log(
It.Is<LogLevel>(logLevel => logLevel == LogLevel.Information),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("User logged in.")),
It.IsAny<Exception>(),
It.Is<Func<It.IsAnyType, Exception?, string>>((_, __) => true)), Times.Once);
}

[Fact]
public async Task OnPostAsync_InvalidCredentials_ReturnsPageWithModelError()
{
// Arrange
_loginModel.Input = new LoginModel.InputModel
{
Email = "[email protected]",
Password = "WrongPassword!",
RememberMe = false
};
_mockSignInManager.Setup(s => s.PasswordSignInAsync(
_loginModel.Input.Email,
_loginModel.Input.Password,
_loginModel.Input.RememberMe,
false))
.ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Failed);

// Act
await _loginModel.OnPostAsync("~/");

// Assert
Assert.True(_loginModel.ModelState.ContainsKey(string.Empty));
Assert.Equal("Invalid login attempt.", _loginModel.ModelState[string.Empty]!.Errors[0].ErrorMessage);
}

[Fact]
public async Task OnPostAsync_LockedOut_RedirectsToLockoutPage()
{
// Arrange
_loginModel.Input = new LoginModel.InputModel
{
Email = "[email protected]",
Password = "Password123!",
RememberMe = false
};
_mockSignInManager.Setup(s => s.PasswordSignInAsync(
_loginModel.Input.Email,
_loginModel.Input.Password,
_loginModel.Input.RememberMe,
false))
.ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.LockedOut);

// Act
var result = await _loginModel.OnPostAsync("~/");

// Assert
var redirectResult = Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("./Lockout", redirectResult.PageName);
_mockLogger.Verify(
l => l.Log(
It.Is<LogLevel>(logLevel => logLevel == LogLevel.Warning),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("User account locked out.")),
It.IsAny<Exception>(),
It.Is<Func<It.IsAnyType, Exception?, string>>((_, __) => true)), Times.Once);
}

[Fact]
public async Task OnPostAsync_TwoFactorRequired_RedirectsTo2faPage()
{
// Arrange
_loginModel.Input = new LoginModel.InputModel
{
Email = "[email protected]",
Password = "Password123!",
RememberMe = true
};
_mockSignInManager.Setup(s => s.PasswordSignInAsync(
_loginModel.Input.Email,
_loginModel.Input.Password,
_loginModel.Input.RememberMe,
false))
.ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.TwoFactorRequired);

// Act
var result = await _loginModel.OnPostAsync("~/");

// Assert
var redirectResult = Assert.IsType<RedirectToPageResult>(result);
Assert.Equal("./LoginWith2fa", redirectResult.PageName);
Assert.Equal(new Dictionary<string, object> { { "ReturnUrl", "~/" }, { "RememberMe", true } }, redirectResult.RouteValues!);
}
}
68 changes: 68 additions & 0 deletions GameLibrary.Tests/Pages/Account/LogoutModelTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright 2024 Web.Tech. Group17
//
// Licensed under the Apache License, Version 2.0 (the "License"):
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using GameLibrary.Models;
using GameLibrary.Pages.Account;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Moq;

namespace GameLibrary.Tests.Pages.Account;

public class LogoutModelTests
{
private readonly Mock<SignInManager<User>> _mockSignInManager;
private readonly Mock<ILogger<LogoutModel>> _mockLogger;
private readonly LogoutModel _logoutModel;

public LogoutModelTests()
{
var userStoreMock = new Mock<IUserStore<User>>();
var userManagerMock = new Mock<UserManager<User>>(
userStoreMock.Object,
null!, null!, null!, null!, null!, null!, null!, null!);

_mockSignInManager = new Mock<SignInManager<User>>(
userManagerMock.Object,
Mock.Of<IHttpContextAccessor>(),
Mock.Of<IUserClaimsPrincipalFactory<User>>(),
null!, null!, null!, null!);

_mockLogger = new Mock<ILogger<LogoutModel>>();
_logoutModel = new LogoutModel(_mockSignInManager.Object, _mockLogger.Object);
}

[Fact]
public async Task OnPost_NoReturnUrl_RedirectsToPage()
{
// Act
var result = await _logoutModel.OnPost();

// Assert
_mockSignInManager.Verify(s => s.SignOutAsync(), Times.Once);

_mockLogger.Verify(
l => l.Log(
It.Is<LogLevel>(logLevel => logLevel == LogLevel.Information),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("User logged out.")),
It.IsAny<Exception>(),
It.Is<Func<It.IsAnyType, Exception?, string>>((v, t) => true)),
Times.Once);

Assert.IsType<RedirectToPageResult>(result);
}
}
119 changes: 119 additions & 0 deletions GameLibrary.Tests/Pages/Account/RegisterModelTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// Copyright 2024 Web.Tech. Group17
//
// Licensed under the Apache License, Version 2.0 (the "License"):
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using GameLibrary.Models;
using GameLibrary.Pages.Account;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Moq;

namespace GameLibrary.Tests.Pages.Account;

public class RegisterModelTests
{
private readonly Mock<UserManager<User>> _mockUserManager;
private readonly Mock<SignInManager<User>> _mockSignInManager;
private readonly Mock<IUserEmailStore<User>> _mockEmailStore;
private readonly Mock<ILogger<RegisterModel>> _mockLogger;
private readonly Mock<IEmailSender> _mockEmailSender;
private readonly RegisterModel _registerModel;

public RegisterModelTests()
{
_mockEmailStore = new Mock<IUserEmailStore<User>>();
_mockUserManager = new Mock<UserManager<User>>(
_mockEmailStore.Object, null!, null!, null!, null!, null!, null!, null!, null!);

_mockUserManager.Setup(u => u.SupportsUserEmail).Returns(true);

_mockSignInManager = MockSignInManager();
_mockLogger = new Mock<ILogger<RegisterModel>>();
_mockEmailSender = new Mock<IEmailSender>();

_registerModel = new RegisterModel(
_mockUserManager.Object,
_mockEmailStore.Object,
_mockSignInManager.Object,
_mockLogger.Object,
_mockEmailSender.Object);

var httpContext = new DefaultHttpContext();
httpContext.Request.Scheme = "http";
_registerModel.PageContext.HttpContext = httpContext;

_registerModel.Url = Mock.Of<IUrlHelper>();
}

private static Mock<SignInManager<User>> MockSignInManager()
{
var userManager = new Mock<UserManager<User>>(
Mock.Of<IUserStore<User>>(), null!, null!, null!, null!, null!, null!, null!, null!);

return new Mock<SignInManager<User>>(
userManager.Object,
Mock.Of<IHttpContextAccessor>(),
Mock.Of<IUserClaimsPrincipalFactory<User>>(),
null!, null!, null!, null!);
}

[Fact]
public async Task OnPostAsync_WhenUserCreationFails_ReturnsPageWithModelError()
{
// Arrange
_registerModel.Input = new RegisterModel.InputModel
{
Email = "[email protected]",
Password = "Password123!",
ConfirmPassword = "Password123!"
};

_mockUserManager.Setup(u => u.CreateAsync(It.IsAny<User>(), _registerModel.Input.Password))
.ReturnsAsync(IdentityResult.Failed(new IdentityError { Description = "User creation failed." }));

// Act
var result = await _registerModel.OnPostAsync("~/");

// Assert
Assert.IsType<PageResult>(result);
Assert.True(_registerModel.ModelState.ContainsKey(string.Empty));
Assert.Equal("User creation failed.", _registerModel.ModelState[string.Empty]!.Errors[0].ErrorMessage);
}

[Fact]
public async Task OnPostAsync_RegistrationFails_AddsModelError()
{
// Arrange
_registerModel.Input = new RegisterModel.InputModel
{
Email = "[email protected]",
Password = "Password123!",
ConfirmPassword = "Password123!"
};

_mockUserManager.Setup(u => u.CreateAsync(It.IsAny<User>(), _registerModel.Input.Password))
.ReturnsAsync(IdentityResult.Failed(new IdentityError { Description = "Registration failed." }));

// Act
var result = await _registerModel.OnPostAsync("~/");

// Assert
Assert.IsType<PageResult>(result);
Assert.True(_registerModel.ModelState.ContainsKey(string.Empty));
Assert.Equal("Registration failed.", _registerModel.ModelState[string.Empty]!.Errors[0].ErrorMessage);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright 2024 PET Group16
// Copyright 2024 Web.Tech. Group17
//
// Licensed under the Apache License, Version 2.0 (the "License"):
// you may not use this file except in compliance with the License.
Expand All @@ -12,12 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using GameLibrary.Pages;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Moq;
using System.Diagnostics;
using GameLibrary.Pages;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace GameLibrary.Tests;

Expand Down
4 changes: 3 additions & 1 deletion GameLibrary/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using GameLibrary.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace GameLibrary.Data;

public class ApplicationDbContext : DbContext
public class ApplicationDbContext : IdentityDbContext<User, Role, Guid>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
Expand Down
Binary file modified GameLibrary/Database.db
Binary file not shown.
Binary file added GameLibrary/Database.db-shm
Binary file not shown.
Empty file added GameLibrary/Database.db-wal
Empty file.
Loading