User management
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -68,3 +68,4 @@ coverage/
|
|||||||
.storybook-out
|
.storybook-out
|
||||||
|
|
||||||
.env
|
.env
|
||||||
|
frontend/dist
|
||||||
4
AGENT.md
4
AGENT.md
@@ -54,3 +54,7 @@ bloop/
|
|||||||
├── pnpm-workspace.yaml # pnpm workspace
|
├── pnpm-workspace.yaml # pnpm workspace
|
||||||
└── package.json # Root scripts
|
└── package.json # Root scripts
|
||||||
```
|
```
|
||||||
|
|
||||||
|
# Managing Shared Types Between Rust and TypeScript
|
||||||
|
|
||||||
|
ts-rs allows you to derive TypeScript types from Rust structs/enums. By annotating your Rust types with #[derive(TS)] and related macros, ts-rs will generate .ts declaration files for those types.
|
||||||
|
|||||||
@@ -17,3 +17,5 @@ sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "chron
|
|||||||
chrono = { version = "0.4", features = ["serde"] }
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||||
dotenvy = "0.15"
|
dotenvy = "0.15"
|
||||||
|
bcrypt = "0.15"
|
||||||
|
jsonwebtoken = "9.2"
|
||||||
|
|||||||
23
backend/migrations/002_update_users_auth.sql
Normal file
23
backend/migrations/002_update_users_auth.sql
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
-- Update users table for authentication system
|
||||||
|
-- Add new columns and update existing ones
|
||||||
|
|
||||||
|
-- First, add the new columns
|
||||||
|
ALTER TABLE users
|
||||||
|
ADD COLUMN password_hash VARCHAR(255),
|
||||||
|
ADD COLUMN is_admin BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
|
||||||
|
-- Update existing users to have a placeholder password hash
|
||||||
|
-- (This is safe since there shouldn't be any real users yet)
|
||||||
|
UPDATE users SET password_hash = '$2b$10$placeholder' WHERE password_hash IS NULL;
|
||||||
|
|
||||||
|
-- Make password_hash required
|
||||||
|
ALTER TABLE users ALTER COLUMN password_hash SET NOT NULL;
|
||||||
|
|
||||||
|
-- Remove the old password column if it exists
|
||||||
|
ALTER TABLE users DROP COLUMN IF EXISTS password;
|
||||||
|
|
||||||
|
-- Create index on email for faster lookups
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
||||||
|
|
||||||
|
-- Create index on is_admin for admin queries
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_users_is_admin ON users(is_admin);
|
||||||
90
backend/src/auth.rs
Normal file
90
backend/src/auth.rs
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
use axum::{
|
||||||
|
async_trait,
|
||||||
|
extract::FromRequestParts,
|
||||||
|
http::{request::Parts, StatusCode, HeaderMap},
|
||||||
|
RequestPartsExt,
|
||||||
|
};
|
||||||
|
use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub struct Claims {
|
||||||
|
pub user_id: Uuid,
|
||||||
|
pub email: String,
|
||||||
|
pub is_admin: bool,
|
||||||
|
pub exp: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct AuthUser {
|
||||||
|
pub user_id: Uuid,
|
||||||
|
pub email: String,
|
||||||
|
pub is_admin: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl<S> FromRequestParts<S> for AuthUser
|
||||||
|
where
|
||||||
|
S: Send + Sync,
|
||||||
|
{
|
||||||
|
type Rejection = StatusCode;
|
||||||
|
|
||||||
|
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
|
||||||
|
let headers = &parts.headers;
|
||||||
|
|
||||||
|
let auth_header = headers
|
||||||
|
.get("authorization")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
|
|
||||||
|
let token = auth_header
|
||||||
|
.strip_prefix("Bearer ")
|
||||||
|
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||||
|
|
||||||
|
let jwt_secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "your-secret-key".to_string());
|
||||||
|
|
||||||
|
let claims = decode::<Claims>(
|
||||||
|
token,
|
||||||
|
&DecodingKey::from_secret(jwt_secret.as_ref()),
|
||||||
|
&Validation::default(),
|
||||||
|
)
|
||||||
|
.map_err(|_| StatusCode::UNAUTHORIZED)?
|
||||||
|
.claims;
|
||||||
|
|
||||||
|
Ok(AuthUser {
|
||||||
|
user_id: claims.user_id,
|
||||||
|
email: claims.email,
|
||||||
|
is_admin: claims.is_admin,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_token(user_id: Uuid, email: String, is_admin: bool) -> Result<String, jsonwebtoken::errors::Error> {
|
||||||
|
let jwt_secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "your-secret-key".to_string());
|
||||||
|
|
||||||
|
let expiration = chrono::Utc::now()
|
||||||
|
.checked_add_signed(chrono::Duration::hours(24))
|
||||||
|
.expect("valid timestamp")
|
||||||
|
.timestamp() as usize;
|
||||||
|
|
||||||
|
let claims = Claims {
|
||||||
|
user_id,
|
||||||
|
email,
|
||||||
|
is_admin,
|
||||||
|
exp: expiration,
|
||||||
|
};
|
||||||
|
|
||||||
|
encode(
|
||||||
|
&Header::default(),
|
||||||
|
&claims,
|
||||||
|
&EncodingKey::from_secret(jwt_secret.as_ref()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hash_password(password: &str) -> Result<String, bcrypt::BcryptError> {
|
||||||
|
bcrypt::hash(password, bcrypt::DEFAULT_COST)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn verify_password(password: &str, hash: &str) -> Result<bool, bcrypt::BcryptError> {
|
||||||
|
bcrypt::verify(password, hash)
|
||||||
|
}
|
||||||
@@ -1,22 +1,22 @@
|
|||||||
use axum::{
|
use axum::{
|
||||||
routing::{get, post},
|
extract::{Extension, Query},
|
||||||
Router,
|
|
||||||
Json,
|
|
||||||
response::Json as ResponseJson,
|
response::Json as ResponseJson,
|
||||||
extract::{Query, Extension},
|
routing::{get, post},
|
||||||
|
Json, Router,
|
||||||
};
|
};
|
||||||
use tower_http::cors::CorsLayer;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tracing_subscriber;
|
use sqlx::{postgres::PgPoolOptions, PgPool};
|
||||||
use sqlx::{PgPool, postgres::PgPoolOptions};
|
|
||||||
use std::env;
|
use std::env;
|
||||||
|
use tower_http::cors::CorsLayer;
|
||||||
|
use tracing_subscriber;
|
||||||
|
|
||||||
|
mod auth;
|
||||||
mod routes;
|
|
||||||
mod models;
|
mod models;
|
||||||
|
mod routes;
|
||||||
|
|
||||||
use routes::health;
|
use auth::hash_password;
|
||||||
use models::ApiResponse;
|
use models::ApiResponse;
|
||||||
|
use routes::{health, projects, users};
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
struct HelloQuery {
|
struct HelloQuery {
|
||||||
@@ -35,7 +35,9 @@ async fn hello_handler(Query(params): Query<HelloQuery>) -> ResponseJson<HelloRe
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn echo_handler(Json(payload): Json<serde_json::Value>) -> ResponseJson<ApiResponse<serde_json::Value>> {
|
async fn echo_handler(
|
||||||
|
Json(payload): Json<serde_json::Value>,
|
||||||
|
) -> ResponseJson<ApiResponse<serde_json::Value>> {
|
||||||
ResponseJson(ApiResponse {
|
ResponseJson(ApiResponse {
|
||||||
success: true,
|
success: true,
|
||||||
data: Some(payload),
|
data: Some(payload),
|
||||||
@@ -51,19 +53,26 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
tracing_subscriber::fmt::init();
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
// Database connection
|
// Database connection
|
||||||
let database_url = env::var("DATABASE_URL")
|
let database_url =
|
||||||
.expect("DATABASE_URL must be set in environment or .env file");
|
env::var("DATABASE_URL").expect("DATABASE_URL must be set in environment or .env file");
|
||||||
|
|
||||||
let pool = PgPoolOptions::new()
|
let pool = PgPoolOptions::new()
|
||||||
.max_connections(10)
|
.max_connections(10)
|
||||||
.connect(&database_url)
|
.connect(&database_url)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
// Create default admin account if it doesn't exist
|
||||||
|
if let Err(e) = create_admin_account(&pool).await {
|
||||||
|
tracing::warn!("Failed to create admin account: {}", e);
|
||||||
|
}
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/", get(|| async { "Bloop API" }))
|
.route("/", get(|| async { "Bloop API" }))
|
||||||
.route("/health", get(health::health_check))
|
.route("/health", get(health::health_check))
|
||||||
.route("/hello", get(hello_handler))
|
.route("/hello", get(hello_handler))
|
||||||
.route("/echo", post(echo_handler))
|
.route("/echo", post(echo_handler))
|
||||||
|
.merge(projects::projects_router())
|
||||||
|
.merge(users::users_router())
|
||||||
.layer(Extension(pool))
|
.layer(Extension(pool))
|
||||||
.layer(CorsLayer::permissive());
|
.layer(CorsLayer::permissive());
|
||||||
|
|
||||||
@@ -75,3 +84,57 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn create_admin_account(pool: &sqlx::PgPool) -> anyhow::Result<()> {
|
||||||
|
use chrono::Utc;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
let admin_email = "admin@example.com";
|
||||||
|
let admin_password = env::var("ADMIN_PASSWORD")
|
||||||
|
.unwrap_or_else(|_| "admin123".to_string());
|
||||||
|
|
||||||
|
// Check if admin already exists
|
||||||
|
let existing_admin = sqlx::query!(
|
||||||
|
"SELECT id, password_hash FROM users WHERE email = $1",
|
||||||
|
admin_email
|
||||||
|
)
|
||||||
|
.fetch_optional(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let password_hash = hash_password(&admin_password)?;
|
||||||
|
|
||||||
|
if let Some(admin) = existing_admin {
|
||||||
|
// Update existing admin password
|
||||||
|
let now = Utc::now();
|
||||||
|
sqlx::query!(
|
||||||
|
"UPDATE users SET password_hash = $2, is_admin = $3, updated_at = $4 WHERE id = $1",
|
||||||
|
admin.id,
|
||||||
|
password_hash,
|
||||||
|
true,
|
||||||
|
now
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("Updated admin account");
|
||||||
|
} else {
|
||||||
|
// Create new admin account
|
||||||
|
let id = Uuid::new_v4();
|
||||||
|
let now = Utc::now();
|
||||||
|
sqlx::query!(
|
||||||
|
"INSERT INTO users (id, email, password_hash, is_admin, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6)",
|
||||||
|
id,
|
||||||
|
admin_email,
|
||||||
|
password_hash,
|
||||||
|
true,
|
||||||
|
now,
|
||||||
|
now
|
||||||
|
)
|
||||||
|
.execute(pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
tracing::info!("Created admin account: {}", admin_email);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ use uuid::Uuid;
|
|||||||
pub struct User {
|
pub struct User {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub password: String, // This should be hashed
|
#[serde(skip_serializing)]
|
||||||
|
pub password_hash: String, // Hashed password
|
||||||
|
pub is_admin: bool,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
@@ -16,10 +18,45 @@ pub struct User {
|
|||||||
pub struct CreateUser {
|
pub struct CreateUser {
|
||||||
pub email: String,
|
pub email: String,
|
||||||
pub password: String,
|
pub password: String,
|
||||||
|
pub is_admin: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub struct UpdateUser {
|
pub struct UpdateUser {
|
||||||
pub email: Option<String>,
|
pub email: Option<String>,
|
||||||
pub password: Option<String>,
|
pub password: Option<String>,
|
||||||
|
pub is_admin: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
pub struct LoginRequest {
|
||||||
|
pub email: String,
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct LoginResponse {
|
||||||
|
pub user: UserResponse,
|
||||||
|
pub token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
|
pub struct UserResponse {
|
||||||
|
pub id: Uuid,
|
||||||
|
pub email: String,
|
||||||
|
pub is_admin: bool,
|
||||||
|
pub created_at: DateTime<Utc>,
|
||||||
|
pub updated_at: DateTime<Utc>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<User> for UserResponse {
|
||||||
|
fn from(user: User) -> Self {
|
||||||
|
Self {
|
||||||
|
id: user.id,
|
||||||
|
email: user.email,
|
||||||
|
is_admin: user.is_admin,
|
||||||
|
created_at: user.created_at,
|
||||||
|
updated_at: user.updated_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,3 @@
|
|||||||
pub mod health;
|
pub mod health;
|
||||||
|
pub mod projects;
|
||||||
|
pub mod users;
|
||||||
|
|||||||
171
backend/src/routes/projects.rs
Normal file
171
backend/src/routes/projects.rs
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
use axum::{
|
||||||
|
routing::{get, post, put, delete},
|
||||||
|
Router,
|
||||||
|
Json,
|
||||||
|
response::Json as ResponseJson,
|
||||||
|
extract::{Path, Extension},
|
||||||
|
http::StatusCode,
|
||||||
|
};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
use crate::models::{ApiResponse, project::{Project, CreateProject, UpdateProject}};
|
||||||
|
|
||||||
|
pub async fn get_projects(Extension(pool): Extension<PgPool>) -> Result<ResponseJson<ApiResponse<Vec<Project>>>, StatusCode> {
|
||||||
|
match sqlx::query_as!(
|
||||||
|
Project,
|
||||||
|
"SELECT id, name, owner_id, created_at, updated_at FROM projects ORDER BY created_at DESC"
|
||||||
|
)
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(projects) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(projects),
|
||||||
|
message: None,
|
||||||
|
})),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to fetch projects: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_project(
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
Extension(pool): Extension<PgPool>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<Project>>, StatusCode> {
|
||||||
|
match sqlx::query_as!(
|
||||||
|
Project,
|
||||||
|
"SELECT id, name, owner_id, created_at, updated_at FROM projects WHERE id = $1",
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(project)) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(project),
|
||||||
|
message: None,
|
||||||
|
})),
|
||||||
|
Ok(None) => Err(StatusCode::NOT_FOUND),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to fetch project: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_project(
|
||||||
|
Extension(pool): Extension<PgPool>,
|
||||||
|
Json(payload): Json<CreateProject>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<Project>>, StatusCode> {
|
||||||
|
let id = Uuid::new_v4();
|
||||||
|
let now = Utc::now();
|
||||||
|
|
||||||
|
match sqlx::query_as!(
|
||||||
|
Project,
|
||||||
|
"INSERT INTO projects (id, name, owner_id, created_at, updated_at) VALUES ($1, $2, $3, $4, $5) RETURNING id, name, owner_id, created_at, updated_at",
|
||||||
|
id,
|
||||||
|
payload.name,
|
||||||
|
payload.owner_id,
|
||||||
|
now,
|
||||||
|
now
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(project) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(project),
|
||||||
|
message: Some("Project created successfully".to_string()),
|
||||||
|
})),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to create project: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_project(
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
Extension(pool): Extension<PgPool>,
|
||||||
|
Json(payload): Json<UpdateProject>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<Project>>, StatusCode> {
|
||||||
|
let now = Utc::now();
|
||||||
|
|
||||||
|
// Check if project exists first
|
||||||
|
let existing_project = sqlx::query_as!(
|
||||||
|
Project,
|
||||||
|
"SELECT id, name, owner_id, created_at, updated_at FROM projects WHERE id = $1",
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let existing_project = match existing_project {
|
||||||
|
Ok(Some(project)) => project,
|
||||||
|
Ok(None) => return Err(StatusCode::NOT_FOUND),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to check project existence: {}", e);
|
||||||
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Use existing name if not provided in update
|
||||||
|
let name = payload.name.unwrap_or(existing_project.name);
|
||||||
|
|
||||||
|
match sqlx::query_as!(
|
||||||
|
Project,
|
||||||
|
"UPDATE projects SET name = $2, updated_at = $3 WHERE id = $1 RETURNING id, name, owner_id, created_at, updated_at",
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
now
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(project) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(project),
|
||||||
|
message: Some("Project updated successfully".to_string()),
|
||||||
|
})),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to update project: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_project(
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
Extension(pool): Extension<PgPool>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<()>>, StatusCode> {
|
||||||
|
match sqlx::query!("DELETE FROM projects WHERE id = $1", id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(result) => {
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
Err(StatusCode::NOT_FOUND)
|
||||||
|
} else {
|
||||||
|
Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: None,
|
||||||
|
message: Some("Project deleted successfully".to_string()),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to delete project: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn projects_router() -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/projects", get(get_projects).post(create_project))
|
||||||
|
.route("/projects/:id", get(get_project).put(update_project).delete(delete_project))
|
||||||
|
}
|
||||||
301
backend/src/routes/users.rs
Normal file
301
backend/src/routes/users.rs
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
use axum::{
|
||||||
|
routing::{get, post, put, delete},
|
||||||
|
Router,
|
||||||
|
Json,
|
||||||
|
response::Json as ResponseJson,
|
||||||
|
extract::{Path, Extension},
|
||||||
|
http::StatusCode,
|
||||||
|
};
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
use chrono::Utc;
|
||||||
|
|
||||||
|
use crate::models::{ApiResponse, user::{User, CreateUser, UpdateUser, LoginRequest, LoginResponse, UserResponse}};
|
||||||
|
use crate::auth::{AuthUser, create_token, hash_password, verify_password};
|
||||||
|
|
||||||
|
pub async fn login(
|
||||||
|
Extension(pool): Extension<PgPool>,
|
||||||
|
Json(payload): Json<LoginRequest>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<LoginResponse>>, StatusCode> {
|
||||||
|
match sqlx::query_as!(
|
||||||
|
User,
|
||||||
|
"SELECT id, email, password_hash, is_admin, created_at, updated_at FROM users WHERE email = $1",
|
||||||
|
payload.email
|
||||||
|
)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(user)) => {
|
||||||
|
match verify_password(&payload.password, &user.password_hash) {
|
||||||
|
Ok(true) => {
|
||||||
|
match create_token(user.id, user.email.clone(), user.is_admin) {
|
||||||
|
Ok(token) => {
|
||||||
|
Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(LoginResponse {
|
||||||
|
user: user.into(),
|
||||||
|
token,
|
||||||
|
}),
|
||||||
|
message: Some("Login successful".to_string()),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to create token: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(false) => Err(StatusCode::UNAUTHORIZED),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Password verification error: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(None) => Err(StatusCode::UNAUTHORIZED),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to fetch user: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_users(
|
||||||
|
_auth: AuthUser,
|
||||||
|
Extension(pool): Extension<PgPool>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<Vec<UserResponse>>>, StatusCode> {
|
||||||
|
match sqlx::query_as!(
|
||||||
|
User,
|
||||||
|
"SELECT id, email, password_hash, is_admin, created_at, updated_at FROM users ORDER BY created_at DESC"
|
||||||
|
)
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(users) => {
|
||||||
|
let user_responses: Vec<UserResponse> = users.into_iter().map(|u| u.into()).collect();
|
||||||
|
Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(user_responses),
|
||||||
|
message: None,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to fetch users: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_user(
|
||||||
|
auth: AuthUser,
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
Extension(pool): Extension<PgPool>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<UserResponse>>, StatusCode> {
|
||||||
|
// Users can only view their own profile unless they're admin
|
||||||
|
if auth.user_id != id && !auth.is_admin {
|
||||||
|
return Err(StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
match sqlx::query_as!(
|
||||||
|
User,
|
||||||
|
"SELECT id, email, password_hash, is_admin, created_at, updated_at FROM users WHERE id = $1",
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(user)) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(user.into()),
|
||||||
|
message: None,
|
||||||
|
})),
|
||||||
|
Ok(None) => Err(StatusCode::NOT_FOUND),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to fetch user: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create_user(
|
||||||
|
auth: AuthUser,
|
||||||
|
Extension(pool): Extension<PgPool>,
|
||||||
|
Json(payload): Json<CreateUser>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<UserResponse>>, StatusCode> {
|
||||||
|
// Only admins can create users
|
||||||
|
if !auth.is_admin {
|
||||||
|
return Err(StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = Uuid::new_v4();
|
||||||
|
let now = Utc::now();
|
||||||
|
let is_admin = payload.is_admin.unwrap_or(false);
|
||||||
|
|
||||||
|
let password_hash = match hash_password(&payload.password) {
|
||||||
|
Ok(hash) => hash,
|
||||||
|
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||||
|
};
|
||||||
|
|
||||||
|
match sqlx::query_as!(
|
||||||
|
User,
|
||||||
|
"INSERT INTO users (id, email, password_hash, is_admin, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id, email, password_hash, is_admin, created_at, updated_at",
|
||||||
|
id,
|
||||||
|
payload.email,
|
||||||
|
password_hash,
|
||||||
|
is_admin,
|
||||||
|
now,
|
||||||
|
now
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(user) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(user.into()),
|
||||||
|
message: Some("User created successfully".to_string()),
|
||||||
|
})),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to create user: {}", e);
|
||||||
|
if e.to_string().contains("users_email_key") {
|
||||||
|
Err(StatusCode::CONFLICT) // Email already exists
|
||||||
|
} else {
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn update_user(
|
||||||
|
auth: AuthUser,
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
Extension(pool): Extension<PgPool>,
|
||||||
|
Json(payload): Json<UpdateUser>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<UserResponse>>, StatusCode> {
|
||||||
|
// Users can only update their own profile unless they're admin
|
||||||
|
if auth.user_id != id && !auth.is_admin {
|
||||||
|
return Err(StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = Utc::now();
|
||||||
|
|
||||||
|
// Get existing user
|
||||||
|
let existing_user = match sqlx::query_as!(
|
||||||
|
User,
|
||||||
|
"SELECT id, email, password_hash, is_admin, created_at, updated_at FROM users WHERE id = $1",
|
||||||
|
id
|
||||||
|
)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(user)) => user,
|
||||||
|
Ok(None) => return Err(StatusCode::NOT_FOUND),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to check user existence: {}", e);
|
||||||
|
return Err(StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let email = payload.email.unwrap_or(existing_user.email);
|
||||||
|
let is_admin = if auth.is_admin {
|
||||||
|
payload.is_admin.unwrap_or(existing_user.is_admin)
|
||||||
|
} else {
|
||||||
|
existing_user.is_admin // Non-admins can't change admin status
|
||||||
|
};
|
||||||
|
|
||||||
|
let password_hash = if let Some(new_password) = payload.password {
|
||||||
|
match hash_password(&new_password) {
|
||||||
|
Ok(hash) => hash,
|
||||||
|
Err(_) => return Err(StatusCode::INTERNAL_SERVER_ERROR),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
existing_user.password_hash
|
||||||
|
};
|
||||||
|
|
||||||
|
match sqlx::query_as!(
|
||||||
|
User,
|
||||||
|
"UPDATE users SET email = $2, password_hash = $3, is_admin = $4, updated_at = $5 WHERE id = $1 RETURNING id, email, password_hash, is_admin, created_at, updated_at",
|
||||||
|
id,
|
||||||
|
email,
|
||||||
|
password_hash,
|
||||||
|
is_admin,
|
||||||
|
now
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(user) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(user.into()),
|
||||||
|
message: Some("User updated successfully".to_string()),
|
||||||
|
})),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to update user: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn delete_user(
|
||||||
|
auth: AuthUser,
|
||||||
|
Path(id): Path<Uuid>,
|
||||||
|
Extension(pool): Extension<PgPool>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<()>>, StatusCode> {
|
||||||
|
// Only admins can delete users, and they can't delete themselves
|
||||||
|
if !auth.is_admin || auth.user_id == id {
|
||||||
|
return Err(StatusCode::FORBIDDEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
match sqlx::query!("DELETE FROM users WHERE id = $1", id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(result) => {
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
Err(StatusCode::NOT_FOUND)
|
||||||
|
} else {
|
||||||
|
Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: None,
|
||||||
|
message: Some("User deleted successfully".to_string()),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to delete user: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_current_user(
|
||||||
|
auth: AuthUser,
|
||||||
|
Extension(pool): Extension<PgPool>
|
||||||
|
) -> Result<ResponseJson<ApiResponse<UserResponse>>, StatusCode> {
|
||||||
|
match sqlx::query_as!(
|
||||||
|
User,
|
||||||
|
"SELECT id, email, password_hash, is_admin, created_at, updated_at FROM users WHERE id = $1",
|
||||||
|
auth.user_id
|
||||||
|
)
|
||||||
|
.fetch_optional(&pool)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Some(user)) => Ok(ResponseJson(ApiResponse {
|
||||||
|
success: true,
|
||||||
|
data: Some(user.into()),
|
||||||
|
message: None,
|
||||||
|
})),
|
||||||
|
Ok(None) => Err(StatusCode::NOT_FOUND),
|
||||||
|
Err(e) => {
|
||||||
|
tracing::error!("Failed to fetch current user: {}", e);
|
||||||
|
Err(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn users_router() -> Router {
|
||||||
|
Router::new()
|
||||||
|
.route("/auth/login", post(login))
|
||||||
|
.route("/auth/me", get(get_current_user))
|
||||||
|
.route("/users", get(get_users).post(create_user))
|
||||||
|
.route("/users/:id", get(get_user).put(update_user).delete(delete_user))
|
||||||
|
}
|
||||||
75
frontend/package-lock.json
generated
75
frontend/package-lock.json
generated
@@ -8,7 +8,9 @@
|
|||||||
"name": "bloop-frontend",
|
"name": "bloop-frontend",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@radix-ui/react-slot": "^1.0.2",
|
"@radix-ui/react-label": "^2.1.7",
|
||||||
|
"@radix-ui/react-separator": "^1.1.7",
|
||||||
|
"@radix-ui/react-slot": "^1.2.3",
|
||||||
"class-variance-authority": "^0.7.0",
|
"class-variance-authority": "^0.7.0",
|
||||||
"clsx": "^2.0.0",
|
"clsx": "^2.0.0",
|
||||||
"lucide-react": "^0.303.0",
|
"lucide-react": "^0.303.0",
|
||||||
@@ -1060,6 +1062,75 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@radix-ui/react-label": {
|
||||||
|
"version": "2.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-label/-/react-label-2.1.7.tgz",
|
||||||
|
"integrity": "sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-primitive": "2.1.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-primitive": {
|
||||||
|
"version": "2.1.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",
|
||||||
|
"integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-slot": "1.2.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@radix-ui/react-separator": {
|
||||||
|
"version": "1.1.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.7.tgz",
|
||||||
|
"integrity": "sha512-0HEb8R9E8A+jZjvmFCy/J4xhbXy3TV+9XSnGJ3KvTtjlIUy/YQ/p6UYZvi7YbeoeXdyU9+Y3scizK6hkY37baA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@radix-ui/react-primitive": "2.1.3"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": "*",
|
||||||
|
"@types/react-dom": "*",
|
||||||
|
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
|
||||||
|
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"@types/react-dom": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@radix-ui/react-slot": {
|
"node_modules/@radix-ui/react-slot": {
|
||||||
"version": "1.2.3",
|
"version": "1.2.3",
|
||||||
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
|
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
|
||||||
@@ -1455,7 +1526,7 @@
|
|||||||
"version": "18.3.7",
|
"version": "18.3.7",
|
||||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
|
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",
|
||||||
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
|
||||||
"dev": true,
|
"devOptional": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/react": "^18.0.0"
|
"@types/react": "^18.0.0"
|
||||||
|
|||||||
@@ -10,7 +10,9 @@
|
|||||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0"
|
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@radix-ui/react-slot": "^1.0.2",
|
"@radix-ui/react-label": "^2.1.7",
|
||||||
|
"@radix-ui/react-separator": "^1.1.7",
|
||||||
|
"@radix-ui/react-slot": "^1.2.3",
|
||||||
"class-variance-authority": "^0.7.0",
|
"class-variance-authority": "^0.7.0",
|
||||||
"clsx": "^2.0.0",
|
"clsx": "^2.0.0",
|
||||||
"lucide-react": "^0.303.0",
|
"lucide-react": "^0.303.0",
|
||||||
|
|||||||
@@ -1,25 +1,48 @@
|
|||||||
import { useState, useEffect } from 'react'
|
import { useState, useEffect } from 'react'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
interface ApiResponse<T> {
|
import { ProjectsPage } from '@/components/projects/projects-page'
|
||||||
success: boolean
|
import { UsersPage } from '@/components/users/users-page'
|
||||||
data?: T
|
import { LoginForm } from '@/components/auth/login-form'
|
||||||
message?: string
|
import { ApiResponse } from 'shared/types'
|
||||||
}
|
import { authStorage, isAuthenticated, logout, makeAuthenticatedRequest } from '@/lib/auth'
|
||||||
|
import { ArrowLeft, Heart, Activity, FolderOpen, Users, CheckCircle, AlertCircle, LogOut } from 'lucide-react'
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
|
const [currentPage, setCurrentPage] = useState<'home' | 'projects' | 'users'>('home')
|
||||||
const [message, setMessage] = useState<string>('')
|
const [message, setMessage] = useState<string>('')
|
||||||
|
const [messageType, setMessageType] = useState<'success' | 'error'>('success')
|
||||||
const [loading, setLoading] = useState(false)
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [authenticated, setAuthenticated] = useState(false)
|
||||||
|
|
||||||
|
const currentUser = authStorage.getUser()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setAuthenticated(isAuthenticated())
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
const handleLogin = () => {
|
||||||
|
setAuthenticated(true)
|
||||||
|
setCurrentPage('home')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
logout()
|
||||||
|
setAuthenticated(false)
|
||||||
|
setCurrentPage('home')
|
||||||
|
}
|
||||||
|
|
||||||
const fetchHello = async () => {
|
const fetchHello = async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/hello?name=Bloop')
|
const response = await makeAuthenticatedRequest('/api/hello?name=Bloop')
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
setMessage(data.message)
|
setMessage(data.message)
|
||||||
|
setMessageType('success')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setMessage('Error connecting to backend')
|
setMessage('Error connecting to backend')
|
||||||
|
setMessageType('error')
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
@@ -28,42 +51,240 @@ function App() {
|
|||||||
const checkHealth = async () => {
|
const checkHealth = async () => {
|
||||||
setLoading(true)
|
setLoading(true)
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/health')
|
const response = await makeAuthenticatedRequest('/api/health')
|
||||||
const data: ApiResponse<string> = await response.json()
|
const data: ApiResponse<string> = await response.json()
|
||||||
setMessage(data.message || 'Health check completed')
|
setMessage(data.message || 'Health check completed')
|
||||||
|
setMessageType('success')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setMessage('Backend health check failed')
|
setMessage('Backend health check failed')
|
||||||
|
setMessageType('error')
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
if (!authenticated) {
|
||||||
<div className="min-h-screen bg-background p-8">
|
return <LoginForm onSuccess={handleLogin} />
|
||||||
<div className="max-w-2xl mx-auto">
|
}
|
||||||
<Card>
|
|
||||||
<CardHeader>
|
if (currentPage === 'projects' || currentPage === 'users') {
|
||||||
<CardTitle>Welcome to Bloop</CardTitle>
|
return (
|
||||||
<CardDescription>
|
<div className="min-h-screen bg-background">
|
||||||
A full-stack monorepo with Rust backend and React frontend
|
<div className="border-b">
|
||||||
</CardDescription>
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
|
||||||
</CardHeader>
|
<div className="flex items-center justify-between h-16">
|
||||||
<CardContent className="space-y-4">
|
<div className="flex items-center space-x-6">
|
||||||
<div className="flex gap-4">
|
<h2 className="text-lg font-semibold">Bloop</h2>
|
||||||
<Button onClick={fetchHello} disabled={loading}>
|
<div className="flex items-center space-x-1">
|
||||||
Say Hello
|
<Button
|
||||||
</Button>
|
variant={currentPage === 'projects' ? 'default' : 'ghost'}
|
||||||
<Button onClick={checkHealth} variant="outline" disabled={loading}>
|
size="sm"
|
||||||
Check Health
|
onClick={() => setCurrentPage('projects')}
|
||||||
</Button>
|
>
|
||||||
</div>
|
<FolderOpen className="mr-2 h-4 w-4" />
|
||||||
{message && (
|
Projects
|
||||||
<div className="p-4 bg-muted rounded-md">
|
</Button>
|
||||||
<p className="text-sm">{message}</p>
|
{currentUser?.is_admin && (
|
||||||
|
<Button
|
||||||
|
variant={currentPage === 'users' ? 'default' : 'ghost'}
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setCurrentPage('users')}
|
||||||
|
>
|
||||||
|
<Users className="mr-2 h-4 w-4" />
|
||||||
|
Users
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<div className="text-sm text-muted-foreground">
|
||||||
|
Welcome, {currentUser?.email}
|
||||||
|
</div>
|
||||||
|
<Button variant="ghost" onClick={() => setCurrentPage('home')}>
|
||||||
|
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||||
|
Home
|
||||||
|
</Button>
|
||||||
|
<Button variant="ghost" onClick={handleLogout}>
|
||||||
|
<LogOut className="mr-2 h-4 w-4" />
|
||||||
|
Logout
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="max-w-7xl mx-auto p-6 sm:p-8">
|
||||||
|
{currentPage === 'projects' ? <ProjectsPage /> : <UsersPage />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gradient-to-br from-background to-muted/20">
|
||||||
|
<div className="container mx-auto px-4 py-12">
|
||||||
|
<div className="max-w-4xl mx-auto">
|
||||||
|
<div className="text-center mb-12">
|
||||||
|
<div className="flex items-center justify-center mb-6">
|
||||||
|
<div className="rounded-full bg-primary/10 p-4">
|
||||||
|
<Heart className="h-8 w-8 text-primary" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<h1 className="text-4xl font-bold tracking-tight mb-4">
|
||||||
|
Welcome to Bloop
|
||||||
|
</h1>
|
||||||
|
<p className="text-xl text-muted-foreground max-w-2xl mx-auto">
|
||||||
|
A modern full-stack monorepo built with Rust backend and React frontend.
|
||||||
|
Get started by exploring our features below.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3 mb-8">
|
||||||
|
<Card className="hover:shadow-md transition-shadow">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="rounded-lg bg-blue-100 p-2 mr-3">
|
||||||
|
<Heart className="h-5 w-5 text-blue-600" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-lg">API Test</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Test the connection between frontend and backend
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={fetchHello}
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<Heart className="mr-2 h-4 w-4" />
|
||||||
|
Say Hello
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card className="hover:shadow-md transition-shadow">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="rounded-lg bg-green-100 p-2 mr-3">
|
||||||
|
<Activity className="h-5 w-5 text-green-600" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-lg">Health Check</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Monitor the health status of your backend services
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={checkHealth}
|
||||||
|
variant="outline"
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<Activity className="mr-2 h-4 w-4" />
|
||||||
|
Check Health
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card className="hover:shadow-md transition-shadow">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="rounded-lg bg-purple-100 p-2 mr-3">
|
||||||
|
<FolderOpen className="h-5 w-5 text-purple-600" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-lg">Projects</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Manage your projects with full CRUD operations
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={() => setCurrentPage('projects')}
|
||||||
|
className="w-full"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<FolderOpen className="mr-2 h-4 w-4" />
|
||||||
|
View Projects
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
{currentUser?.is_admin && (
|
||||||
|
<Card className="hover:shadow-md transition-shadow">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="rounded-lg bg-orange-100 p-2 mr-3">
|
||||||
|
<Users className="h-5 w-5 text-orange-600" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-lg">Users</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Manage user accounts and permissions
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={() => setCurrentPage('users')}
|
||||||
|
className="w-full"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<Users className="mr-2 h-4 w-4" />
|
||||||
|
Manage Users
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
)}
|
)}
|
||||||
</CardContent>
|
|
||||||
</Card>
|
<Card className="hover:shadow-md transition-shadow">
|
||||||
|
<CardHeader>
|
||||||
|
<div className="flex items-center">
|
||||||
|
<div className="rounded-lg bg-red-100 p-2 mr-3">
|
||||||
|
<LogOut className="h-5 w-5 text-red-600" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-lg">Account</CardTitle>
|
||||||
|
</div>
|
||||||
|
<CardDescription>
|
||||||
|
Logged in as {currentUser?.email}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<Button
|
||||||
|
onClick={handleLogout}
|
||||||
|
variant="outline"
|
||||||
|
className="w-full"
|
||||||
|
size="sm"
|
||||||
|
>
|
||||||
|
<LogOut className="mr-2 h-4 w-4" />
|
||||||
|
Logout
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<Alert variant={messageType === 'error' ? 'destructive' : 'default'} className="max-w-2xl mx-auto">
|
||||||
|
{messageType === 'error' ? (
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<CheckCircle className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
<AlertDescription>
|
||||||
|
{message}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-12 text-center">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Built with ❤️ using Rust, React, TypeScript, and Tailwind CSS
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
118
frontend/src/components/auth/login-form.tsx
Normal file
118
frontend/src/components/auth/login-form.tsx
Normal file
@@ -0,0 +1,118 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { LoginRequest, LoginResponse, ApiResponse } from 'shared/types'
|
||||||
|
import { authStorage } from '@/lib/auth'
|
||||||
|
import { LogIn, AlertCircle } from 'lucide-react'
|
||||||
|
|
||||||
|
interface LoginFormProps {
|
||||||
|
onSuccess: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LoginForm({ onSuccess }: LoginFormProps) {
|
||||||
|
const [email, setEmail] = useState('')
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const loginData: LoginRequest = { email, password }
|
||||||
|
const response = await fetch('/api/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(loginData),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 401) {
|
||||||
|
throw new Error('Invalid email or password')
|
||||||
|
}
|
||||||
|
throw new Error('Login failed')
|
||||||
|
}
|
||||||
|
|
||||||
|
const data: ApiResponse<LoginResponse> = await response.json()
|
||||||
|
|
||||||
|
if (data.success && data.data) {
|
||||||
|
authStorage.setToken(data.data.token)
|
||||||
|
authStorage.setUser(data.data.user)
|
||||||
|
onSuccess()
|
||||||
|
} else {
|
||||||
|
throw new Error('Login failed')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
setError(error instanceof Error ? error.message : 'An error occurred')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-background to-muted/20">
|
||||||
|
<Card className="w-full max-w-md">
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
|
||||||
|
<LogIn className="h-6 w-6 text-primary" />
|
||||||
|
</div>
|
||||||
|
<CardTitle className="text-2xl">Welcome back</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Sign in to your account to continue
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="Enter your email"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">Password</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
placeholder="Enter your password"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
{error}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Button type="submit" className="w-full" disabled={loading}>
|
||||||
|
{loading ? 'Signing in...' : 'Sign in'}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div className="mt-6 text-center text-sm text-muted-foreground">
|
||||||
|
<p>Default admin credentials:</p>
|
||||||
|
<p>Email: admin@example.com</p>
|
||||||
|
<p>Password: Check your ADMIN_PASSWORD env var</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
211
frontend/src/components/projects/project-detail.tsx
Normal file
211
frontend/src/components/projects/project-detail.tsx
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Project, ApiResponse } from 'shared/types'
|
||||||
|
import { ProjectForm } from './project-form'
|
||||||
|
import { ArrowLeft, Edit, Trash2, Calendar, Clock, User, AlertCircle, Loader2 } from 'lucide-react'
|
||||||
|
|
||||||
|
interface ProjectDetailProps {
|
||||||
|
projectId: string
|
||||||
|
onBack: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectDetail({ projectId, onBack }: ProjectDetailProps) {
|
||||||
|
const [project, setProject] = useState<Project | null>(null)
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [showEditForm, setShowEditForm] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
const fetchProject = async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/projects/${projectId}`)
|
||||||
|
const data: ApiResponse<Project> = await response.json()
|
||||||
|
if (data.success && data.data) {
|
||||||
|
setProject(data.data)
|
||||||
|
} else {
|
||||||
|
setError('Project not found')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch project:', error)
|
||||||
|
setError('Failed to load project')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async () => {
|
||||||
|
if (!project) return
|
||||||
|
if (!confirm(`Are you sure you want to delete "${project.name}"? This action cannot be undone.`)) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/projects/${projectId}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
if (response.ok) {
|
||||||
|
onBack()
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete project:', error)
|
||||||
|
setError('Failed to delete project')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEditSuccess = () => {
|
||||||
|
setShowEditForm(false)
|
||||||
|
fetchProject()
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchProject()
|
||||||
|
}, [projectId])
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
Loading project...
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !project) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<Button variant="outline" onClick={onBack}>
|
||||||
|
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||||
|
Back to Projects
|
||||||
|
</Button>
|
||||||
|
<Card>
|
||||||
|
<CardContent className="py-12 text-center">
|
||||||
|
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-lg bg-muted">
|
||||||
|
<AlertCircle className="h-6 w-6 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<h3 className="mt-4 text-lg font-semibold">Project not found</h3>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
{error || 'The project you\'re looking for doesn\'t exist or has been deleted.'}
|
||||||
|
</p>
|
||||||
|
<Button className="mt-4" onClick={onBack}>
|
||||||
|
Back to Projects
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex justify-between items-start">
|
||||||
|
<div className="flex items-center space-x-4">
|
||||||
|
<Button variant="outline" onClick={onBack}>
|
||||||
|
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||||
|
Back to Projects
|
||||||
|
</Button>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold">{project.name}</h1>
|
||||||
|
<p className="text-sm text-muted-foreground">Project details and settings</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button variant="outline" onClick={() => setShowEditForm(true)}>
|
||||||
|
<Edit className="mr-2 h-4 w-4" />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleDelete}
|
||||||
|
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
{error}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle className="flex items-center">
|
||||||
|
<Calendar className="mr-2 h-5 w-5" />
|
||||||
|
Project Information
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="text-sm font-medium text-muted-foreground">Status</span>
|
||||||
|
<Badge variant="secondary">Active</Badge>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center text-sm">
|
||||||
|
<Calendar className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<span className="text-muted-foreground">Created:</span>
|
||||||
|
<span className="ml-2">{new Date(project.created_at).toLocaleDateString()}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-sm">
|
||||||
|
<Clock className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<span className="text-muted-foreground">Last Updated:</span>
|
||||||
|
<span className="ml-2">{new Date(project.updated_at).toLocaleDateString()}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center text-sm">
|
||||||
|
<User className="mr-2 h-4 w-4 text-muted-foreground" />
|
||||||
|
<span className="text-muted-foreground">Owner ID:</span>
|
||||||
|
<code className="ml-2 text-xs bg-muted px-1 py-0.5 rounded">
|
||||||
|
{project.owner_id.substring(0, 8)}...
|
||||||
|
</code>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Project Details</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Technical information about this project
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-medium text-muted-foreground">Project ID</h4>
|
||||||
|
<code className="mt-1 block text-xs bg-muted p-2 rounded font-mono">
|
||||||
|
{project.id}
|
||||||
|
</code>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-medium text-muted-foreground">Created At</h4>
|
||||||
|
<p className="mt-1 text-sm">
|
||||||
|
{new Date(project.created_at).toLocaleString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-medium text-muted-foreground">Last Modified</h4>
|
||||||
|
<p className="mt-1 text-sm">
|
||||||
|
{new Date(project.updated_at).toLocaleString()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ProjectForm
|
||||||
|
open={showEditForm}
|
||||||
|
onClose={() => setShowEditForm(false)}
|
||||||
|
onSuccess={handleEditSuccess}
|
||||||
|
project={project}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
127
frontend/src/components/projects/project-form.tsx
Normal file
127
frontend/src/components/projects/project-form.tsx
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
|
import { Project, CreateProject, UpdateProject } from 'shared/types'
|
||||||
|
import { AlertCircle } from 'lucide-react'
|
||||||
|
|
||||||
|
interface ProjectFormProps {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onSuccess: () => void
|
||||||
|
project?: Project | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ProjectForm({ open, onClose, onSuccess, project }: ProjectFormProps) {
|
||||||
|
const [name, setName] = useState(project?.name || '')
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
const isEditing = !!project
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isEditing) {
|
||||||
|
const updateData: UpdateProject = { name }
|
||||||
|
const response = await fetch(`/api/projects/${project.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(updateData),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to update project')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// For now, using a placeholder owner_id - this should come from auth
|
||||||
|
const createData: CreateProject = {
|
||||||
|
name,
|
||||||
|
owner_id: '00000000-0000-0000-0000-000000000000'
|
||||||
|
}
|
||||||
|
const response = await fetch('/api/projects', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(createData),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to create project')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onSuccess()
|
||||||
|
setName('')
|
||||||
|
} catch (error) {
|
||||||
|
setError(error instanceof Error ? error.message : 'An error occurred')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
setName(project?.name || '')
|
||||||
|
setError('')
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleClose}>
|
||||||
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
{isEditing ? 'Edit Project' : 'Create New Project'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{isEditing
|
||||||
|
? 'Make changes to your project here. Click save when you\'re done.'
|
||||||
|
: 'Add a new project to your workspace. You can always edit it later.'
|
||||||
|
}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="name">Project Name</Label>
|
||||||
|
<Input
|
||||||
|
id="name"
|
||||||
|
type="text"
|
||||||
|
value={name}
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
placeholder="Enter project name"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
{error}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleClose}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={loading || !name.trim()}>
|
||||||
|
{loading ? 'Saving...' : isEditing ? 'Save Changes' : 'Create Project'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
169
frontend/src/components/projects/project-list.tsx
Normal file
169
frontend/src/components/projects/project-list.tsx
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Project, ApiResponse } from 'shared/types'
|
||||||
|
import { ProjectForm } from './project-form'
|
||||||
|
import { Plus, Edit, Trash2, Calendar, AlertCircle, Loader2 } from 'lucide-react'
|
||||||
|
|
||||||
|
export function ProjectList() {
|
||||||
|
const [projects, setProjects] = useState<Project[]>([])
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [showForm, setShowForm] = useState(false)
|
||||||
|
const [editingProject, setEditingProject] = useState<Project | null>(null)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
const fetchProjects = async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/projects')
|
||||||
|
const data: ApiResponse<Project[]> = await response.json()
|
||||||
|
if (data.success && data.data) {
|
||||||
|
setProjects(data.data)
|
||||||
|
} else {
|
||||||
|
setError('Failed to load projects')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch projects:', error)
|
||||||
|
setError('Failed to connect to server')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (id: string, name: string) => {
|
||||||
|
if (!confirm(`Are you sure you want to delete "${name}"? This action cannot be undone.`)) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/projects/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
if (response.ok) {
|
||||||
|
fetchProjects()
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete project:', error)
|
||||||
|
setError('Failed to delete project')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEdit = (project: Project) => {
|
||||||
|
setEditingProject(project)
|
||||||
|
setShowForm(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFormSuccess = () => {
|
||||||
|
setShowForm(false)
|
||||||
|
setEditingProject(null)
|
||||||
|
fetchProjects()
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchProjects()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Projects</h1>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Manage your projects and track their progress
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button onClick={() => setShowForm(true)}>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Create Project
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
{error}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
Loading projects...
|
||||||
|
</div>
|
||||||
|
) : projects.length === 0 ? (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="py-12 text-center">
|
||||||
|
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-lg bg-muted">
|
||||||
|
<Plus className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
<h3 className="mt-4 text-lg font-semibold">No projects yet</h3>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
Get started by creating your first project.
|
||||||
|
</p>
|
||||||
|
<Button
|
||||||
|
className="mt-4"
|
||||||
|
onClick={() => setShowForm(true)}
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Create your first project
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{projects.map((project) => (
|
||||||
|
<Card key={project.id} className="hover:shadow-md transition-shadow">
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<CardTitle className="text-lg">{project.name}</CardTitle>
|
||||||
|
<Badge variant="secondary" className="ml-2">
|
||||||
|
Active
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<CardDescription className="flex items-center">
|
||||||
|
<Calendar className="mr-1 h-3 w-3" />
|
||||||
|
Created {new Date(project.created_at).toLocaleDateString()}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleEdit(project)}
|
||||||
|
className="h-8"
|
||||||
|
>
|
||||||
|
<Edit className="mr-1 h-3 w-3" />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDelete(project.id, project.name)}
|
||||||
|
className="h-8 text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
<Trash2 className="mr-1 h-3 w-3" />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<ProjectForm
|
||||||
|
open={showForm}
|
||||||
|
onClose={() => {
|
||||||
|
setShowForm(false)
|
||||||
|
setEditingProject(null)
|
||||||
|
}}
|
||||||
|
onSuccess={handleFormSuccess}
|
||||||
|
project={editingProject}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
18
frontend/src/components/projects/projects-page.tsx
Normal file
18
frontend/src/components/projects/projects-page.tsx
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { ProjectList } from './project-list'
|
||||||
|
import { ProjectDetail } from './project-detail'
|
||||||
|
|
||||||
|
export function ProjectsPage() {
|
||||||
|
const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null)
|
||||||
|
|
||||||
|
if (selectedProjectId) {
|
||||||
|
return (
|
||||||
|
<ProjectDetail
|
||||||
|
projectId={selectedProjectId}
|
||||||
|
onBack={() => setSelectedProjectId(null)}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return <ProjectList />
|
||||||
|
}
|
||||||
59
frontend/src/components/ui/alert.tsx
Normal file
59
frontend/src/components/ui/alert.tsx
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const alertVariants = cva(
|
||||||
|
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-background text-foreground",
|
||||||
|
destructive:
|
||||||
|
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const Alert = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
|
||||||
|
>(({ className, variant, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
role="alert"
|
||||||
|
className={cn(alertVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
Alert.displayName = "Alert"
|
||||||
|
|
||||||
|
const AlertTitle = React.forwardRef<
|
||||||
|
HTMLParagraphElement,
|
||||||
|
React.HTMLAttributes<HTMLHeadingElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<h5
|
||||||
|
ref={ref}
|
||||||
|
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
AlertTitle.displayName = "AlertTitle"
|
||||||
|
|
||||||
|
const AlertDescription = React.forwardRef<
|
||||||
|
HTMLParagraphElement,
|
||||||
|
React.HTMLAttributes<HTMLParagraphElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={cn("text-sm [&_p]:leading-relaxed", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
AlertDescription.displayName = "AlertDescription"
|
||||||
|
|
||||||
|
export { Alert, AlertTitle, AlertDescription }
|
||||||
36
frontend/src/components/ui/badge.tsx
Normal file
36
frontend/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
|
||||||
|
secondary:
|
||||||
|
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
destructive:
|
||||||
|
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
|
||||||
|
outline: "text-foreground",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
export interface BadgeProps
|
||||||
|
extends React.HTMLAttributes<HTMLDivElement>,
|
||||||
|
VariantProps<typeof badgeVariants> {}
|
||||||
|
|
||||||
|
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||||
|
return (
|
||||||
|
<div className={cn(badgeVariants({ variant }), className)} {...props} />
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants }
|
||||||
113
frontend/src/components/ui/dialog.tsx
Normal file
113
frontend/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { X } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const Dialog = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement> & {
|
||||||
|
open?: boolean
|
||||||
|
onOpenChange?: (open: boolean) => void
|
||||||
|
}
|
||||||
|
>(({ className, open, onOpenChange, children, ...props }, ref) => {
|
||||||
|
if (!open) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 bg-black/50"
|
||||||
|
onClick={() => onOpenChange?.(false)}
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"relative z-50 grid w-full max-w-lg gap-4 border bg-background p-6 shadow-lg duration-200 sm:rounded-lg",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
|
||||||
|
onClick={() => onOpenChange?.(false)}
|
||||||
|
>
|
||||||
|
<X className="h-4 w-4" />
|
||||||
|
<span className="sr-only">Close</span>
|
||||||
|
</button>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})
|
||||||
|
Dialog.displayName = "Dialog"
|
||||||
|
|
||||||
|
const DialogHeader = ({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col space-y-1.5 text-center sm:text-left",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
DialogHeader.displayName = "DialogHeader"
|
||||||
|
|
||||||
|
const DialogTitle = React.forwardRef<
|
||||||
|
HTMLParagraphElement,
|
||||||
|
React.HTMLAttributes<HTMLHeadingElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<h3
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"text-lg font-semibold leading-none tracking-tight",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
DialogTitle.displayName = "DialogTitle"
|
||||||
|
|
||||||
|
const DialogDescription = React.forwardRef<
|
||||||
|
HTMLParagraphElement,
|
||||||
|
React.HTMLAttributes<HTMLParagraphElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<p
|
||||||
|
ref={ref}
|
||||||
|
className={cn("text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
DialogDescription.displayName = "DialogDescription"
|
||||||
|
|
||||||
|
const DialogContent = React.forwardRef<
|
||||||
|
HTMLDivElement,
|
||||||
|
React.HTMLAttributes<HTMLDivElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div ref={ref} className={cn("grid gap-4", className)} {...props} />
|
||||||
|
))
|
||||||
|
DialogContent.displayName = "DialogContent"
|
||||||
|
|
||||||
|
const DialogFooter = ({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.HTMLAttributes<HTMLDivElement>) => (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
DialogFooter.displayName = "DialogFooter"
|
||||||
|
|
||||||
|
export {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
}
|
||||||
25
frontend/src/components/ui/input.tsx
Normal file
25
frontend/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
export interface InputProps
|
||||||
|
extends React.InputHTMLAttributes<HTMLInputElement> {}
|
||||||
|
|
||||||
|
const Input = React.forwardRef<HTMLInputElement, InputProps>(
|
||||||
|
({ className, type, ...props }, ref) => {
|
||||||
|
return (
|
||||||
|
<input
|
||||||
|
type={type}
|
||||||
|
className={cn(
|
||||||
|
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
ref={ref}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
Input.displayName = "Input"
|
||||||
|
|
||||||
|
export { Input }
|
||||||
24
frontend/src/components/ui/label.tsx
Normal file
24
frontend/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const labelVariants = cva(
|
||||||
|
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||||
|
)
|
||||||
|
|
||||||
|
const Label = React.forwardRef<
|
||||||
|
React.ElementRef<typeof LabelPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
|
||||||
|
VariantProps<typeof labelVariants>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<LabelPrimitive.Root
|
||||||
|
ref={ref}
|
||||||
|
className={cn(labelVariants(), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
Label.displayName = LabelPrimitive.Root.displayName
|
||||||
|
|
||||||
|
export { Label }
|
||||||
31
frontend/src/components/ui/separator.tsx
Normal file
31
frontend/src/components/ui/separator.tsx
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import * as React from "react"
|
||||||
|
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const Separator = React.forwardRef<
|
||||||
|
React.ElementRef<typeof SeparatorPrimitive.Root>,
|
||||||
|
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
|
||||||
|
>(
|
||||||
|
(
|
||||||
|
{ className, orientation = "horizontal", decorative = true, ...props },
|
||||||
|
ref
|
||||||
|
) => (
|
||||||
|
<SeparatorPrimitive.Root
|
||||||
|
ref={ref}
|
||||||
|
decorative={decorative}
|
||||||
|
orientation={orientation}
|
||||||
|
className={cn(
|
||||||
|
"shrink-0 bg-border",
|
||||||
|
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
)
|
||||||
|
Separator.displayName = SeparatorPrimitive.Root.displayName
|
||||||
|
|
||||||
|
export { Separator }
|
||||||
117
frontend/src/components/ui/table.tsx
Normal file
117
frontend/src/components/ui/table.tsx
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const Table = React.forwardRef<
|
||||||
|
HTMLTableElement,
|
||||||
|
React.HTMLAttributes<HTMLTableElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<div className="relative w-full overflow-auto">
|
||||||
|
<table
|
||||||
|
ref={ref}
|
||||||
|
className={cn("w-full caption-bottom text-sm", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
Table.displayName = "Table"
|
||||||
|
|
||||||
|
const TableHeader = React.forwardRef<
|
||||||
|
HTMLTableSectionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableSectionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||||
|
))
|
||||||
|
TableHeader.displayName = "TableHeader"
|
||||||
|
|
||||||
|
const TableBody = React.forwardRef<
|
||||||
|
HTMLTableSectionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableSectionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<tbody
|
||||||
|
ref={ref}
|
||||||
|
className={cn("[&_tr:last-child]:border-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableBody.displayName = "TableBody"
|
||||||
|
|
||||||
|
const TableFooter = React.forwardRef<
|
||||||
|
HTMLTableSectionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableSectionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<tfoot
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableFooter.displayName = "TableFooter"
|
||||||
|
|
||||||
|
const TableRow = React.forwardRef<
|
||||||
|
HTMLTableRowElement,
|
||||||
|
React.HTMLAttributes<HTMLTableRowElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<tr
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableRow.displayName = "TableRow"
|
||||||
|
|
||||||
|
const TableHead = React.forwardRef<
|
||||||
|
HTMLTableCellElement,
|
||||||
|
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<th
|
||||||
|
ref={ref}
|
||||||
|
className={cn(
|
||||||
|
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableHead.displayName = "TableHead"
|
||||||
|
|
||||||
|
const TableCell = React.forwardRef<
|
||||||
|
HTMLTableCellElement,
|
||||||
|
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<td
|
||||||
|
ref={ref}
|
||||||
|
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableCell.displayName = "TableCell"
|
||||||
|
|
||||||
|
const TableCaption = React.forwardRef<
|
||||||
|
HTMLTableCaptionElement,
|
||||||
|
React.HTMLAttributes<HTMLTableCaptionElement>
|
||||||
|
>(({ className, ...props }, ref) => (
|
||||||
|
<caption
|
||||||
|
ref={ref}
|
||||||
|
className={cn("mt-4 text-sm text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
TableCaption.displayName = "TableCaption"
|
||||||
|
|
||||||
|
export {
|
||||||
|
Table,
|
||||||
|
TableHeader,
|
||||||
|
TableBody,
|
||||||
|
TableFooter,
|
||||||
|
TableHead,
|
||||||
|
TableRow,
|
||||||
|
TableCell,
|
||||||
|
TableCaption,
|
||||||
|
}
|
||||||
185
frontend/src/components/users/user-form.tsx
Normal file
185
frontend/src/components/users/user-form.tsx
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
import { useState } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
|
import { User, CreateUser, UpdateUser } from 'shared/types'
|
||||||
|
import { makeAuthenticatedRequest, authStorage } from '@/lib/auth'
|
||||||
|
import { AlertCircle } from 'lucide-react'
|
||||||
|
|
||||||
|
interface UserFormProps {
|
||||||
|
open: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onSuccess: () => void
|
||||||
|
user?: User | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UserForm({ open, onClose, onSuccess, user }: UserFormProps) {
|
||||||
|
const [email, setEmail] = useState(user?.email || '')
|
||||||
|
const [password, setPassword] = useState('')
|
||||||
|
const [isAdmin, setIsAdmin] = useState(user?.is_admin || false)
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
|
||||||
|
const currentUser = authStorage.getUser()
|
||||||
|
const isEditing = !!user
|
||||||
|
const canEditAdminStatus = currentUser?.is_admin && currentUser.id !== user?.id
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
setLoading(true)
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (isEditing) {
|
||||||
|
const updateData: UpdateUser = {
|
||||||
|
email: email !== user.email ? email : undefined,
|
||||||
|
password: password ? password : undefined,
|
||||||
|
is_admin: canEditAdminStatus && isAdmin !== user.is_admin ? isAdmin : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove undefined values
|
||||||
|
Object.keys(updateData).forEach(key => {
|
||||||
|
if (updateData[key as keyof UpdateUser] === undefined) {
|
||||||
|
delete updateData[key as keyof UpdateUser]
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const response = await makeAuthenticatedRequest(`/api/users/${user.id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(updateData),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Failed to update user')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!password) {
|
||||||
|
throw new Error('Password is required for new users')
|
||||||
|
}
|
||||||
|
|
||||||
|
const createData: CreateUser = {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
is_admin: currentUser?.is_admin ? isAdmin : false
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await makeAuthenticatedRequest('/api/users', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(createData),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
if (response.status === 409) {
|
||||||
|
throw new Error('A user with this email already exists')
|
||||||
|
}
|
||||||
|
throw new Error('Failed to create user')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onSuccess()
|
||||||
|
resetForm()
|
||||||
|
} catch (error) {
|
||||||
|
setError(error instanceof Error ? error.message : 'An error occurred')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetForm = () => {
|
||||||
|
setEmail(user?.email || '')
|
||||||
|
setPassword('')
|
||||||
|
setIsAdmin(user?.is_admin || false)
|
||||||
|
setError('')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleClose = () => {
|
||||||
|
resetForm()
|
||||||
|
onClose()
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={handleClose}>
|
||||||
|
<DialogContent className="sm:max-w-[425px]">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>
|
||||||
|
{isEditing ? 'Edit User' : 'Create New User'}
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{isEditing
|
||||||
|
? 'Make changes to the user account here. Click save when you\'re done.'
|
||||||
|
: 'Add a new user to the system. They will be able to log in with these credentials.'
|
||||||
|
}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="email">Email</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="Enter email address"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="password">
|
||||||
|
{isEditing ? 'New Password (leave blank to keep current)' : 'Password'}
|
||||||
|
</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
placeholder={isEditing ? "Enter new password" : "Enter password"}
|
||||||
|
required={!isEditing}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canEditAdminStatus && (
|
||||||
|
<div className="flex items-center space-x-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="isAdmin"
|
||||||
|
checked={isAdmin}
|
||||||
|
onChange={(e) => setIsAdmin(e.target.checked)}
|
||||||
|
className="rounded border-gray-300"
|
||||||
|
/>
|
||||||
|
<Label htmlFor="isAdmin" className="text-sm font-medium">
|
||||||
|
Administrator privileges
|
||||||
|
</Label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
{error}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={handleClose}
|
||||||
|
disabled={loading}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" disabled={loading || !email.trim()}>
|
||||||
|
{loading ? 'Saving...' : isEditing ? 'Save Changes' : 'Create User'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
)
|
||||||
|
}
|
||||||
188
frontend/src/components/users/user-list.tsx
Normal file
188
frontend/src/components/users/user-list.tsx
Normal file
@@ -0,0 +1,188 @@
|
|||||||
|
import { useState, useEffect } from 'react'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert'
|
||||||
|
import { User, ApiResponse } from 'shared/types'
|
||||||
|
import { UserForm } from './user-form'
|
||||||
|
import { makeAuthenticatedRequest, authStorage } from '@/lib/auth'
|
||||||
|
import { Plus, Edit, Trash2, Calendar, AlertCircle, Loader2, Shield, User as UserIcon } from 'lucide-react'
|
||||||
|
|
||||||
|
export function UserList() {
|
||||||
|
const [users, setUsers] = useState<User[]>([])
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
const [showForm, setShowForm] = useState(false)
|
||||||
|
const [editingUser, setEditingUser] = useState<User | null>(null)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const currentUser = authStorage.getUser()
|
||||||
|
|
||||||
|
const fetchUsers = async () => {
|
||||||
|
setLoading(true)
|
||||||
|
setError('')
|
||||||
|
try {
|
||||||
|
const response = await makeAuthenticatedRequest('/api/users')
|
||||||
|
const data: ApiResponse<User[]> = await response.json()
|
||||||
|
if (data.success && data.data) {
|
||||||
|
setUsers(data.data)
|
||||||
|
} else {
|
||||||
|
setError('Failed to load users')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch users:', error)
|
||||||
|
setError('Failed to connect to server')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (id: string, email: string) => {
|
||||||
|
if (!confirm(`Are you sure you want to delete user "${email}"? This action cannot be undone.`)) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await makeAuthenticatedRequest(`/api/users/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
})
|
||||||
|
if (response.ok) {
|
||||||
|
fetchUsers()
|
||||||
|
} else if (response.status === 403) {
|
||||||
|
setError('You cannot delete this user')
|
||||||
|
} else {
|
||||||
|
setError('Failed to delete user')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete user:', error)
|
||||||
|
setError('Failed to delete user')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEdit = (user: User) => {
|
||||||
|
setEditingUser(user)
|
||||||
|
setShowForm(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleFormSuccess = () => {
|
||||||
|
setShowForm(false)
|
||||||
|
setEditingUser(null)
|
||||||
|
fetchUsers()
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchUsers()
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex justify-between items-center">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-bold tracking-tight">Users</h1>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
Manage user accounts and permissions
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{currentUser?.is_admin && (
|
||||||
|
<Button onClick={() => setShowForm(true)}>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Add User
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
{error}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<div className="flex items-center justify-center py-12">
|
||||||
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||||
|
Loading users...
|
||||||
|
</div>
|
||||||
|
) : users.length === 0 ? (
|
||||||
|
<Card>
|
||||||
|
<CardContent className="py-12 text-center">
|
||||||
|
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-lg bg-muted">
|
||||||
|
<UserIcon className="h-6 w-6" />
|
||||||
|
</div>
|
||||||
|
<h3 className="mt-4 text-lg font-semibold">No users found</h3>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
Get started by creating the first user account.
|
||||||
|
</p>
|
||||||
|
{currentUser?.is_admin && (
|
||||||
|
<Button
|
||||||
|
className="mt-4"
|
||||||
|
onClick={() => setShowForm(true)}
|
||||||
|
>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
Add your first user
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
) : (
|
||||||
|
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||||
|
{users.map((user) => (
|
||||||
|
<Card key={user.id} className="hover:shadow-md transition-shadow">
|
||||||
|
<CardHeader className="pb-3">
|
||||||
|
<div className="flex items-start justify-between">
|
||||||
|
<CardTitle className="text-lg flex items-center">
|
||||||
|
{user.is_admin ? (
|
||||||
|
<Shield className="mr-2 h-4 w-4 text-orange-500" />
|
||||||
|
) : (
|
||||||
|
<UserIcon className="mr-2 h-4 w-4 text-blue-500" />
|
||||||
|
)}
|
||||||
|
{user.email}
|
||||||
|
</CardTitle>
|
||||||
|
<Badge variant={user.is_admin ? "default" : "secondary"}>
|
||||||
|
{user.is_admin ? "Admin" : "User"}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<CardDescription className="flex items-center">
|
||||||
|
<Calendar className="mr-1 h-3 w-3" />
|
||||||
|
Joined {new Date(user.created_at).toLocaleDateString()}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleEdit(user)}
|
||||||
|
className="h-8"
|
||||||
|
>
|
||||||
|
<Edit className="mr-1 h-3 w-3" />
|
||||||
|
Edit
|
||||||
|
</Button>
|
||||||
|
{currentUser?.is_admin && currentUser.id !== user.id && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDelete(user.id, user.email)}
|
||||||
|
className="h-8 text-red-600 hover:text-red-700 hover:bg-red-50"
|
||||||
|
>
|
||||||
|
<Trash2 className="mr-1 h-3 w-3" />
|
||||||
|
Delete
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<UserForm
|
||||||
|
open={showForm}
|
||||||
|
onClose={() => {
|
||||||
|
setShowForm(false)
|
||||||
|
setEditingUser(null)
|
||||||
|
}}
|
||||||
|
onSuccess={handleFormSuccess}
|
||||||
|
user={editingUser}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
5
frontend/src/components/users/users-page.tsx
Normal file
5
frontend/src/components/users/users-page.tsx
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { UserList } from './user-list'
|
||||||
|
|
||||||
|
export function UsersPage() {
|
||||||
|
return <UserList />
|
||||||
|
}
|
||||||
63
frontend/src/lib/auth.ts
Normal file
63
frontend/src/lib/auth.ts
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
import { User } from 'shared/types'
|
||||||
|
|
||||||
|
const TOKEN_KEY = 'auth_token'
|
||||||
|
const USER_KEY = 'auth_user'
|
||||||
|
|
||||||
|
export const authStorage = {
|
||||||
|
getToken: (): string | null => {
|
||||||
|
return localStorage.getItem(TOKEN_KEY)
|
||||||
|
},
|
||||||
|
|
||||||
|
setToken: (token: string): void => {
|
||||||
|
localStorage.setItem(TOKEN_KEY, token)
|
||||||
|
},
|
||||||
|
|
||||||
|
removeToken: (): void => {
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
},
|
||||||
|
|
||||||
|
getUser: (): User | null => {
|
||||||
|
const user = localStorage.getItem(USER_KEY)
|
||||||
|
return user ? JSON.parse(user) : null
|
||||||
|
},
|
||||||
|
|
||||||
|
setUser: (user: User): void => {
|
||||||
|
localStorage.setItem(USER_KEY, JSON.stringify(user))
|
||||||
|
},
|
||||||
|
|
||||||
|
removeUser: (): void => {
|
||||||
|
localStorage.removeItem(USER_KEY)
|
||||||
|
},
|
||||||
|
|
||||||
|
clear: (): void => {
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
localStorage.removeItem(USER_KEY)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getAuthHeaders = (): Record<string, string> => {
|
||||||
|
const token = authStorage.getToken()
|
||||||
|
return token ? { Authorization: `Bearer ${token}` } : {}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const makeAuthenticatedRequest = async (url: string, options: RequestInit = {}) => {
|
||||||
|
const headers = {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
|
...(options.headers || {})
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetch(url, {
|
||||||
|
...options,
|
||||||
|
headers
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isAuthenticated = (): boolean => {
|
||||||
|
return !!authStorage.getToken()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const logout = (): void => {
|
||||||
|
authStorage.clear()
|
||||||
|
window.location.href = '/'
|
||||||
|
}
|
||||||
@@ -17,7 +17,8 @@
|
|||||||
"noFallthroughCasesInSwitch": true,
|
"noFallthroughCasesInSwitch": true,
|
||||||
"baseUrl": ".",
|
"baseUrl": ".",
|
||||||
"paths": {
|
"paths": {
|
||||||
"@/*": ["./src/*"]
|
"@/*": ["./src/*"],
|
||||||
|
"shared/*": ["../shared/*"]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"include": ["src"],
|
"include": ["src"],
|
||||||
|
|||||||
@@ -12,3 +12,50 @@ export interface HelloResponse {
|
|||||||
export interface HelloQuery {
|
export interface HelloQuery {
|
||||||
name?: string
|
name?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface Project {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
owner_id: string
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateProject {
|
||||||
|
name: string
|
||||||
|
owner_id: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateProject {
|
||||||
|
name?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface User {
|
||||||
|
id: string
|
||||||
|
email: string
|
||||||
|
is_admin: boolean
|
||||||
|
created_at: string
|
||||||
|
updated_at: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateUser {
|
||||||
|
email: string
|
||||||
|
password: string
|
||||||
|
is_admin?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateUser {
|
||||||
|
email?: string
|
||||||
|
password?: string
|
||||||
|
is_admin?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginRequest {
|
||||||
|
email: string
|
||||||
|
password: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginResponse {
|
||||||
|
user: User
|
||||||
|
token: string
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user