Files
systemrevivalserver/Services/Admin/Pages/Login.cshtml.cs
T

82 lines
2.1 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using DataServer.Data;
using Server.Services.Auth;
namespace Server.Services.Admin.Pages;
public class LoginModel : PageModel
{
private readonly GameDbContext _db;
private readonly IPasswordHasher _hasher;
public LoginModel(GameDbContext db, IPasswordHasher hasher)
{
_db = db;
_hasher = hasher;
}
[BindProperty]
public string Username { get; set; } = "";
[BindProperty]
public string Password { get; set; } = "";
public string? ErrorMessage { get; set; }
public void OnGet()
{
// Check if already logged in
if (HttpContext.Session.GetString("AdminId") != null)
{
Response.Redirect("/admin");
}
}
public async Task<IActionResult> OnPostAsync()
{
if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
{
ErrorMessage = "Username and password are required.";
return Page();
}
var account = await _db.Accounts
.FirstOrDefaultAsync(a => a.Username == Username);
if (account == null)
{
ErrorMessage = "Invalid username or password.";
return Page();
}
if (!_hasher.Verify(Password, account.PasswordHash, account.PasswordSalt))
{
ErrorMessage = "Invalid username or password.";
return Page();
}
// Check if admin
if (account.Role < AccountRole.Moderator)
{
ErrorMessage = "You do not have permission to access the admin panel.";
return Page();
}
// Check if banned
if (account.IsBanned)
{
ErrorMessage = "Your account has been banned.";
return Page();
}
// Set session
HttpContext.Session.SetString("AdminId", account.Id.ToString());
HttpContext.Session.SetString("AdminUsername", account.Username);
HttpContext.Session.SetString("AdminRole", account.Role.ToString());
return RedirectToPage("/Index");
}
}