админка
This commit is contained in:
983
Cargo.lock
generated
983
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
16
Cargo.toml
16
Cargo.toml
@@ -5,12 +5,20 @@ edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.48.0", features = ["full"] }
|
||||
sea-orm = { version = "2.0.0-rc.20", features = ["sqlx-postgres", "runtime-tokio-rustls", "macros"] }
|
||||
sea-orm-migration = "2.0.0-rc.20"
|
||||
sea-orm = { version = "1.0", features = ["sqlx-postgres", "runtime-tokio-rustls", "macros"] }
|
||||
sea-orm-migration = { version = "1.0", default-features = false, features = ["sqlx-postgres", "runtime-tokio-rustls"] }
|
||||
dotenvy = "0.15.7"
|
||||
axum = { version = "0.8.7", features = ["json"] }
|
||||
axum = { version = "0.7", features = ["json"] }
|
||||
chrono = { version = "0.4.42", features = ["serde"] }
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
utoipa = { version = "5.4.0", features = ["axum_extras", "chrono", "decimal_float"] }
|
||||
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] }
|
||||
utoipa-swagger-ui = { version = "8.0", features = ["axum"] }
|
||||
axum-login = "0.15"
|
||||
tower-sessions = "0.12"
|
||||
tower-sessions-sqlx-store = { version = "0.12", features = ["postgres"] }
|
||||
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
|
||||
argon2 = "0.5"
|
||||
async-trait = "0.1"
|
||||
thiserror = "2.0"
|
||||
time = "0.3"
|
||||
90
src/auth.rs
Normal file
90
src/auth.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use axum_login::{AuthUser, AuthnBackend, UserId};
|
||||
use sea_orm::{DatabaseConnection, EntityTrait, ColumnTrait, QueryFilter};
|
||||
use argon2::{
|
||||
password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||
Argon2,
|
||||
};
|
||||
|
||||
use crate::models::{user, User};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthBackend {
|
||||
pub db: DatabaseConnection,
|
||||
}
|
||||
|
||||
impl AuthUser for user::Model {
|
||||
type Id = i32;
|
||||
|
||||
fn id(&self) -> Self::Id {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn session_auth_hash(&self) -> &[u8] {
|
||||
self.password_hash.as_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("Database error: {0}")]
|
||||
Database(#[from] sea_orm::DbErr),
|
||||
#[error("Password hashing error")]
|
||||
PasswordHash,
|
||||
#[error("Invalid credentials")]
|
||||
InvalidCredentials,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Credentials {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl AuthnBackend for AuthBackend {
|
||||
type User = user::Model;
|
||||
type Credentials = Credentials;
|
||||
type Error = Error;
|
||||
|
||||
async fn authenticate(
|
||||
&self,
|
||||
creds: Self::Credentials,
|
||||
) -> Result<Option<Self::User>, Self::Error> {
|
||||
let user = User::find()
|
||||
.filter(user::Column::Username.eq(&creds.username))
|
||||
.one(&self.db)
|
||||
.await?;
|
||||
|
||||
if let Some(user) = user {
|
||||
let parsed_hash = PasswordHash::new(&user.password_hash)
|
||||
.map_err(|_| Error::PasswordHash)?;
|
||||
|
||||
let is_valid = Argon2::default()
|
||||
.verify_password(creds.password.as_bytes(), &parsed_hash)
|
||||
.is_ok();
|
||||
|
||||
if is_valid {
|
||||
Ok(Some(user))
|
||||
} else {
|
||||
Err(Error::InvalidCredentials)
|
||||
}
|
||||
} else {
|
||||
Err(Error::InvalidCredentials)
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_user(&self, user_id: &UserId<Self>) -> Result<Option<Self::User>, Self::Error> {
|
||||
let user = User::find_by_id(*user_id).one(&self.db).await?;
|
||||
Ok(user)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hash_password(password: &str) -> Result<String, Error> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
argon2
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map(|hash| hash.to_string())
|
||||
.map_err(|_| Error::PasswordHash)
|
||||
}
|
||||
49
src/main.rs
49
src/main.rs
@@ -1,21 +1,29 @@
|
||||
use axum::{
|
||||
routing::{get, post, put, delete},
|
||||
Router,
|
||||
Router, middleware as axum_middleware,
|
||||
};
|
||||
use sea_orm::{Database, DatabaseConnection, DbErr};
|
||||
use sea_orm_migration::prelude::*;
|
||||
use std::net::SocketAddr;
|
||||
use utoipa::OpenApi;
|
||||
use utoipa_swagger_ui::SwaggerUi;
|
||||
use tower_sessions::{Expiry, SessionManagerLayer};
|
||||
use tower_sessions_sqlx_store::PostgresStore;
|
||||
use axum_login::AuthManagerLayerBuilder;
|
||||
use time::Duration;
|
||||
|
||||
mod models;
|
||||
mod services;
|
||||
mod migration;
|
||||
mod routes;
|
||||
mod auth;
|
||||
mod middleware;
|
||||
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(
|
||||
paths(
|
||||
routes::auth::login,
|
||||
routes::auth::logout,
|
||||
routes::family::create_family,
|
||||
routes::family::get_family,
|
||||
routes::family::get_all_families,
|
||||
@@ -38,6 +46,8 @@ mod routes;
|
||||
models::family::Model,
|
||||
models::category::Model,
|
||||
models::expense::Model,
|
||||
routes::auth::LoginRequest,
|
||||
routes::auth::LoginResponse,
|
||||
routes::family::CreateFamilyRequest,
|
||||
routes::family::UpdateFamilyRequest,
|
||||
routes::category::CreateCategoryRequest,
|
||||
@@ -48,6 +58,7 @@ mod routes;
|
||||
)
|
||||
),
|
||||
tags(
|
||||
(name = "auth", description = "Authentication endpoints"),
|
||||
(name = "families", description = "Family management endpoints"),
|
||||
(name = "categories", description = "Category management endpoints"),
|
||||
(name = "expenses", description = "Expense management endpoints")
|
||||
@@ -79,8 +90,34 @@ async fn main() -> Result<(), DbErr> {
|
||||
crate::migration::Migrator::up(&db, None).await?;
|
||||
println!("Migrations completed!");
|
||||
|
||||
let api_routes = Router::new()
|
||||
let database_url = std::env::var("DATABASE_URL")
|
||||
.expect("DATABASE_URL must be set in .env file");
|
||||
|
||||
let session_store = PostgresStore::new(
|
||||
sqlx::PgPool::connect(&database_url)
|
||||
.await
|
||||
.expect("Failed to connect to database for sessions"),
|
||||
);
|
||||
session_store
|
||||
.migrate()
|
||||
.await
|
||||
.expect("Failed to run session store migrations");
|
||||
|
||||
let session_layer = SessionManagerLayer::new(session_store)
|
||||
.with_secure(false)
|
||||
.with_expiry(Expiry::OnInactivity(Duration::days(1)));
|
||||
|
||||
let backend = auth::AuthBackend { db: db.clone() };
|
||||
let auth_layer = AuthManagerLayerBuilder::new(backend, session_layer).build();
|
||||
|
||||
let protected_routes = Router::new()
|
||||
.route("/families", post(routes::family::create_family))
|
||||
.route_layer(axum_middleware::from_fn(middleware::require_admin));
|
||||
|
||||
let api_routes = Router::new()
|
||||
.route("/login", post(routes::auth::login))
|
||||
.route("/logout", post(routes::auth::logout))
|
||||
.merge(protected_routes)
|
||||
.route("/families", get(routes::family::get_all_families))
|
||||
.route("/families/{id}", get(routes::family::get_family))
|
||||
.route("/families/{id}", put(routes::family::update_family))
|
||||
@@ -96,11 +133,13 @@ async fn main() -> Result<(), DbErr> {
|
||||
.route("/families/{family_id}/categories/{category_id}/expenses/{expense_id}", put(routes::expense::update_expense))
|
||||
.route("/families/{family_id}/categories/{category_id}/expenses/{expense_id}", delete(routes::expense::delete_expense))
|
||||
.route("/families/{family_id}/categories/{category_id}/remaining", get(routes::expense::get_remaining_limit))
|
||||
.layer(auth_layer)
|
||||
.with_state(db);
|
||||
|
||||
let app = api_routes
|
||||
.merge(SwaggerUi::new("/swagger-ui")
|
||||
.url("/api-docs/openapi.json", ApiDoc::openapi()));
|
||||
let swagger_ui = SwaggerUi::new("/swagger-ui")
|
||||
.url("/api-docs/openapi.json", ApiDoc::openapi());
|
||||
|
||||
let app = api_routes.merge(swagger_ui);
|
||||
|
||||
let addr = SocketAddr::from(([0, 0, 0, 0], 8080));
|
||||
println!("Server running on http://{}", addr);
|
||||
|
||||
23
src/middleware.rs
Normal file
23
src/middleware.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use axum::{
|
||||
extract::Request,
|
||||
http::StatusCode,
|
||||
middleware::Next,
|
||||
response::Response,
|
||||
};
|
||||
use axum_login::AuthSession;
|
||||
|
||||
use crate::auth::AuthBackend;
|
||||
|
||||
pub async fn require_admin(
|
||||
auth_session: AuthSession<AuthBackend>,
|
||||
request: Request,
|
||||
next: Next,
|
||||
) -> Result<Response, StatusCode> {
|
||||
let user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if !user.is_admin {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
Ok(next.run(request).await)
|
||||
}
|
||||
57
src/migration/m20241209_000002_create_users.rs
Normal file
57
src/migration/m20241209_000002_create_users.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.create_table(
|
||||
Table::create()
|
||||
.table(User::Table)
|
||||
.if_not_exists()
|
||||
.col(
|
||||
ColumnDef::new(User::Id)
|
||||
.integer()
|
||||
.not_null()
|
||||
.auto_increment()
|
||||
.primary_key(),
|
||||
)
|
||||
.col(
|
||||
ColumnDef::new(User::Username)
|
||||
.string()
|
||||
.not_null()
|
||||
.unique_key(),
|
||||
)
|
||||
.col(ColumnDef::new(User::PasswordHash).string().not_null())
|
||||
.col(
|
||||
ColumnDef::new(User::IsAdmin)
|
||||
.boolean()
|
||||
.not_null()
|
||||
.default(false),
|
||||
)
|
||||
.to_owned(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
manager
|
||||
.drop_table(Table::drop().table(User::Table).to_owned())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum User {
|
||||
Table,
|
||||
Id,
|
||||
Username,
|
||||
PasswordHash,
|
||||
IsAdmin,
|
||||
}
|
||||
48
src/migration/m20241209_000003_seed_admin.rs
Normal file
48
src/migration/m20241209_000003_seed_admin.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use sea_orm_migration::prelude::*;
|
||||
|
||||
#[derive(DeriveMigrationName)]
|
||||
pub struct Migration;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigrationTrait for Migration {
|
||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
use argon2::{
|
||||
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
|
||||
Argon2,
|
||||
};
|
||||
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let argon2 = Argon2::default();
|
||||
let password_hash = argon2
|
||||
.hash_password("2123".as_bytes(), &salt)
|
||||
.map_err(|_| DbErr::Migration("Failed to hash password".to_string()))?
|
||||
.to_string();
|
||||
|
||||
let insert = Query::insert()
|
||||
.into_table(User::Table)
|
||||
.columns([User::Username, User::PasswordHash, User::IsAdmin])
|
||||
.values_panic(["admin".into(), password_hash.into(), true.into()])
|
||||
.to_owned();
|
||||
|
||||
manager.exec_stmt(insert).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||
let delete = Query::delete()
|
||||
.from_table(User::Table)
|
||||
.and_where(Expr::col(User::Username).eq("admin"))
|
||||
.to_owned();
|
||||
|
||||
manager.exec_stmt(delete).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DeriveIden)]
|
||||
enum User {
|
||||
Table,
|
||||
Username,
|
||||
PasswordHash,
|
||||
IsAdmin,
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
pub use sea_orm_migration::prelude::*;
|
||||
|
||||
mod m20241209_000001_create_tables;
|
||||
mod m20241209_000002_create_users;
|
||||
mod m20241209_000003_seed_admin;
|
||||
|
||||
pub struct Migrator;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl MigratorTrait for Migrator {
|
||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||
vec![Box::new(m20241209_000001_create_tables::Migration)]
|
||||
vec![
|
||||
Box::new(m20241209_000001_create_tables::Migration),
|
||||
Box::new(m20241209_000002_create_users::Migration),
|
||||
Box::new(m20241209_000003_seed_admin::Migration),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
pub mod family;
|
||||
pub mod category;
|
||||
pub mod expense;
|
||||
pub mod user;
|
||||
|
||||
pub use family::Entity as Family;
|
||||
pub use category::Entity as Category;
|
||||
pub use expense::Entity as Expense;
|
||||
pub use user::Entity as User;
|
||||
|
||||
18
src/models/user.rs
Normal file
18
src/models/user.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "user")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
#[sea_orm(unique)]
|
||||
pub username: String,
|
||||
pub password_hash: String,
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
|
||||
impl ActiveModelBehavior for ActiveModel {}
|
||||
75
src/routes/auth.rs
Normal file
75
src/routes/auth.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use axum_login::AuthSession;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::auth::{AuthBackend, Credentials};
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct LoginRequest {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct LoginResponse {
|
||||
pub success: bool,
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/login",
|
||||
tag = "auth",
|
||||
request_body = LoginRequest,
|
||||
responses(
|
||||
(status = 200, description = "Login successful", body = LoginResponse),
|
||||
(status = 401, description = "Invalid credentials")
|
||||
)
|
||||
)]
|
||||
pub async fn login(
|
||||
mut auth_session: AuthSession<AuthBackend>,
|
||||
Json(payload): Json<LoginRequest>,
|
||||
) -> Result<Json<LoginResponse>, StatusCode> {
|
||||
let user = auth_session
|
||||
.authenticate(Credentials {
|
||||
username: payload.username,
|
||||
password: payload.password,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
auth_session
|
||||
.login(&user)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(LoginResponse {
|
||||
success: true,
|
||||
is_admin: user.is_admin,
|
||||
}))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/logout",
|
||||
tag = "auth",
|
||||
responses(
|
||||
(status = 200, description = "Logout successful")
|
||||
)
|
||||
)]
|
||||
pub async fn logout(
|
||||
mut auth_session: AuthSession<AuthBackend>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
auth_session
|
||||
.logout()
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(StatusCode::OK)
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod family;
|
||||
pub mod category;
|
||||
pub mod expense;
|
||||
pub mod auth;
|
||||
|
||||
Reference in New Issue
Block a user