User management
This commit is contained in:
@@ -17,3 +17,5 @@ sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "chron
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
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::{
|
||||
routing::{get, post},
|
||||
Router,
|
||||
Json,
|
||||
extract::{Extension, Query},
|
||||
response::Json as ResponseJson,
|
||||
extract::{Query, Extension},
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use tower_http::cors::CorsLayer;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tracing_subscriber;
|
||||
use sqlx::{PgPool, postgres::PgPoolOptions};
|
||||
use sqlx::{postgres::PgPoolOptions, PgPool};
|
||||
use std::env;
|
||||
use tower_http::cors::CorsLayer;
|
||||
use tracing_subscriber;
|
||||
|
||||
|
||||
mod routes;
|
||||
mod auth;
|
||||
mod models;
|
||||
mod routes;
|
||||
|
||||
use routes::health;
|
||||
use auth::hash_password;
|
||||
use models::ApiResponse;
|
||||
use routes::{health, projects, users};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
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 {
|
||||
success: true,
|
||||
data: Some(payload),
|
||||
@@ -47,31 +49,92 @@ async fn echo_handler(Json(payload): Json<serde_json::Value>) -> ResponseJson<Ap
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
// Load environment variables from .env file
|
||||
dotenvy::dotenv().ok();
|
||||
|
||||
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// Database connection
|
||||
let database_url = env::var("DATABASE_URL")
|
||||
.expect("DATABASE_URL must be set in environment or .env file");
|
||||
|
||||
let database_url =
|
||||
env::var("DATABASE_URL").expect("DATABASE_URL must be set in environment or .env file");
|
||||
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(10)
|
||||
.connect(&database_url)
|
||||
.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()
|
||||
.route("/", get(|| async { "Bloop API" }))
|
||||
.route("/health", get(health::health_check))
|
||||
.route("/hello", get(hello_handler))
|
||||
.route("/echo", post(echo_handler))
|
||||
.merge(projects::projects_router())
|
||||
.merge(users::users_router())
|
||||
.layer(Extension(pool))
|
||||
.layer(CorsLayer::permissive());
|
||||
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3001").await?;
|
||||
|
||||
|
||||
tracing::info!("Server running on http://0.0.0.0:3001");
|
||||
|
||||
|
||||
axum::serve(listener, app).await?;
|
||||
|
||||
|
||||
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 id: Uuid,
|
||||
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 updated_at: DateTime<Utc>,
|
||||
}
|
||||
@@ -16,10 +18,45 @@ pub struct User {
|
||||
pub struct CreateUser {
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
pub is_admin: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UpdateUser {
|
||||
pub email: 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 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))
|
||||
}
|
||||
Reference in New Issue
Block a user