mirror of
https://github.com/MvDevsUnion/WPetition.git
synced 2026-02-27 20:40:36 +00:00
added admin dashboard
This commit is contained in:
9
Submission.Api/.claude/settings.local.json
Normal file
9
Submission.Api/.claude/settings.local.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(dotnet add package:*)",
|
||||
"Bash(dotnet build:*)",
|
||||
"Bash(findstr:*)"
|
||||
]
|
||||
}
|
||||
}
|
||||
161
Submission.Api/Controllers/AdminController.cs
Normal file
161
Submission.Api/Controllers/AdminController.cs
Normal file
@@ -0,0 +1,161 @@
|
||||
using Ashi.MongoInterface.Service;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Submission.Api.Configuration;
|
||||
using Submission.Api.Dto;
|
||||
using Submission.Api.Models;
|
||||
|
||||
namespace Submission.Api.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class AdminController : ControllerBase
|
||||
{
|
||||
private readonly PetitionSettings _petitionSettings;
|
||||
private readonly IMongoRepository<Author> _authorRepository;
|
||||
private readonly IMongoRepository<PetitionDetail> _petitionRepository;
|
||||
private readonly IMongoRepository<Signature> _signatureRepository;
|
||||
public AdminController(IOptions<PetitionSettings> petitionSettings, IMongoRepository<Author> authorRepository, IMongoRepository<PetitionDetail> petitionRepository, IMongoRepository<Signature> signatureRepository)
|
||||
{
|
||||
_petitionSettings = petitionSettings.Value;
|
||||
_authorRepository = authorRepository;
|
||||
_petitionRepository = petitionRepository;
|
||||
_signatureRepository = signatureRepository;
|
||||
}
|
||||
|
||||
[HttpGet("petitions", Name = "GetPetitions")]
|
||||
public IActionResult GetPetitions()
|
||||
{
|
||||
try
|
||||
{
|
||||
var petitions = _petitionRepository.FilterBy(x => x.Id != null);
|
||||
return Ok(petitions);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Problem("Petitions Folder not found");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("petitions-list", Name = "GetPetitionsList")]
|
||||
public IActionResult GetPetitionsList()
|
||||
{
|
||||
var list = _petitionRepository.FilterBy(x => x.Id != null);
|
||||
return Ok(list);
|
||||
}
|
||||
|
||||
[HttpGet("create-petition-folder", Name = "CreatePetitionFolder")]
|
||||
public IActionResult create_petition_folder()
|
||||
{
|
||||
if (Directory.Exists("Petitions"))
|
||||
{
|
||||
return Ok("Petitions folder already exists");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory("Petitions");
|
||||
return Ok("Petitions folder created");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Problem(e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
[HttpGet("export/{petition_id}", Name = "ExportSignatures")]
|
||||
public async Task<IActionResult> ExportSignatures([FromRoute] Guid petition_id)
|
||||
{
|
||||
var petition = await _petitionRepository.FindByIdAsync(petition_id);
|
||||
if (petition == null)
|
||||
return NotFound("Petition not found");
|
||||
|
||||
var signatures = _signatureRepository.FilterBy(x => x.PetitionId == petition_id)
|
||||
.OrderBy(x => x.Timestamp)
|
||||
.ToList();
|
||||
|
||||
var rows = new System.Text.StringBuilder();
|
||||
int index = 1;
|
||||
foreach (var sig in signatures)
|
||||
{
|
||||
rows.Append($@"
|
||||
<tr>
|
||||
<td>{index++}</td>
|
||||
<td>{System.Net.WebUtility.HtmlEncode(sig.Name)}</td>
|
||||
<td>{System.Net.WebUtility.HtmlEncode(sig.IdCard)}</td>
|
||||
<td>{sig.Timestamp:yyyy-MM-dd}</td>
|
||||
<td class=""sig-cell"">{sig.Signature_SVG}</td>
|
||||
</tr>");
|
||||
}
|
||||
|
||||
var html = $@"<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset=""utf-8"" />
|
||||
<title>Signatures - {System.Net.WebUtility.HtmlEncode(petition.NameEng)}</title>
|
||||
<style>
|
||||
body {{ font-family: Arial, sans-serif; margin: 20px; }}
|
||||
h1 {{ font-size: 1.4em; }}
|
||||
table {{ border-collapse: collapse; width: 100%; }}
|
||||
th, td {{ border: 1px solid #ccc; padding: 8px; text-align: left; vertical-align: middle; }}
|
||||
th {{ background: #f5f5f5; }}
|
||||
.sig-cell {{ width: 220px; height: 90px; }}
|
||||
.sig-cell svg {{ max-width: 100%; max-height: 100%; display: block; }}
|
||||
@media print {{ body {{ margin: 0; }} }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {{
|
||||
document.querySelectorAll('.sig-cell svg').forEach(function(svg) {{
|
||||
var w = svg.getAttribute('width');
|
||||
var h = svg.getAttribute('height');
|
||||
if (!svg.getAttribute('viewBox') && w && h) {{
|
||||
svg.setAttribute('viewBox', '0 0 ' + parseFloat(w) + ' ' + parseFloat(h));
|
||||
}}
|
||||
svg.removeAttribute('width');
|
||||
svg.removeAttribute('height');
|
||||
svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
|
||||
}});
|
||||
}});
|
||||
</script>
|
||||
<h1>Signatures for: {System.Net.WebUtility.HtmlEncode(petition.NameEng)}</h1>
|
||||
<p>Total signatures: {signatures.Count}</p>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>#</th>
|
||||
<th>Name</th>
|
||||
<th>ID Card</th>
|
||||
<th>Date Signed</th>
|
||||
<th>Signature</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows}
|
||||
</tbody>
|
||||
</table>
|
||||
</body>
|
||||
</html>";
|
||||
|
||||
return Content(html, "text/html");
|
||||
}
|
||||
[HttpPatch("petitions/{petition_id}/approve")]
|
||||
public async Task<IActionResult> ApprovePetition([FromRoute] Guid petition_id, [FromBody] ApprovalDto body)
|
||||
{
|
||||
var petition = await _petitionRepository.FindByIdAsync(petition_id);
|
||||
if (petition == null)
|
||||
return NotFound("Petition not found");
|
||||
|
||||
petition.isApproved = body.IsApproved;
|
||||
await _petitionRepository.ReplaceOneAsync(petition);
|
||||
|
||||
return Ok(petition);
|
||||
}
|
||||
}
|
||||
}
|
||||
48
Submission.Api/Controllers/AuthController.cs
Normal file
48
Submission.Api/Controllers/AuthController.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Submission.Api.Controllers
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public AuthController(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
public IActionResult Login([FromBody] LoginRequest request)
|
||||
{
|
||||
var adminUsername = _configuration["AdminSettings:Username"];
|
||||
var adminPassword = _configuration["AdminSettings:Password"];
|
||||
|
||||
if (request.Username != adminUsername || request.Password != adminPassword)
|
||||
return Unauthorized("Invalid credentials");
|
||||
|
||||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]!));
|
||||
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: _configuration["Jwt:Issuer"],
|
||||
claims: new[] { new Claim(ClaimTypes.Name, request.Username) },
|
||||
expires: DateTime.UtcNow.AddHours(24),
|
||||
signingCredentials: credentials
|
||||
);
|
||||
|
||||
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
|
||||
}
|
||||
}
|
||||
|
||||
public class LoginRequest
|
||||
{
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -28,167 +28,8 @@ namespace Submission.Api.Controllers
|
||||
_petitionRepository = petitionRepository;
|
||||
}
|
||||
|
||||
[HttpGet("petitions", Name = "GetPetitions")]
|
||||
public IActionResult GetPetitions()
|
||||
{
|
||||
try
|
||||
{
|
||||
var files = Directory.EnumerateFiles("Petitions");
|
||||
return Ok(files);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Problem("Petitions Folder not found");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("petitions-list", Name = "GetPetitionsList")]
|
||||
public IActionResult GetPetitionsList()
|
||||
{
|
||||
var list = _petitionRepository.FilterBy(x => x.Id != null);
|
||||
return Ok(list);
|
||||
}
|
||||
|
||||
|
||||
|
||||
[HttpGet("create-petition-folder", Name = "CreatePetitionFolder")]
|
||||
public IActionResult create_petition_folder()
|
||||
{
|
||||
if (Directory.Exists("Petitions"))
|
||||
{
|
||||
return Ok("Petitions folder already exists");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory("Petitions");
|
||||
return Ok("Petitions folder created");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Problem(e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("upload-petition", Name = "UploadPetition")]
|
||||
public async Task<IActionResult> UploadPetition(IFormFile file)
|
||||
{
|
||||
// Check if petition creation is allowed
|
||||
if (!_petitionSettings.AllowPetitionCreation)
|
||||
{
|
||||
return StatusCode(403, new { message = "Petition creation is disabled. Set 'PetitionSettings:AllowPetitionCreation' to true in appsettings.json" });
|
||||
}
|
||||
|
||||
// Validate file exists
|
||||
if (file == null || file.Length == 0)
|
||||
{
|
||||
return BadRequest(new { message = "No file uploaded" });
|
||||
}
|
||||
|
||||
// Validate file extension
|
||||
if (!file.FileName.EndsWith(".md", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return BadRequest(new { message = "Only .md files are allowed" });
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Read file content
|
||||
string fileContent;
|
||||
using (var reader = new StreamReader(file.OpenReadStream()))
|
||||
{
|
||||
fileContent = await reader.ReadToEndAsync();
|
||||
}
|
||||
|
||||
// Parse frontmatter and body
|
||||
var (frontmatter, body) = ParseMarkdownFile(fileContent);
|
||||
|
||||
if (frontmatter == null)
|
||||
{
|
||||
return BadRequest(new { message = "Invalid markdown format. Frontmatter is required." });
|
||||
}
|
||||
|
||||
// Parse YAML frontmatter
|
||||
var deserializer = new DeserializerBuilder()
|
||||
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
||||
.Build();
|
||||
|
||||
var metadata = deserializer.Deserialize<Dictionary<string, object>>(frontmatter);
|
||||
|
||||
// Extract values
|
||||
var petitionId = Guid.NewGuid();
|
||||
var startDateStr = metadata["startDate"].ToString();
|
||||
var nameDhiv = metadata["nameDhiv"].ToString();
|
||||
var nameEng = metadata["nameEng"].ToString();
|
||||
var authorData = metadata["author"] as Dictionary<object, object>;
|
||||
|
||||
var authorName = authorData["name"].ToString();
|
||||
var authorNid = authorData["nid"].ToString();
|
||||
|
||||
// Parse start date (format: dd-MM-yyyy)
|
||||
var startDate = DateOnly.ParseExact(startDateStr, "dd-MM-yyyy", CultureInfo.InvariantCulture);
|
||||
|
||||
// Parse petition bodies from markdown
|
||||
var (petitionBodyDhiv, petitionBodyEng) = ParsePetitionBodies(body);
|
||||
|
||||
// Check if petition already exists
|
||||
var existingPetition = await _petitionRepository.FindByIdAsync(petitionId);
|
||||
if (existingPetition != null)
|
||||
{
|
||||
return Conflict(new { message = $"A petition with ID '{petitionId}' already exists in the database" });
|
||||
}
|
||||
|
||||
// Create or get author
|
||||
var author = await _authorRepository.FindOneAsync(x => x.NID == authorNid);
|
||||
if (author == null)
|
||||
{
|
||||
author = new Author
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = authorName,
|
||||
NID = authorNid
|
||||
};
|
||||
await _authorRepository.InsertOneAsync(author);
|
||||
}
|
||||
|
||||
// Create petition
|
||||
var petition = new PetitionDetail
|
||||
{
|
||||
Id = petitionId,
|
||||
StartDate = startDate,
|
||||
NameDhiv = nameDhiv,
|
||||
NameEng = nameEng,
|
||||
AuthorId = author.Id,
|
||||
PetitionBodyDhiv = petitionBodyDhiv,
|
||||
PetitionBodyEng = petitionBodyEng,
|
||||
SignatureCount = 0
|
||||
};
|
||||
|
||||
await _petitionRepository.InsertOneAsync(petition);
|
||||
|
||||
// Save file with GUID prefix
|
||||
Directory.CreateDirectory("Petitions");
|
||||
var newFileName = $"{Guid.NewGuid()}_{file.FileName}";
|
||||
var filePath = Path.Combine("Petitions", newFileName);
|
||||
|
||||
await System.IO.File.WriteAllTextAsync(filePath, fileContent);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
message = "Petition created successfully",
|
||||
petitionId = petitionId,
|
||||
fileName = newFileName,
|
||||
filePath = filePath,
|
||||
authorId = author.Id
|
||||
});
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return Problem(e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("svg-debug", Name = "SvgDebug")]
|
||||
public async Task<IActionResult> SVG_TEST([FromForm]string svg)
|
||||
|
||||
7
Submission.Api/Dto/ApprovalDto.cs
Normal file
7
Submission.Api/Dto/ApprovalDto.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace Submission.Api.Dto
|
||||
{
|
||||
public class ApprovalDto
|
||||
{
|
||||
public bool IsApproved { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
using System.Text;
|
||||
using Ashi.MongoInterface;
|
||||
using Ashi.MongoInterface.Service;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Submission.Api.Configuration;
|
||||
using Submission.Api.Controllers;
|
||||
using Submission.Api.Services;
|
||||
@@ -28,6 +31,27 @@ builder.Services.AddSwaggerGen();
|
||||
// Register TurnstileService with typed HttpClient
|
||||
builder.Services.AddHttpClient<TurnstileService>();
|
||||
|
||||
// Add JWT authentication
|
||||
var jwtKey = builder.Configuration["Jwt:Key"]!;
|
||||
var jwtIssuer = builder.Configuration["Jwt:Issuer"]!;
|
||||
builder.Services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = false,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtIssuer,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
|
||||
};
|
||||
});
|
||||
|
||||
// Add rate limiting
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
@@ -53,6 +77,7 @@ app.UseHttpsRedirection();
|
||||
|
||||
app.UseRateLimiter();
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="9.0.11" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.0.1" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.2.1" />
|
||||
|
||||
@@ -15,5 +15,13 @@
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AdminSettings": {
|
||||
"Username": "admin",
|
||||
"Password": "admin123"
|
||||
},
|
||||
"Jwt": {
|
||||
"Key": "dev-secret-key-that-is-at-least-32-characters-long!",
|
||||
"Issuer": "SubmissionApi"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { BrowserRouter, Routes, Route } from "react-router-dom";
|
||||
import { HomePage } from "@/pages/HomePage";
|
||||
import { PetitionPage } from "@/pages/PetitionPage";
|
||||
import { CreatePetitionPage } from "@/pages/CreatePetitionPage";
|
||||
import { AdminLoginPage } from "@/pages/AdminLoginPage";
|
||||
import { AdminDashboardPage } from "@/pages/AdminDashboardPage";
|
||||
import { Layout } from "@/components/layout/Layout";
|
||||
|
||||
function App() {
|
||||
@@ -12,6 +14,8 @@ function App() {
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/Petition/:slug" element={<PetitionPage />} />
|
||||
<Route path="/CreatePetition" element={<CreatePetitionPage />} />
|
||||
<Route path="/admin/login" element={<AdminLoginPage />} />
|
||||
<Route path="/admin" element={<AdminDashboardPage />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
</BrowserRouter>
|
||||
|
||||
117
frontend-react/src/lib/adminApi.ts
Normal file
117
frontend-react/src/lib/adminApi.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
const API_BASE_URL = "";
|
||||
|
||||
const TOKEN_KEY = "adminToken";
|
||||
|
||||
export function getToken(): string | null {
|
||||
return localStorage.getItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
localStorage.setItem(TOKEN_KEY, token);
|
||||
}
|
||||
|
||||
export function clearToken(): void {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export async function login(
|
||||
username: string,
|
||||
password: string,
|
||||
): Promise<string> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
throw new Error("Invalid credentials");
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Login failed: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setToken(data.token);
|
||||
return data.token;
|
||||
}
|
||||
|
||||
export async function adminFetch(
|
||||
url: string,
|
||||
options: RequestInit = {},
|
||||
): Promise<Response> {
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
window.location.href = "/admin/login";
|
||||
throw new Error("No token");
|
||||
}
|
||||
|
||||
const res = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...options.headers,
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
clearToken();
|
||||
window.location.href = "/admin/login";
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
export interface AdminPetition {
|
||||
id: string;
|
||||
slug: string;
|
||||
nameEng: string;
|
||||
nameDhiv: string;
|
||||
signatureCount: number;
|
||||
startDate: string;
|
||||
isApproved: boolean;
|
||||
authorDetails?: { name: string };
|
||||
}
|
||||
|
||||
export async function fetchAdminPetitions(): Promise<AdminPetition[]> {
|
||||
const res = await adminFetch(`${API_BASE_URL}/api/admin/petitions`);
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.detail || `HTTP error: ${res.status}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function createPetitionFolder(): Promise<string> {
|
||||
const res = await adminFetch(
|
||||
`${API_BASE_URL}/api/admin/create-petition-folder`,
|
||||
);
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP error: ${res.status}`);
|
||||
}
|
||||
return res.text();
|
||||
}
|
||||
|
||||
export async function updatePetitionApproval(
|
||||
petitionId: string,
|
||||
isApproved: boolean,
|
||||
): Promise<void> {
|
||||
const res = await adminFetch(
|
||||
`${API_BASE_URL}/api/admin/petitions/${petitionId}/approve`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ isApproved }),
|
||||
},
|
||||
);
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.detail || `HTTP error: ${res.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function getExportUrl(petitionId: string): string {
|
||||
return `${API_BASE_URL}/api/admin/export/${petitionId}`;
|
||||
}
|
||||
278
frontend-react/src/pages/AdminDashboardPage.tsx
Normal file
278
frontend-react/src/pages/AdminDashboardPage.tsx
Normal file
@@ -0,0 +1,278 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import {
|
||||
fetchAdminPetitions,
|
||||
createPetitionFolder,
|
||||
getExportUrl,
|
||||
getToken,
|
||||
clearToken,
|
||||
updatePetitionApproval,
|
||||
type AdminPetition,
|
||||
} from "@/lib/adminApi";
|
||||
import {
|
||||
Loader2,
|
||||
LogOut,
|
||||
FileDown,
|
||||
FolderPlus,
|
||||
Users,
|
||||
ShieldCheck,
|
||||
CheckCircle,
|
||||
Clock,
|
||||
Eye,
|
||||
XCircle,
|
||||
} from "lucide-react";
|
||||
|
||||
export function AdminDashboardPage() {
|
||||
const navigate = useNavigate();
|
||||
const [petitions, setPetitions] = useState<AdminPetition[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [folderMsg, setFolderMsg] = useState<string | null>(null);
|
||||
const [togglingId, setTogglingId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) {
|
||||
navigate("/admin/login");
|
||||
return;
|
||||
}
|
||||
loadPetitions();
|
||||
}, [navigate]);
|
||||
|
||||
async function loadPetitions() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await fetchAdminPetitions();
|
||||
setPetitions(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load petitions");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateFolder() {
|
||||
setFolderMsg(null);
|
||||
try {
|
||||
const msg = await createPetitionFolder();
|
||||
setFolderMsg(msg);
|
||||
} catch (err) {
|
||||
setFolderMsg(
|
||||
err instanceof Error ? err.message : "Failed to create folder",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleApproval(petition: AdminPetition) {
|
||||
setTogglingId(petition.id);
|
||||
try {
|
||||
await updatePetitionApproval(petition.id, !petition.isApproved);
|
||||
await loadPetitions();
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : "Failed to update approval",
|
||||
);
|
||||
} finally {
|
||||
setTogglingId(null);
|
||||
}
|
||||
}
|
||||
|
||||
function handleLogout() {
|
||||
clearToken();
|
||||
navigate("/admin/login");
|
||||
}
|
||||
|
||||
function handleExport(petitionId: string) {
|
||||
const token = getToken();
|
||||
if (!token) return;
|
||||
fetch(getExportUrl(petitionId), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.status === 401) {
|
||||
clearToken();
|
||||
navigate("/admin/login");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error("Export failed");
|
||||
return res.blob();
|
||||
})
|
||||
.then((blob) => {
|
||||
if (!blob) return;
|
||||
const url = URL.createObjectURL(blob);
|
||||
window.open(url, "_blank");
|
||||
})
|
||||
.catch(() => {
|
||||
setError("Failed to export petition");
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 font-sans">
|
||||
{/* Header */}
|
||||
<div className="bg-white border-b border-slate-200 shadow-sm">
|
||||
<div className="max-w-5xl mx-auto px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<ShieldCheck className="w-5 h-5 text-slate-700" />
|
||||
<h1 className="text-lg font-semibold text-slate-900">
|
||||
Admin Dashboard
|
||||
</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={handleCreateFolder}
|
||||
className="inline-flex items-center gap-1.5 text-xs text-slate-500 hover:text-slate-800 border border-slate-200 hover:border-slate-300 rounded-md px-2.5 py-1.5 transition-colors"
|
||||
>
|
||||
<FolderPlus className="w-3.5 h-3.5" />
|
||||
Create Folder
|
||||
</button>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="inline-flex items-center gap-1.5 text-xs text-red-500 hover:text-red-600 border border-red-200 hover:border-red-300 rounded-md px-2.5 py-1.5 transition-colors"
|
||||
>
|
||||
<LogOut className="w-3.5 h-3.5" />
|
||||
Logout
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-5xl mx-auto px-4 py-6">
|
||||
{folderMsg && (
|
||||
<div className="bg-blue-50 border border-blue-200 text-blue-700 text-sm rounded-lg px-4 py-2.5 mb-4">
|
||||
{folderMsg}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg px-4 py-2.5 mb-4">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-sm font-medium text-slate-500 uppercase tracking-wide">
|
||||
All Petitions
|
||||
</h2>
|
||||
<span className="text-xs text-slate-400">
|
||||
{petitions.length} total
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<Loader2 className="w-6 h-6 text-slate-400 animate-spin" />
|
||||
</div>
|
||||
) : petitions.length === 0 ? (
|
||||
<div className="bg-white rounded-xl border border-slate-200 p-8 text-center">
|
||||
<p className="text-slate-500 text-sm">No petitions found.</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-xl border border-slate-200 overflow-hidden shadow-sm">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 bg-slate-50/80">
|
||||
<th className="text-left px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
|
||||
Petition
|
||||
</th>
|
||||
<th className="text-left px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide hidden md:table-cell">
|
||||
Slug
|
||||
</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
|
||||
Sigs
|
||||
</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
|
||||
Status
|
||||
</th>
|
||||
<th className="text-center px-4 py-2.5 text-xs font-medium text-slate-500 uppercase tracking-wide">
|
||||
Actions
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{petitions.map((p) => (
|
||||
<tr
|
||||
key={p.id}
|
||||
className="border-b border-slate-100 last:border-0 hover:bg-slate-50/50 transition-colors"
|
||||
>
|
||||
<td className="px-4 py-3">
|
||||
<div className="font-medium text-slate-900 text-sm">
|
||||
{p.nameEng}
|
||||
</div>
|
||||
<div
|
||||
className="text-xs text-slate-400 dhivehi mt-0.5"
|
||||
dir="rtl"
|
||||
>
|
||||
{p.nameDhiv}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3 hidden md:table-cell">
|
||||
<span className="text-xs text-slate-400 font-mono bg-slate-50 px-1.5 py-0.5 rounded">
|
||||
{p.slug}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
<span className="inline-flex items-center gap-1 text-slate-600 text-xs">
|
||||
<Users className="w-3 h-3" />
|
||||
{p.signatureCount}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-center">
|
||||
{p.isApproved ? (
|
||||
<span className="inline-flex items-center gap-1 text-xs font-medium text-emerald-700 bg-emerald-50 rounded-full px-2 py-0.5">
|
||||
<CheckCircle className="w-3 h-3" />
|
||||
Approved
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center gap-1 text-xs font-medium text-amber-700 bg-amber-50 rounded-full px-2 py-0.5">
|
||||
<Clock className="w-3 h-3" />
|
||||
Pending
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<button
|
||||
onClick={() => navigate(`/Petition/${p.slug || p.id}`)}
|
||||
className="p-1.5 rounded-md text-slate-400 hover:text-slate-700 hover:bg-slate-100 transition-colors"
|
||||
title="View petition"
|
||||
>
|
||||
<Eye className="w-4 h-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleToggleApproval(p)}
|
||||
disabled={togglingId === p.id}
|
||||
className={`p-1.5 rounded-md transition-colors disabled:opacity-50 ${
|
||||
p.isApproved
|
||||
? "text-red-500 hover:text-red-700 hover:bg-red-50"
|
||||
: "text-emerald-500 hover:text-emerald-700 hover:bg-emerald-50"
|
||||
}`}
|
||||
title={p.isApproved ? "Disapprove" : "Approve"}
|
||||
>
|
||||
{togglingId === p.id ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : p.isApproved ? (
|
||||
<XCircle className="w-4 h-4" />
|
||||
) : (
|
||||
<CheckCircle className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExport(p.id)}
|
||||
className="p-1.5 rounded-md text-slate-400 hover:text-blue-600 hover:bg-blue-50 transition-colors"
|
||||
title="Export signatures"
|
||||
>
|
||||
<FileDown className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
103
frontend-react/src/pages/AdminLoginPage.tsx
Normal file
103
frontend-react/src/pages/AdminLoginPage.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { login } from "@/lib/adminApi";
|
||||
import { Lock, Loader2 } from "lucide-react";
|
||||
|
||||
export function AdminLoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await login(username, password);
|
||||
navigate("/admin");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Login failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-b from-slate-50 to-slate-100 flex items-center justify-center px-4">
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-8">
|
||||
<div className="flex justify-center mb-6">
|
||||
<div className="bg-slate-100 p-3 rounded-full">
|
||||
<Lock className="w-8 h-8 text-slate-600" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h1 className="text-xl font-bold text-slate-900 text-center mb-6">
|
||||
Admin Login
|
||||
</h1>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg px-4 py-3 mb-4">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label
|
||||
htmlFor="username"
|
||||
className="block text-sm font-medium text-slate-700 mb-1"
|
||||
>
|
||||
Username
|
||||
</label>
|
||||
<input
|
||||
id="username"
|
||||
type="text"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
autoFocus
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-slate-700 mb-1"
|
||||
>
|
||||
Password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full bg-slate-900 hover:bg-slate-800 text-white font-medium py-2.5 rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Signing in...
|
||||
</>
|
||||
) : (
|
||||
"Sign in"
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -85,7 +85,7 @@ function GuidelinesModal({ onAccept }: { onAccept: () => void }) {
|
||||
I Understand, Continue
|
||||
</button>
|
||||
<a
|
||||
href="https://majlis.gov.mv/en/pes/petitions"
|
||||
href="https://epetition.majlis.gov.mv/petition-rules"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 font-medium py-3 px-6 rounded-lg transition-colors text-center"
|
||||
|
||||
@@ -11,7 +11,8 @@ import { AuthorCard } from "@/components/petition/AuthorCard";
|
||||
import { PetitionBody } from "@/components/petition/PetitionBody";
|
||||
import { SignatureForm } from "@/components/signature/SignatureForm";
|
||||
import { TweetModal } from "@/components/TweetModal";
|
||||
import { PenLine } from "lucide-react";
|
||||
import { PenLine, ArrowLeft } from "lucide-react";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
export function PetitionPage() {
|
||||
const { slug } = useParams<{ slug: string }>();
|
||||
@@ -58,7 +59,27 @@ export function PetitionPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50/50 p-4 md:p-8 font-sans">
|
||||
<div className="min-h-screen bg-slate-50/50 font-sans">
|
||||
<div className="sticky top-0 z-10 bg-white/90 backdrop-blur-sm border-b border-slate-200 shadow-sm">
|
||||
<div className="max-w-3xl mx-auto px-4 py-2.5 flex items-center gap-3">
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-900 transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Home
|
||||
</Link>
|
||||
{petition && (
|
||||
<>
|
||||
<span className="text-slate-300">/</span>
|
||||
<span className="text-sm text-slate-700 font-medium truncate">
|
||||
{language === "dv" ? petition.nameDhiv : petition.nameEng}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4 md:p-8">
|
||||
<div className="max-w-3xl mx-auto bg-white rounded-xl shadow-sm border border-slate-100 p-6 md:p-10 animate-in fade-in duration-500 slide-in-from-bottom-4">
|
||||
{loading ? (
|
||||
<div className="min-h-[400px] flex flex-col justify-center">
|
||||
@@ -111,6 +132,7 @@ export function PetitionPage() {
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ export default defineConfig({
|
||||
server: {
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://localhost:9755",
|
||||
target: "http://localhost:5299",
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "9.0.0",
|
||||
"rollForward": "latestMinor",
|
||||
"allowPrerelease": false
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user