initial commit of gitara site
This commit is contained in:
100
src/app.rs
Normal file
100
src/app.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use async_trait::async_trait;
|
||||
use loco_rs::{
|
||||
app::{AppContext, Hooks, Initializer},
|
||||
bgworker::{BackgroundWorker, Queue},
|
||||
boot::{create_app, BootResult, StartMode},
|
||||
config::Config,
|
||||
controller::AppRoutes,
|
||||
db::{self, truncate_table},
|
||||
environment::Environment,
|
||||
storage::{self, Storage},
|
||||
task::Tasks,
|
||||
Result,
|
||||
};
|
||||
use migration::Migrator;
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use crate::{
|
||||
controllers, initializers, models::_entities::users, tasks, workers::downloader::DownloadWorker,
|
||||
};
|
||||
|
||||
pub struct App;
|
||||
#[async_trait]
|
||||
impl Hooks for App {
|
||||
fn app_name() -> &'static str {
|
||||
env!("CARGO_CRATE_NAME")
|
||||
}
|
||||
|
||||
fn app_version() -> String {
|
||||
format!(
|
||||
"{} ({})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
option_env!("BUILD_SHA")
|
||||
.or(option_env!("GITHUB_SHA"))
|
||||
.unwrap_or("dev")
|
||||
)
|
||||
}
|
||||
|
||||
async fn boot(
|
||||
mode: StartMode,
|
||||
environment: &Environment,
|
||||
config: Config,
|
||||
) -> Result<BootResult> {
|
||||
create_app::<Self, Migrator>(mode, environment, config).await
|
||||
}
|
||||
|
||||
async fn load_config(environment: &Environment) -> Result<Config> {
|
||||
dotenvy::dotenv().ok();
|
||||
environment.load()
|
||||
}
|
||||
|
||||
async fn initializers(_ctx: &AppContext) -> Result<Vec<Box<dyn Initializer>>> {
|
||||
Ok(vec![
|
||||
Box::new(initializers::view_engine::ViewEngineInitializer),
|
||||
Box::new(initializers::admin_seeder::AdminSeeder),
|
||||
])
|
||||
}
|
||||
|
||||
fn routes(_ctx: &AppContext) -> AppRoutes {
|
||||
AppRoutes::with_default_routes() // controller routes below
|
||||
.add_route(controllers::auth::routes())
|
||||
.add_route(controllers::admin::routes())
|
||||
.add_route(controllers::blog::routes())
|
||||
.add_route(controllers::i18n::routes())
|
||||
.add_route(controllers::media::routes())
|
||||
.add_route(controllers::pages::routes())
|
||||
.add_route(controllers::frontend::routes())
|
||||
}
|
||||
|
||||
async fn after_context(ctx: AppContext) -> Result<AppContext> {
|
||||
let upload_root = crate::controllers::media::uploads_root(&ctx.config)?;
|
||||
tokio::fs::create_dir_all(upload_root.join(controllers::media::AUDIO_STORAGE_DIR)).await?;
|
||||
tokio::fs::create_dir_all(upload_root.join(controllers::media::IMAGE_STORAGE_DIR)).await?;
|
||||
|
||||
let driver = storage::drivers::local::new_with_prefix(&upload_root)?;
|
||||
Ok(AppContext {
|
||||
storage: Arc::new(Storage::single(driver)),
|
||||
..ctx
|
||||
})
|
||||
}
|
||||
|
||||
async fn connect_workers(ctx: &AppContext, queue: &Queue) -> Result<()> {
|
||||
queue.register(DownloadWorker::build(ctx)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(unused_variables)]
|
||||
fn register_tasks(tasks: &mut Tasks) {
|
||||
// tasks-inject (do not remove)
|
||||
}
|
||||
async fn truncate(ctx: &AppContext) -> Result<()> {
|
||||
truncate_table(&ctx.db, users::Entity).await?;
|
||||
Ok(())
|
||||
}
|
||||
async fn seed(ctx: &AppContext, base: &Path) -> Result<()> {
|
||||
db::seed::<users::ActiveModel>(&ctx.db, &base.join("users.yaml").display().to_string())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
8
src/bin/main.rs
Normal file
8
src/bin/main.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use loco_rs::cli;
|
||||
use migration::Migrator;
|
||||
use gitara_web::app::App;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> loco_rs::Result<()> {
|
||||
cli::main::<App, Migrator>().await
|
||||
}
|
||||
57
src/controllers/admin.rs
Normal file
57
src/controllers/admin.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use crate::models::{
|
||||
_entities::{audio_albums, audio_tracks, audit_logs, blog_articles, users},
|
||||
users as users_model,
|
||||
};
|
||||
use loco_rs::prelude::*;
|
||||
use sea_orm::{EntityTrait, PaginatorTrait};
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct DashboardResponse {
|
||||
users: u64,
|
||||
blog_articles: u64,
|
||||
audio_albums: u64,
|
||||
audio_tracks: u64,
|
||||
audit_logs: u64,
|
||||
}
|
||||
|
||||
pub(crate) fn admin_email(ctx: &AppContext) -> Option<&str> {
|
||||
ctx.config
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.get("admin_email"))
|
||||
.and_then(|email| email.as_str())
|
||||
}
|
||||
|
||||
pub(crate) fn is_admin(ctx: &AppContext, user: &users::Model) -> bool {
|
||||
admin_email(ctx).is_some_and(|email| user.email.eq_ignore_ascii_case(email))
|
||||
}
|
||||
|
||||
pub(crate) async fn current_admin(auth: auth::JWT, ctx: &AppContext) -> Result<users::Model> {
|
||||
let user = users_model::Model::find_by_pid(&ctx.db, &auth.claims.pid).await?;
|
||||
|
||||
if !is_admin(ctx, &user) {
|
||||
return unauthorized("admin only");
|
||||
}
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn dashboard(auth: auth::JWT, State(ctx): State<AppContext>) -> Result<Response> {
|
||||
current_admin(auth, &ctx).await?;
|
||||
|
||||
format::json(DashboardResponse {
|
||||
users: users::Entity::find().count(&ctx.db).await?,
|
||||
blog_articles: blog_articles::Entity::find().count(&ctx.db).await?,
|
||||
audio_albums: audio_albums::Entity::find().count(&ctx.db).await?,
|
||||
audio_tracks: audio_tracks::Entity::find().count(&ctx.db).await?,
|
||||
audit_logs: audit_logs::Entity::find().count(&ctx.db).await?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.prefix("/api/admin")
|
||||
.add("/dashboard", get(dashboard))
|
||||
}
|
||||
316
src/controllers/auth.rs
Normal file
316
src/controllers/auth.rs
Normal file
@@ -0,0 +1,316 @@
|
||||
use crate::{
|
||||
mailers::auth::AuthMailer,
|
||||
models::{
|
||||
_entities::users,
|
||||
users::{LoginParams, RegisterParams},
|
||||
},
|
||||
views::auth::{CurrentResponse, LoginResponse},
|
||||
};
|
||||
use axum_extra::extract::cookie::{Cookie, SameSite};
|
||||
use loco_rs::prelude::*;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::OnceLock;
|
||||
use time::Duration as TimeDuration;
|
||||
|
||||
pub static EMAIL_DOMAIN_RE: OnceLock<Regex> = OnceLock::new();
|
||||
pub(crate) const AUTH_COOKIE: &str = "auth_token";
|
||||
|
||||
fn get_allow_email_domain_re() -> &'static Regex {
|
||||
EMAIL_DOMAIN_RE.get_or_init(|| {
|
||||
Regex::new(r"@example\.com$|@gmail\.com$").expect("Failed to compile regex")
|
||||
})
|
||||
}
|
||||
|
||||
fn admin_email(ctx: &AppContext) -> Option<&str> {
|
||||
ctx.config
|
||||
.settings
|
||||
.as_ref()
|
||||
.and_then(|settings| settings.get("admin_email"))
|
||||
.and_then(|email| email.as_str())
|
||||
}
|
||||
|
||||
fn is_admin(ctx: &AppContext, user: &users::Model) -> bool {
|
||||
admin_email(ctx).is_some_and(|email| user.email.eq_ignore_ascii_case(email))
|
||||
}
|
||||
|
||||
pub(crate) fn auth_cookie(token: &str, max_age_seconds: u64) -> Cookie<'static> {
|
||||
Cookie::build((AUTH_COOKIE, token.to_string()))
|
||||
.path("/")
|
||||
.http_only(true)
|
||||
.same_site(SameSite::Lax)
|
||||
.max_age(TimeDuration::seconds(max_age_seconds as i64))
|
||||
.build()
|
||||
}
|
||||
|
||||
pub(crate) fn clear_auth_cookie() -> Cookie<'static> {
|
||||
Cookie::build((AUTH_COOKIE, ""))
|
||||
.path("/")
|
||||
.http_only(true)
|
||||
.same_site(SameSite::Lax)
|
||||
.max_age(TimeDuration::seconds(0))
|
||||
.build()
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct ForgotParams {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct ResetParams {
|
||||
pub token: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct MagicLinkParams {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct ResendVerificationParams {
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
/// Register function creates a new user with the given parameters and sends a
|
||||
/// welcome email to the user
|
||||
#[debug_handler]
|
||||
async fn register(
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<RegisterParams>,
|
||||
) -> Result<Response> {
|
||||
let res = users::Model::create_with_password(&ctx.db, ¶ms).await;
|
||||
|
||||
let user = match res {
|
||||
Ok(user) => user,
|
||||
Err(err) => {
|
||||
tracing::info!(
|
||||
message = err.to_string(),
|
||||
user_email = ¶ms.email,
|
||||
"could not register user",
|
||||
);
|
||||
return format::json(());
|
||||
}
|
||||
};
|
||||
|
||||
let user = user
|
||||
.into_active_model()
|
||||
.set_email_verification_sent(&ctx.db)
|
||||
.await?;
|
||||
|
||||
AuthMailer::send_welcome(&ctx, &user).await?;
|
||||
|
||||
format::json(())
|
||||
}
|
||||
|
||||
/// Verify register user. if the user not verified his email, he can't login to
|
||||
/// the system.
|
||||
#[debug_handler]
|
||||
async fn verify(State(ctx): State<AppContext>, Path(token): Path<String>) -> Result<Response> {
|
||||
let Ok(user) = users::Model::find_by_verification_token(&ctx.db, &token).await else {
|
||||
return unauthorized("invalid token");
|
||||
};
|
||||
|
||||
if user.email_verified_at.is_some() {
|
||||
tracing::info!(pid = user.pid.to_string(), "user already verified");
|
||||
} else {
|
||||
let active_model = user.into_active_model();
|
||||
let user = active_model.verified(&ctx.db).await?;
|
||||
tracing::info!(pid = user.pid.to_string(), "user verified");
|
||||
}
|
||||
|
||||
format::json(())
|
||||
}
|
||||
|
||||
/// In case the user forgot his password this endpoints generate a forgot token
|
||||
/// and send email to the user. In case the email not found in our DB, we are
|
||||
/// returning a valid request for for security reasons (not exposing users DB
|
||||
/// list).
|
||||
#[debug_handler]
|
||||
async fn forgot(
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<ForgotParams>,
|
||||
) -> Result<Response> {
|
||||
let Ok(user) = users::Model::find_by_email(&ctx.db, ¶ms.email).await else {
|
||||
// we don't want to expose our users email. if the email is invalid we still
|
||||
// returning success to the caller
|
||||
return format::json(());
|
||||
};
|
||||
|
||||
let user = user
|
||||
.into_active_model()
|
||||
.set_forgot_password_sent(&ctx.db)
|
||||
.await?;
|
||||
|
||||
AuthMailer::forgot_password(&ctx, &user).await?;
|
||||
|
||||
format::json(())
|
||||
}
|
||||
|
||||
/// reset user password by the given parameters
|
||||
#[debug_handler]
|
||||
async fn reset(State(ctx): State<AppContext>, Json(params): Json<ResetParams>) -> Result<Response> {
|
||||
let Ok(user) = users::Model::find_by_reset_token(&ctx.db, ¶ms.token).await else {
|
||||
// we don't want to expose our users email. if the email is invalid we still
|
||||
// returning success to the caller
|
||||
tracing::info!("reset token not found");
|
||||
|
||||
return format::json(());
|
||||
};
|
||||
user.into_active_model()
|
||||
.reset_password(&ctx.db, ¶ms.password)
|
||||
.await?;
|
||||
|
||||
format::json(())
|
||||
}
|
||||
|
||||
/// Creates a user login and returns a token
|
||||
#[debug_handler]
|
||||
async fn login(State(ctx): State<AppContext>, Json(params): Json<LoginParams>) -> Result<Response> {
|
||||
let Ok(user) = users::Model::find_by_email(&ctx.db, ¶ms.email).await else {
|
||||
tracing::debug!(
|
||||
email = params.email,
|
||||
"login attempt with non-existent email"
|
||||
);
|
||||
return unauthorized("Invalid credentials!");
|
||||
};
|
||||
|
||||
let valid = user.verify_password(¶ms.password);
|
||||
|
||||
if !valid {
|
||||
return unauthorized("unauthorized!");
|
||||
}
|
||||
|
||||
let jwt_secret = ctx.config.get_jwt_config()?;
|
||||
|
||||
let token = user
|
||||
.generate_jwt(&jwt_secret.secret, jwt_secret.expiration)
|
||||
.or_else(|_| unauthorized("unauthorized!"))?;
|
||||
|
||||
format::render()
|
||||
.cookies(&[auth_cookie(&token, jwt_secret.expiration)])?
|
||||
.json(LoginResponse::new(&user, &token, is_admin(&ctx, &user)))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn current(auth: auth::JWT, State(ctx): State<AppContext>) -> Result<Response> {
|
||||
let user = users::Model::find_by_pid(&ctx.db, &auth.claims.pid).await?;
|
||||
format::json(CurrentResponse::new(&user, is_admin(&ctx, &user)))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn logout() -> Result<Response> {
|
||||
format::render().cookies(&[clear_auth_cookie()])?.json(())
|
||||
}
|
||||
|
||||
/// Magic link authentication provides a secure and passwordless way to log in to the application.
|
||||
///
|
||||
/// # Flow
|
||||
/// 1. **Request a Magic Link**:
|
||||
/// A registered user sends a POST request to `/magic-link` with their email.
|
||||
/// If the email exists, a short-lived, one-time-use token is generated and sent to the user's email.
|
||||
/// For security and to avoid exposing whether an email exists, the response always returns 200, even if the email is invalid.
|
||||
///
|
||||
/// 2. **Click the Magic Link**:
|
||||
/// The user clicks the link (/magic-link/{token}), which validates the token and its expiration.
|
||||
/// If valid, the server generates a JWT and responds with a [`LoginResponse`].
|
||||
/// If invalid or expired, an unauthorized response is returned.
|
||||
///
|
||||
/// This flow enhances security by avoiding traditional passwords and providing a seamless login experience.
|
||||
async fn magic_link(
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<MagicLinkParams>,
|
||||
) -> Result<Response> {
|
||||
let email_regex = get_allow_email_domain_re();
|
||||
if !email_regex.is_match(¶ms.email) {
|
||||
tracing::debug!(
|
||||
email = params.email,
|
||||
"The provided email is invalid or does not match the allowed domains"
|
||||
);
|
||||
return bad_request("invalid request");
|
||||
}
|
||||
|
||||
let Ok(user) = users::Model::find_by_email(&ctx.db, ¶ms.email).await else {
|
||||
// we don't want to expose our users email. if the email is invalid we still
|
||||
// returning success to the caller
|
||||
tracing::debug!(email = params.email, "user not found by email");
|
||||
return format::empty_json();
|
||||
};
|
||||
|
||||
let user = user.into_active_model().create_magic_link(&ctx.db).await?;
|
||||
AuthMailer::send_magic_link(&ctx, &user).await?;
|
||||
|
||||
format::empty_json()
|
||||
}
|
||||
|
||||
/// Verifies a magic link token and authenticates the user.
|
||||
async fn magic_link_verify(
|
||||
Path(token): Path<String>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let Ok(user) = users::Model::find_by_magic_token(&ctx.db, &token).await else {
|
||||
// we don't want to expose our users email. if the email is invalid we still
|
||||
// returning success to the caller
|
||||
return unauthorized("unauthorized!");
|
||||
};
|
||||
|
||||
let user = user.into_active_model().clear_magic_link(&ctx.db).await?;
|
||||
|
||||
let jwt_secret = ctx.config.get_jwt_config()?;
|
||||
|
||||
let token = user
|
||||
.generate_jwt(&jwt_secret.secret, jwt_secret.expiration)
|
||||
.or_else(|_| unauthorized("unauthorized!"))?;
|
||||
|
||||
format::render()
|
||||
.cookies(&[auth_cookie(&token, jwt_secret.expiration)])?
|
||||
.json(LoginResponse::new(&user, &token, is_admin(&ctx, &user)))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn resend_verification_email(
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<ResendVerificationParams>,
|
||||
) -> Result<Response> {
|
||||
let Ok(user) = users::Model::find_by_email(&ctx.db, ¶ms.email).await else {
|
||||
tracing::info!(
|
||||
email = params.email,
|
||||
"User not found for resend verification"
|
||||
);
|
||||
return format::json(());
|
||||
};
|
||||
|
||||
if user.email_verified_at.is_some() {
|
||||
tracing::info!(
|
||||
pid = user.pid.to_string(),
|
||||
"User already verified, skipping resend"
|
||||
);
|
||||
return format::json(());
|
||||
}
|
||||
|
||||
let user = user
|
||||
.into_active_model()
|
||||
.set_email_verification_sent(&ctx.db)
|
||||
.await?;
|
||||
|
||||
AuthMailer::send_welcome(&ctx, &user).await?;
|
||||
tracing::info!(pid = user.pid.to_string(), "Verification email re-sent");
|
||||
|
||||
format::json(())
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.prefix("/api/auth")
|
||||
.add("/register", post(register))
|
||||
.add("/verify/{token}", get(verify))
|
||||
.add("/login", post(login))
|
||||
.add("/logout", post(logout))
|
||||
.add("/forgot", post(forgot))
|
||||
.add("/reset", post(reset))
|
||||
.add("/current", get(current))
|
||||
.add("/magic-link", post(magic_link))
|
||||
.add("/magic-link/{token}", get(magic_link_verify))
|
||||
.add("/resend-verification-mail", post(resend_verification_email))
|
||||
}
|
||||
245
src/controllers/blog.rs
Normal file
245
src/controllers/blog.rs
Normal file
@@ -0,0 +1,245 @@
|
||||
use crate::{controllers::admin, models::_entities::blog_articles};
|
||||
use chrono::Utc;
|
||||
use loco_rs::prelude::*;
|
||||
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, QueryOrder, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ArticleParams {
|
||||
title: String,
|
||||
content: String,
|
||||
excerpt: Option<String>,
|
||||
published: Option<bool>,
|
||||
featured_image_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct ArticleResponse {
|
||||
id: Uuid,
|
||||
title: String,
|
||||
slug: String,
|
||||
content: String,
|
||||
excerpt: Option<String>,
|
||||
published: bool,
|
||||
author_id: i32,
|
||||
featured_image_id: Option<String>,
|
||||
view_count: i32,
|
||||
created_at: chrono::DateTime<chrono::FixedOffset>,
|
||||
updated_at: chrono::DateTime<chrono::FixedOffset>,
|
||||
published_at: Option<chrono::DateTime<chrono::FixedOffset>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct ArticleListResponse {
|
||||
articles: Vec<ArticleResponse>,
|
||||
}
|
||||
|
||||
impl From<blog_articles::Model> for ArticleResponse {
|
||||
fn from(article: blog_articles::Model) -> Self {
|
||||
Self {
|
||||
id: article.id,
|
||||
title: article.title,
|
||||
slug: article.slug,
|
||||
content: article.content,
|
||||
excerpt: article.excerpt,
|
||||
published: article.published,
|
||||
author_id: article.author_id,
|
||||
featured_image_id: article.featured_image_id,
|
||||
view_count: article.view_count,
|
||||
created_at: article.created_at,
|
||||
updated_at: article.updated_at,
|
||||
published_at: article.published_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn slugify(title: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
let mut last_was_dash = false;
|
||||
|
||||
for ch in title.chars().flat_map(char::to_lowercase) {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
slug.push(ch);
|
||||
last_was_dash = false;
|
||||
} else if !last_was_dash && !slug.is_empty() {
|
||||
slug.push('-');
|
||||
last_was_dash = true;
|
||||
}
|
||||
}
|
||||
|
||||
let slug = slug.trim_matches('-').to_string();
|
||||
if slug.is_empty() {
|
||||
Uuid::new_v4().to_string()
|
||||
} else {
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
fn published_at_for(published: bool) -> Option<chrono::DateTime<chrono::FixedOffset>> {
|
||||
published.then(|| Utc::now().into())
|
||||
}
|
||||
|
||||
async fn find_article_by_id(ctx: &AppContext, id: Uuid) -> Result<blog_articles::Model> {
|
||||
blog_articles::Entity::find_by_id(id)
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn public_index(State(ctx): State<AppContext>) -> Result<Response> {
|
||||
let articles = blog_articles::Entity::find()
|
||||
.filter(blog_articles::Column::Published.eq(true))
|
||||
.order_by_desc(blog_articles::Column::PublishedAt)
|
||||
.all(&ctx.db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(ArticleResponse::from)
|
||||
.collect();
|
||||
|
||||
format::json(ArticleListResponse { articles })
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn public_show(Path(slug): Path<String>, State(ctx): State<AppContext>) -> Result<Response> {
|
||||
let article = blog_articles::Entity::find()
|
||||
.filter(blog_articles::Column::Slug.eq(slug))
|
||||
.filter(blog_articles::Column::Published.eq(true))
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)?;
|
||||
|
||||
let mut active = article.into_active_model();
|
||||
let next_count = active.view_count.as_ref().to_owned() + 1;
|
||||
active.view_count = Set(next_count);
|
||||
let article = active.update(&ctx.db).await?;
|
||||
|
||||
format::json(ArticleResponse::from(article))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_index(auth: auth::JWT, State(ctx): State<AppContext>) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
|
||||
let articles = blog_articles::Entity::find()
|
||||
.order_by_desc(blog_articles::Column::CreatedAt)
|
||||
.all(&ctx.db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(ArticleResponse::from)
|
||||
.collect();
|
||||
|
||||
format::json(ArticleListResponse { articles })
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_create(
|
||||
auth: auth::JWT,
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<ArticleParams>,
|
||||
) -> Result<Response> {
|
||||
let admin_user = admin::current_admin(auth, &ctx).await?;
|
||||
let published = params.published.unwrap_or(false);
|
||||
|
||||
let article = blog_articles::ActiveModel {
|
||||
id: Set(Uuid::new_v4()),
|
||||
title: Set(params.title.clone()),
|
||||
slug: Set(slugify(¶ms.title)),
|
||||
content: Set(params.content),
|
||||
excerpt: Set(params.excerpt),
|
||||
published: Set(published),
|
||||
author_id: Set(admin_user.id),
|
||||
featured_image_id: Set(params.featured_image_id),
|
||||
view_count: Set(0),
|
||||
published_at: Set(published_at_for(published)),
|
||||
..Default::default()
|
||||
}
|
||||
.insert(&ctx.db)
|
||||
.await?;
|
||||
|
||||
format::json(ArticleResponse::from(article))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_update(
|
||||
auth: auth::JWT,
|
||||
Path(id): Path<Uuid>,
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<ArticleParams>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
|
||||
let existing = find_article_by_id(&ctx, id).await?;
|
||||
let was_published = existing.published;
|
||||
let published = params.published.unwrap_or(was_published);
|
||||
|
||||
let mut article = existing.into_active_model();
|
||||
article.title = Set(params.title.clone());
|
||||
article.slug = Set(slugify(¶ms.title));
|
||||
article.content = Set(params.content);
|
||||
article.excerpt = Set(params.excerpt);
|
||||
article.published = Set(published);
|
||||
article.featured_image_id = Set(params.featured_image_id);
|
||||
if published && !was_published {
|
||||
article.published_at = Set(published_at_for(true));
|
||||
} else if !published {
|
||||
article.published_at = Set(None);
|
||||
}
|
||||
|
||||
let article = article.update(&ctx.db).await?;
|
||||
format::json(ArticleResponse::from(article))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_delete(
|
||||
auth: auth::JWT,
|
||||
Path(id): Path<Uuid>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
let article = find_article_by_id(&ctx, id).await?;
|
||||
article.delete(&ctx.db).await?;
|
||||
format::json(())
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_publish(
|
||||
auth: auth::JWT,
|
||||
Path(id): Path<Uuid>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
let mut article = find_article_by_id(&ctx, id).await?.into_active_model();
|
||||
article.published = Set(true);
|
||||
article.published_at = Set(published_at_for(true));
|
||||
let article = article.update(&ctx.db).await?;
|
||||
format::json(ArticleResponse::from(article))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_unpublish(
|
||||
auth: auth::JWT,
|
||||
Path(id): Path<Uuid>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
let mut article = find_article_by_id(&ctx, id).await?.into_active_model();
|
||||
article.published = Set(false);
|
||||
article.published_at = Set(None);
|
||||
let article = article.update(&ctx.db).await?;
|
||||
format::json(ArticleResponse::from(article))
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.prefix("/api")
|
||||
.add("/blog", get(public_index))
|
||||
.add("/blog/{slug}", get(public_show))
|
||||
.add("/admin/blog/articles", get(admin_index))
|
||||
.add("/admin/blog/articles", post(admin_create))
|
||||
.add("/admin/blog/articles/{id}", put(admin_update))
|
||||
.add("/admin/blog/articles/{id}", delete(admin_delete))
|
||||
.add("/admin/blog/articles/{id}/publish", post(admin_publish))
|
||||
.add("/admin/blog/articles/{id}/unpublish", post(admin_unpublish))
|
||||
}
|
||||
479
src/controllers/frontend.rs
Normal file
479
src/controllers/frontend.rs
Normal file
@@ -0,0 +1,479 @@
|
||||
use crate::{
|
||||
controllers::{admin, auth as auth_controller, i18n::current_lang},
|
||||
models::{
|
||||
_entities::{audio_albums, audio_tracks, blog_articles, site_pages},
|
||||
users::{self, LoginParams},
|
||||
},
|
||||
};
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use chrono::Utc;
|
||||
use loco_rs::prelude::*;
|
||||
use sea_orm::{
|
||||
sea_query::Expr, ActiveModelTrait, ColumnTrait, EntityTrait, Order, QueryFilter, QueryOrder,
|
||||
QuerySelect, Set,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use uuid::Uuid;
|
||||
|
||||
const ABOUT_SLUG: &str = "about";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ArticleForm {
|
||||
title: String,
|
||||
content: String,
|
||||
excerpt: Option<String>,
|
||||
published: Option<String>,
|
||||
featured_image_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AboutForm {
|
||||
title: String,
|
||||
content: String,
|
||||
}
|
||||
|
||||
fn slugify(title: &str) -> String {
|
||||
let mut slug = String::new();
|
||||
let mut last_was_dash = false;
|
||||
|
||||
for ch in title.chars().flat_map(char::to_lowercase) {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
slug.push(ch);
|
||||
last_was_dash = false;
|
||||
} else if !last_was_dash && !slug.is_empty() {
|
||||
slug.push('-');
|
||||
last_was_dash = true;
|
||||
}
|
||||
}
|
||||
|
||||
let slug = slug.trim_matches('-').to_string();
|
||||
if slug.is_empty() {
|
||||
Uuid::new_v4().to_string()
|
||||
} else {
|
||||
slug
|
||||
}
|
||||
}
|
||||
|
||||
fn published_at_for(published: bool) -> Option<chrono::DateTime<chrono::FixedOffset>> {
|
||||
published.then(|| Utc::now().into())
|
||||
}
|
||||
|
||||
fn is_checked(value: &Option<String>) -> bool {
|
||||
value
|
||||
.as_deref()
|
||||
.is_some_and(|value| value == "on" || value == "true")
|
||||
}
|
||||
|
||||
fn normalize_empty(value: Option<String>) -> Option<String> {
|
||||
value.and_then(|value| {
|
||||
let value = value.trim().to_string();
|
||||
if value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(value)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn about_page(ctx: &AppContext) -> Result<site_pages::Model> {
|
||||
site_pages::Entity::find()
|
||||
.filter(site_pages::Column::Slug.eq(ABOUT_SLUG))
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)
|
||||
}
|
||||
|
||||
async fn article_by_id(ctx: &AppContext, id: Uuid) -> Result<blog_articles::Model> {
|
||||
blog_articles::Entity::find_by_id(id)
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)
|
||||
}
|
||||
|
||||
async fn logged_in_admin(ctx: &AppContext, jar: &CookieJar) -> bool {
|
||||
let Some(cookie) = jar.get(auth_controller::AUTH_COOKIE) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(jwt_config) = ctx.config.get_jwt_config() else {
|
||||
return false;
|
||||
};
|
||||
let Ok(claims) = loco_rs::auth::jwt::JWT::new(&jwt_config.secret).validate(cookie.value())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Ok(user) = users::Model::find_by_pid(&ctx.db, &claims.claims.pid).await else {
|
||||
return false;
|
||||
};
|
||||
|
||||
admin::is_admin(ctx, &user)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn home(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let articles = blog_articles::Entity::find()
|
||||
.filter(blog_articles::Column::Published.eq(true))
|
||||
.order_by_desc(blog_articles::Column::PublishedAt)
|
||||
.limit(5)
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
|
||||
// A random published song to suggest on the landing page.
|
||||
let featured_track = audio_tracks::Entity::find()
|
||||
.filter(audio_tracks::Column::Published.eq(true))
|
||||
.order_by(Expr::cust("RANDOM()"), Order::Asc)
|
||||
.one(&ctx.db)
|
||||
.await?;
|
||||
|
||||
// A random published album, never the one the suggested song belongs to.
|
||||
let mut album_query =
|
||||
audio_albums::Entity::find().filter(audio_albums::Column::Published.eq(true));
|
||||
if let Some(album_id) = featured_track.as_ref().and_then(|track| track.album_id) {
|
||||
album_query = album_query.filter(audio_albums::Column::Id.ne(album_id));
|
||||
}
|
||||
let featured_album = album_query
|
||||
.order_by(Expr::cust("RANDOM()"), Order::Asc)
|
||||
.one(&ctx.db)
|
||||
.await?;
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"home/index.html",
|
||||
json!({
|
||||
"articles": articles,
|
||||
"featured_track": featured_track,
|
||||
"featured_album": featured_album,
|
||||
"logged_in_admin": logged_in_admin(&ctx, &jar).await,
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn about(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
format::view(
|
||||
&v,
|
||||
"pages/about.html",
|
||||
json!({
|
||||
"page": about_page(&ctx).await?,
|
||||
"logged_in_admin": logged_in_admin(&ctx, &jar).await,
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn blog_index(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let articles = blog_articles::Entity::find()
|
||||
.filter(blog_articles::Column::Published.eq(true))
|
||||
.order_by_desc(blog_articles::Column::PublishedAt)
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"blog/index.html",
|
||||
json!({
|
||||
"articles": articles,
|
||||
"logged_in_admin": logged_in_admin(&ctx, &jar).await,
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn blog_show(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
Path(slug): Path<String>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let article = blog_articles::Entity::find()
|
||||
.filter(blog_articles::Column::Slug.eq(slug))
|
||||
.filter(blog_articles::Column::Published.eq(true))
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)?;
|
||||
|
||||
let mut active = article.into_active_model();
|
||||
let next_count = active.view_count.as_ref().to_owned() + 1;
|
||||
active.view_count = Set(next_count);
|
||||
let article = active.update(&ctx.db).await?;
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"blog/show.html",
|
||||
json!({
|
||||
"article": article,
|
||||
"logged_in_admin": logged_in_admin(&ctx, &jar).await,
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_login_page(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
if logged_in_admin(&ctx, &jar).await {
|
||||
return format::redirect("/admin/dashboard");
|
||||
}
|
||||
|
||||
format::view(
|
||||
&v,
|
||||
"admin/login.html",
|
||||
json!({
|
||||
"error": null,
|
||||
"logged_in_admin": false,
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_login(
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
Form(params): Form<LoginParams>,
|
||||
) -> Result<Response> {
|
||||
let Ok(user) = users::Model::find_by_email(&ctx.db, ¶ms.email).await else {
|
||||
return format::view(
|
||||
&v,
|
||||
"admin/login.html",
|
||||
json!({
|
||||
"error": "Invalid credentials",
|
||||
"logged_in_admin": false,
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
if !user.verify_password(¶ms.password) || !admin::is_admin(&ctx, &user) {
|
||||
return format::view(
|
||||
&v,
|
||||
"admin/login.html",
|
||||
json!({
|
||||
"error": "Invalid credentials",
|
||||
"logged_in_admin": false,
|
||||
"lang": current_lang(&jar),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let jwt_secret = ctx.config.get_jwt_config()?;
|
||||
let token = user
|
||||
.generate_jwt(&jwt_secret.secret, jwt_secret.expiration)
|
||||
.or_else(|_| unauthorized("unauthorized!"))?;
|
||||
|
||||
format::render()
|
||||
.cookies(&[auth_controller::auth_cookie(&token, jwt_secret.expiration)])?
|
||||
.redirect("/admin/dashboard")
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_logout() -> Result<Response> {
|
||||
format::render()
|
||||
.cookies(&[auth_controller::clear_auth_cookie()])?
|
||||
.redirect("/admin/login")
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_home(
|
||||
auth: auth::JWT,
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
let admin_user = admin::current_admin(auth, &ctx).await?;
|
||||
format::view(
|
||||
&v,
|
||||
"admin/index.html",
|
||||
json!({ "admin": admin_user, "lang": current_lang(&jar) }),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_about(
|
||||
auth: auth::JWT,
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
format::view(
|
||||
&v,
|
||||
"admin/about.html",
|
||||
json!({ "page": about_page(&ctx).await?, "lang": current_lang(&jar) }),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_about_update(
|
||||
auth: auth::JWT,
|
||||
State(ctx): State<AppContext>,
|
||||
Form(params): Form<AboutForm>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
let mut page = about_page(&ctx).await?.into_active_model();
|
||||
page.title = Set(params.title);
|
||||
page.content = Set(params.content);
|
||||
page.update(&ctx.db).await?;
|
||||
format::redirect("/admin/about")
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_articles(
|
||||
auth: auth::JWT,
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
let articles = blog_articles::Entity::find()
|
||||
.order_by_desc(blog_articles::Column::CreatedAt)
|
||||
.all(&ctx.db)
|
||||
.await?;
|
||||
format::view(
|
||||
&v,
|
||||
"admin/blog/index.html",
|
||||
json!({ "articles": articles, "lang": current_lang(&jar) }),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_article_new(
|
||||
auth: auth::JWT,
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
format::view(
|
||||
&v,
|
||||
"admin/blog/new.html",
|
||||
json!({ "lang": current_lang(&jar) }),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_article_create(
|
||||
auth: auth::JWT,
|
||||
State(ctx): State<AppContext>,
|
||||
Form(params): Form<ArticleForm>,
|
||||
) -> Result<Response> {
|
||||
let admin_user = admin::current_admin(auth, &ctx).await?;
|
||||
let published = is_checked(¶ms.published);
|
||||
|
||||
blog_articles::ActiveModel {
|
||||
id: Set(Uuid::new_v4()),
|
||||
title: Set(params.title.clone()),
|
||||
slug: Set(slugify(¶ms.title)),
|
||||
content: Set(params.content),
|
||||
excerpt: Set(normalize_empty(params.excerpt)),
|
||||
published: Set(published),
|
||||
author_id: Set(admin_user.id),
|
||||
featured_image_id: Set(normalize_empty(params.featured_image_id)),
|
||||
view_count: Set(0),
|
||||
published_at: Set(published_at_for(published)),
|
||||
..Default::default()
|
||||
}
|
||||
.insert(&ctx.db)
|
||||
.await?;
|
||||
|
||||
format::redirect("/admin/blog/articles")
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_article_edit(
|
||||
auth: auth::JWT,
|
||||
jar: CookieJar,
|
||||
ViewEngine(v): ViewEngine<TeraView>,
|
||||
Path(id): Path<Uuid>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
format::view(
|
||||
&v,
|
||||
"admin/blog/edit.html",
|
||||
json!({ "article": article_by_id(&ctx, id).await?, "lang": current_lang(&jar) }),
|
||||
)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_article_update(
|
||||
auth: auth::JWT,
|
||||
Path(id): Path<Uuid>,
|
||||
State(ctx): State<AppContext>,
|
||||
Form(params): Form<ArticleForm>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
let existing = article_by_id(&ctx, id).await?;
|
||||
let was_published = existing.published;
|
||||
let published = is_checked(¶ms.published);
|
||||
|
||||
let mut article = existing.into_active_model();
|
||||
article.title = Set(params.title.clone());
|
||||
article.slug = Set(slugify(¶ms.title));
|
||||
article.content = Set(params.content);
|
||||
article.excerpt = Set(normalize_empty(params.excerpt));
|
||||
article.published = Set(published);
|
||||
article.featured_image_id = Set(normalize_empty(params.featured_image_id));
|
||||
if published && !was_published {
|
||||
article.published_at = Set(published_at_for(true));
|
||||
} else if !published {
|
||||
article.published_at = Set(None);
|
||||
}
|
||||
article.update(&ctx.db).await?;
|
||||
|
||||
format::redirect("/admin/blog/articles")
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn admin_article_delete(
|
||||
auth: auth::JWT,
|
||||
Path(id): Path<Uuid>,
|
||||
State(ctx): State<AppContext>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
article_by_id(&ctx, id).await?.delete(&ctx.db).await?;
|
||||
format::redirect("/admin/blog/articles")
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.add("/", get(home))
|
||||
.add("/about", get(about))
|
||||
.add("/blog", get(blog_index))
|
||||
.add("/blog/{slug}", get(blog_show))
|
||||
.add("/admin/login", get(admin_login_page))
|
||||
.add("/admin/login", post(admin_login))
|
||||
.add("/admin/logout", post(admin_logout))
|
||||
.add("/admin", get(admin_login_page))
|
||||
.add("/admin/dashboard", get(admin_home))
|
||||
.add("/admin/about", get(admin_about))
|
||||
.add("/admin/about", post(admin_about_update))
|
||||
.add("/admin/blog/articles", get(admin_articles))
|
||||
.add("/admin/blog/articles/new", get(admin_article_new))
|
||||
.add("/admin/blog/articles", post(admin_article_create))
|
||||
.add("/admin/blog/articles/{id}/edit", get(admin_article_edit))
|
||||
.add("/admin/blog/articles/{id}", post(admin_article_update))
|
||||
.add(
|
||||
"/admin/blog/articles/{id}/delete",
|
||||
post(admin_article_delete),
|
||||
)
|
||||
}
|
||||
63
src/controllers/i18n.rs
Normal file
63
src/controllers/i18n.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
use axum::{
|
||||
http::{header, HeaderMap},
|
||||
response::Redirect,
|
||||
};
|
||||
use loco_rs::prelude::*;
|
||||
use serde::Deserialize;
|
||||
|
||||
pub const LANG_COOKIE: &str = "lang";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct LangForm {
|
||||
pub lang: String,
|
||||
}
|
||||
|
||||
pub fn current_lang(jar: &axum_extra::extract::cookie::CookieJar) -> String {
|
||||
match jar
|
||||
.get(LANG_COOKIE)
|
||||
.map(|cookie| cookie.value().to_string())
|
||||
{
|
||||
Some(ref lang) if lang == "en" => "en".to_string(),
|
||||
_ => "sk".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn set_lang(headers: HeaderMap, Form(form): Form<LangForm>) -> Result<Response> {
|
||||
let lang = if form.lang == "en" { "en" } else { "sk" };
|
||||
let cookie = format!("{LANG_COOKIE}={lang}; Path=/; Max-Age=31536000; SameSite=Lax");
|
||||
|
||||
Ok((
|
||||
[(header::SET_COOKIE, cookie)],
|
||||
Redirect::to(&back_path(&headers)),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
fn back_path(headers: &HeaderMap) -> String {
|
||||
let raw = headers
|
||||
.get(header::REFERER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.unwrap_or("/");
|
||||
|
||||
if raw.starts_with('/') {
|
||||
return raw.to_string();
|
||||
}
|
||||
|
||||
if let Some(after_scheme) = raw.split_once("://").map(|(_, rest)| rest) {
|
||||
if let Some(path_start) = after_scheme.find('/') {
|
||||
let path = &after_scheme[path_start..];
|
||||
return if path.starts_with('/') {
|
||||
path.to_string()
|
||||
} else {
|
||||
"/".to_string()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
"/".to_string()
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new().add("/lang", post(set_lang))
|
||||
}
|
||||
1141
src/controllers/media.rs
Normal file
1141
src/controllers/media.rs
Normal file
File diff suppressed because it is too large
Load Diff
7
src/controllers/mod.rs
Normal file
7
src/controllers/mod.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
pub mod admin;
|
||||
pub mod auth;
|
||||
pub mod blog;
|
||||
pub mod frontend;
|
||||
pub mod i18n;
|
||||
pub mod media;
|
||||
pub mod pages;
|
||||
86
src/controllers/pages.rs
Normal file
86
src/controllers/pages.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
use crate::{controllers::admin, models::_entities::site_pages};
|
||||
use loco_rs::prelude::*;
|
||||
use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
const ABOUT_SLUG: &str = "about";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AboutParams {
|
||||
title: String,
|
||||
content: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct PageResponse {
|
||||
id: Uuid,
|
||||
slug: String,
|
||||
title: String,
|
||||
content: String,
|
||||
updated_at: chrono::DateTime<chrono::FixedOffset>,
|
||||
}
|
||||
|
||||
impl From<site_pages::Model> for PageResponse {
|
||||
fn from(page: site_pages::Model) -> Self {
|
||||
Self {
|
||||
id: page.id,
|
||||
slug: page.slug,
|
||||
title: page.title,
|
||||
content: page.content,
|
||||
updated_at: page.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn find_about(ctx: &AppContext) -> Result<site_pages::Model> {
|
||||
site_pages::Entity::find()
|
||||
.filter(site_pages::Column::Slug.eq(ABOUT_SLUG))
|
||||
.one(&ctx.db)
|
||||
.await?
|
||||
.ok_or_else(|| Error::NotFound)
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn about(State(ctx): State<AppContext>) -> Result<Response> {
|
||||
format::json(PageResponse::from(find_about(&ctx).await?))
|
||||
}
|
||||
|
||||
#[debug_handler]
|
||||
async fn update_about(
|
||||
auth: auth::JWT,
|
||||
State(ctx): State<AppContext>,
|
||||
Json(params): Json<AboutParams>,
|
||||
) -> Result<Response> {
|
||||
admin::current_admin(auth, &ctx).await?;
|
||||
|
||||
let page = match find_about(&ctx).await {
|
||||
Ok(page) => {
|
||||
let mut page = page.into_active_model();
|
||||
page.title = Set(params.title);
|
||||
page.content = Set(params.content);
|
||||
page.update(&ctx.db).await?
|
||||
}
|
||||
Err(Error::NotFound) => {
|
||||
site_pages::ActiveModel {
|
||||
id: Set(Uuid::new_v4()),
|
||||
slug: Set(ABOUT_SLUG.to_string()),
|
||||
title: Set(params.title),
|
||||
content: Set(params.content),
|
||||
..Default::default()
|
||||
}
|
||||
.insert(&ctx.db)
|
||||
.await?
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
format::json(PageResponse::from(page))
|
||||
}
|
||||
|
||||
pub fn routes() -> Routes {
|
||||
Routes::new()
|
||||
.prefix("/api")
|
||||
.add("/about", get(about))
|
||||
.add("/admin/about", put(update_about))
|
||||
}
|
||||
1
src/data/mod.rs
Normal file
1
src/data/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
17
src/fixtures/users.yaml
Normal file
17
src/fixtures/users.yaml
Normal file
@@ -0,0 +1,17 @@
|
||||
---
|
||||
- id: 1
|
||||
pid: 11111111-1111-1111-1111-111111111111
|
||||
email: user1@example.com
|
||||
password: "$argon2id$v=19$m=19456,t=2,p=1$ETQBx4rTgNAZhSaeYZKOZg$eYTdH26CRT6nUJtacLDEboP0li6xUwUF/q5nSlQ8uuc"
|
||||
api_key: lo-95ec80d7-cb60-4b70-9b4b-9ef74cb88758
|
||||
name: user1
|
||||
created_at: "2023-11-12T12:34:56.789Z"
|
||||
updated_at: "2023-11-12T12:34:56.789Z"
|
||||
- id: 2
|
||||
pid: 22222222-2222-2222-2222-222222222222
|
||||
email: user2@example.com
|
||||
password: "$argon2id$v=19$m=19456,t=2,p=1$ETQBx4rTgNAZhSaeYZKOZg$eYTdH26CRT6nUJtacLDEboP0li6xUwUF/q5nSlQ8uuc"
|
||||
api_key: lo-153561ca-fa84-4e1b-813a-c62526d0a77e
|
||||
name: user2
|
||||
created_at: "2023-11-12T12:34:56.789Z"
|
||||
updated_at: "2023-11-12T12:34:56.789Z"
|
||||
36
src/initializers/admin_seeder.rs
Normal file
36
src/initializers/admin_seeder.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use async_trait::async_trait;
|
||||
use loco_rs::prelude::*;
|
||||
|
||||
use crate::models::users::{self, RegisterParams};
|
||||
|
||||
pub struct AdminSeeder;
|
||||
|
||||
#[async_trait]
|
||||
impl Initializer for AdminSeeder {
|
||||
fn name(&self) -> String {
|
||||
"admin-seeder".to_string()
|
||||
}
|
||||
|
||||
async fn before_run(&self, ctx: &AppContext) -> Result<()> {
|
||||
let email = std::env::var("ADMIN_EMAIL").unwrap_or_default();
|
||||
let password = std::env::var("ADMIN_PASSWORD").unwrap_or_default();
|
||||
let name = std::env::var("ADMIN_NAME").unwrap_or_else(|_| "Admin".to_string());
|
||||
|
||||
if email.is_empty() || password.is_empty() {
|
||||
tracing::warn!("ADMIN_EMAIL / ADMIN_PASSWORD not set in .env; admin not seeded");
|
||||
} else if users::Model::find_by_email(&ctx.db, &email).await.is_err() {
|
||||
users::Model::create_with_password(
|
||||
&ctx.db,
|
||||
&RegisterParams {
|
||||
email: email.clone(),
|
||||
password,
|
||||
name,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
tracing::info!(admin = %email, "admin user seeded");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
2
src/initializers/mod.rs
Normal file
2
src/initializers/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod admin_seeder;
|
||||
pub mod view_engine;
|
||||
46
src/initializers/view_engine.rs
Normal file
46
src/initializers/view_engine.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
use async_trait::async_trait;
|
||||
use axum::{Extension, Router as AxumRouter};
|
||||
use fluent_templates::{ArcLoader, FluentLoader};
|
||||
use loco_rs::{
|
||||
app::{AppContext, Initializer},
|
||||
controller::views::{engines, ViewEngine},
|
||||
Error, Result,
|
||||
};
|
||||
use tracing::info;
|
||||
|
||||
const I18N_DIR: &str = "assets/i18n";
|
||||
// Kept outside `I18N_DIR`: fluent-templates >=0.13 scans top-level *.ftl files
|
||||
// in that dir as locales, and "shared" parses as a langid, so a shared.ftl
|
||||
// living there would be loaded twice and fail with a duplicate-resource error.
|
||||
const I18N_SHARED: &str = "assets/i18n_shared/shared.ftl";
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
pub struct ViewEngineInitializer;
|
||||
|
||||
#[async_trait]
|
||||
impl Initializer for ViewEngineInitializer {
|
||||
fn name(&self) -> String {
|
||||
"view-engine".to_string()
|
||||
}
|
||||
|
||||
async fn after_routes(&self, router: AxumRouter, _ctx: &AppContext) -> Result<AxumRouter> {
|
||||
let tera_engine = if std::path::Path::new(I18N_DIR).exists() {
|
||||
let arc = std::sync::Arc::new(
|
||||
ArcLoader::builder(&I18N_DIR, unic_langid::langid!("sk"))
|
||||
.shared_resources(Some(&[I18N_SHARED.into()]))
|
||||
.customize(|bundle| bundle.set_use_isolating(false))
|
||||
.build()
|
||||
.map_err(|e| Error::string(&e.to_string()))?,
|
||||
);
|
||||
info!("locales loaded");
|
||||
|
||||
engines::TeraView::build()?.post_process(move |tera| {
|
||||
tera.register_function("t", FluentLoader::new(arc.clone()));
|
||||
Ok(())
|
||||
})?
|
||||
} else {
|
||||
engines::TeraView::build()?
|
||||
};
|
||||
|
||||
Ok(router.layer(Extension(ViewEngine::from(tera_engine))))
|
||||
}
|
||||
}
|
||||
9
src/lib.rs
Normal file
9
src/lib.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
pub mod app;
|
||||
pub mod controllers;
|
||||
pub mod data;
|
||||
pub mod initializers;
|
||||
pub mod mailers;
|
||||
pub mod models;
|
||||
pub mod tasks;
|
||||
pub mod views;
|
||||
pub mod workers;
|
||||
90
src/mailers/auth.rs
Normal file
90
src/mailers/auth.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
// auth mailer
|
||||
#![allow(non_upper_case_globals)]
|
||||
|
||||
use loco_rs::prelude::*;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::models::users;
|
||||
|
||||
static welcome: Dir<'_> = include_dir!("src/mailers/auth/welcome");
|
||||
static forgot: Dir<'_> = include_dir!("src/mailers/auth/forgot");
|
||||
static magic_link: Dir<'_> = include_dir!("src/mailers/auth/magic_link");
|
||||
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
pub struct AuthMailer {}
|
||||
impl Mailer for AuthMailer {}
|
||||
impl AuthMailer {
|
||||
/// Sending welcome email the the given user
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When email sending is failed
|
||||
pub async fn send_welcome(ctx: &AppContext, user: &users::Model) -> Result<()> {
|
||||
Self::mail_template(
|
||||
ctx,
|
||||
&welcome,
|
||||
mailer::Args {
|
||||
to: user.email.to_string(),
|
||||
locals: json!({
|
||||
"name": user.name,
|
||||
"verifyToken": user.email_verification_token,
|
||||
"domain": ctx.config.server.full_url()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sending forgot password email
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When email sending is failed
|
||||
pub async fn forgot_password(ctx: &AppContext, user: &users::Model) -> Result<()> {
|
||||
Self::mail_template(
|
||||
ctx,
|
||||
&forgot,
|
||||
mailer::Args {
|
||||
to: user.email.to_string(),
|
||||
locals: json!({
|
||||
"name": user.name,
|
||||
"resetToken": user.reset_token,
|
||||
"domain": ctx.config.server.full_url()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sends a magic link authentication email to the user.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When email sending is failed
|
||||
pub async fn send_magic_link(ctx: &AppContext, user: &users::Model) -> Result<()> {
|
||||
Self::mail_template(
|
||||
ctx,
|
||||
&magic_link,
|
||||
mailer::Args {
|
||||
to: user.email.to_string(),
|
||||
locals: json!({
|
||||
"name": user.name,
|
||||
"token": user.magic_link_token.clone().ok_or_else(|| Error::string(
|
||||
"the user model not contains magic link token",
|
||||
))?,
|
||||
"host": ctx.config.server.full_url()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
11
src/mailers/auth/forgot/html.t
Normal file
11
src/mailers/auth/forgot/html.t
Normal file
@@ -0,0 +1,11 @@
|
||||
;<html>
|
||||
|
||||
<body>
|
||||
Hey {{name}},
|
||||
Forgot your password? No worries! You can reset it by clicking the link below:
|
||||
<a href="http://{{domain}}/reset#{{resetToken}}">Reset Your Password</a>
|
||||
If you didn't request a password reset, please ignore this email.
|
||||
Best regards,<br>The Loco Team</br>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
1
src/mailers/auth/forgot/subject.t
Normal file
1
src/mailers/auth/forgot/subject.t
Normal file
@@ -0,0 +1 @@
|
||||
Your reset password link
|
||||
3
src/mailers/auth/forgot/text.t
Normal file
3
src/mailers/auth/forgot/text.t
Normal file
@@ -0,0 +1,3 @@
|
||||
Reset your password with this link:
|
||||
|
||||
http://localhost/reset#{{resetToken}}
|
||||
8
src/mailers/auth/magic_link/html.t
Normal file
8
src/mailers/auth/magic_link/html.t
Normal file
@@ -0,0 +1,8 @@
|
||||
;<html>
|
||||
<body>
|
||||
<p>Magic link example:</p>
|
||||
<a href="{{host}}/api/auth/magic-link/{{token}}">
|
||||
Verify Your Account
|
||||
</a>
|
||||
</body>
|
||||
</html>
|
||||
1
src/mailers/auth/magic_link/subject.t
Normal file
1
src/mailers/auth/magic_link/subject.t
Normal file
@@ -0,0 +1 @@
|
||||
Magic link example
|
||||
2
src/mailers/auth/magic_link/text.t
Normal file
2
src/mailers/auth/magic_link/text.t
Normal file
@@ -0,0 +1,2 @@
|
||||
Magic link with this link:
|
||||
{{host}}/api/auth/magic-link/{{token}}
|
||||
13
src/mailers/auth/welcome/html.t
Normal file
13
src/mailers/auth/welcome/html.t
Normal file
@@ -0,0 +1,13 @@
|
||||
;<html>
|
||||
|
||||
<body>
|
||||
Dear {{name}},
|
||||
Welcome to Loco! You can now log in to your account.
|
||||
Before you get started, please verify your account by clicking the link below:
|
||||
<a href="{{domain}}/api/auth/verify/{{verifyToken}}">
|
||||
Verify Your Account
|
||||
</a>
|
||||
<p>Best regards,<br>The Loco Team</p>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
1
src/mailers/auth/welcome/subject.t
Normal file
1
src/mailers/auth/welcome/subject.t
Normal file
@@ -0,0 +1 @@
|
||||
Welcome {{name}}
|
||||
4
src/mailers/auth/welcome/text.t
Normal file
4
src/mailers/auth/welcome/text.t
Normal file
@@ -0,0 +1,4 @@
|
||||
Welcome {{name}}, you can now log in.
|
||||
Verify your account with the link below:
|
||||
|
||||
{{domain}}/api/auth/verify/{{verifyToken}}
|
||||
1
src/mailers/mod.rs
Normal file
1
src/mailers/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod auth;
|
||||
51
src/models/_entities/audio_albums.rs
Normal file
51
src/models/_entities/audio_albums.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "audio_albums")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub title: String,
|
||||
#[sea_orm(unique)]
|
||||
pub slug: String,
|
||||
#[sea_orm(column_type = "Text", nullable)]
|
||||
pub description: Option<String>,
|
||||
pub cover_image_id: Option<String>,
|
||||
pub artist: Option<String>,
|
||||
pub release_date: Option<Date>,
|
||||
pub published: bool,
|
||||
pub uploader_id: i32,
|
||||
pub view_count: i32,
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
pub published_at: Option<DateTimeWithTimeZone>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::audio_tracks::Entity")]
|
||||
AudioTracks,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::UploaderId",
|
||||
to = "super::users::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Users,
|
||||
}
|
||||
|
||||
impl Related<super::audio_tracks::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AudioTracks.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Users.def()
|
||||
}
|
||||
}
|
||||
37
src/models/_entities/audio_tags.rs
Normal file
37
src/models/_entities/audio_tags.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "audio_tags")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
#[sea_orm(unique)]
|
||||
pub name: String,
|
||||
#[sea_orm(unique)]
|
||||
pub slug: String,
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::audio_track_tags::Entity")]
|
||||
AudioTrackTags,
|
||||
}
|
||||
|
||||
impl Related<super::audio_track_tags::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AudioTrackTags.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::audio_tracks::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
super::audio_track_tags::Relation::AudioTracks.def()
|
||||
}
|
||||
fn via() -> Option<RelationDef> {
|
||||
Some(super::audio_track_tags::Relation::AudioTags.def().rev())
|
||||
}
|
||||
}
|
||||
46
src/models/_entities/audio_track_tags.rs
Normal file
46
src/models/_entities/audio_track_tags.rs
Normal file
@@ -0,0 +1,46 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "audio_track_tags")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub track_id: Uuid,
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub tag_id: Uuid,
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::audio_tags::Entity",
|
||||
from = "Column::TagId",
|
||||
to = "super::audio_tags::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
AudioTags,
|
||||
#[sea_orm(
|
||||
belongs_to = "super::audio_tracks::Entity",
|
||||
from = "Column::TrackId",
|
||||
to = "super::audio_tracks::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
AudioTracks,
|
||||
}
|
||||
|
||||
impl Related<super::audio_tags::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AudioTags.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::audio_tracks::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AudioTracks.def()
|
||||
}
|
||||
}
|
||||
58
src/models/_entities/audio_tracks.rs
Normal file
58
src/models/_entities/audio_tracks.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "audio_tracks")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub album_id: Option<Uuid>,
|
||||
pub title: String,
|
||||
pub slug: String,
|
||||
pub audio_file_id: String,
|
||||
pub track_number: Option<i32>,
|
||||
pub duration: Option<i32>,
|
||||
pub featured: bool,
|
||||
pub published: bool,
|
||||
pub play_count: i32,
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
pub published_at: Option<DateTimeWithTimeZone>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::audio_albums::Entity",
|
||||
from = "Column::AlbumId",
|
||||
to = "super::audio_albums::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "SetNull"
|
||||
)]
|
||||
AudioAlbums,
|
||||
#[sea_orm(has_many = "super::audio_track_tags::Entity")]
|
||||
AudioTrackTags,
|
||||
}
|
||||
|
||||
impl Related<super::audio_albums::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AudioAlbums.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::audio_track_tags::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AudioTrackTags.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::audio_tags::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
super::audio_track_tags::Relation::AudioTags.def()
|
||||
}
|
||||
fn via() -> Option<RelationDef> {
|
||||
Some(super::audio_track_tags::Relation::AudioTracks.def().rev())
|
||||
}
|
||||
}
|
||||
40
src/models/_entities/audit_logs.rs
Normal file
40
src/models/_entities/audit_logs.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "audit_logs")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub admin_user_id: i32,
|
||||
pub action: String,
|
||||
pub target_type: Option<String>,
|
||||
pub target_id: Option<Uuid>,
|
||||
#[sea_orm(column_type = "JsonBinary", nullable)]
|
||||
pub details: Option<Json>,
|
||||
#[sea_orm(column_type = "custom(\"inet\")", nullable)]
|
||||
pub ip_address: Option<String>,
|
||||
#[sea_orm(column_type = "Text", nullable)]
|
||||
pub user_agent: Option<String>,
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::AdminUserId",
|
||||
to = "super::users::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Users,
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Users.def()
|
||||
}
|
||||
}
|
||||
42
src/models/_entities/blog_articles.rs
Normal file
42
src/models/_entities/blog_articles.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "blog_articles")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
pub title: String,
|
||||
#[sea_orm(unique)]
|
||||
pub slug: String,
|
||||
#[sea_orm(column_type = "Text")]
|
||||
pub content: String,
|
||||
pub excerpt: Option<String>,
|
||||
pub published: bool,
|
||||
pub author_id: i32,
|
||||
pub featured_image_id: Option<String>,
|
||||
pub view_count: i32,
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
pub published_at: Option<DateTimeWithTimeZone>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(
|
||||
belongs_to = "super::users::Entity",
|
||||
from = "Column::AuthorId",
|
||||
to = "super::users::Column::Id",
|
||||
on_update = "Cascade",
|
||||
on_delete = "Cascade"
|
||||
)]
|
||||
Users,
|
||||
}
|
||||
|
||||
impl Related<super::users::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::Users.def()
|
||||
}
|
||||
}
|
||||
12
src/models/_entities/mod.rs
Normal file
12
src/models/_entities/mod.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
pub mod prelude;
|
||||
|
||||
pub mod audio_albums;
|
||||
pub mod audio_tags;
|
||||
pub mod audio_track_tags;
|
||||
pub mod audio_tracks;
|
||||
pub mod audit_logs;
|
||||
pub mod blog_articles;
|
||||
pub mod site_pages;
|
||||
pub mod users;
|
||||
10
src/models/_entities/prelude.rs
Normal file
10
src/models/_entities/prelude.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
pub use super::audio_albums::Entity as AudioAlbums;
|
||||
pub use super::audio_tags::Entity as AudioTags;
|
||||
pub use super::audio_track_tags::Entity as AudioTrackTags;
|
||||
pub use super::audio_tracks::Entity as AudioTracks;
|
||||
pub use super::audit_logs::Entity as AuditLogs;
|
||||
pub use super::blog_articles::Entity as BlogArticles;
|
||||
pub use super::site_pages::Entity as SitePages;
|
||||
pub use super::users::Entity as Users;
|
||||
21
src/models/_entities/site_pages.rs
Normal file
21
src/models/_entities/site_pages.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "site_pages")]
|
||||
pub struct Model {
|
||||
#[sea_orm(primary_key, auto_increment = false)]
|
||||
pub id: Uuid,
|
||||
#[sea_orm(unique)]
|
||||
pub slug: String,
|
||||
pub title: String,
|
||||
#[sea_orm(column_type = "Text")]
|
||||
pub content: String,
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {}
|
||||
56
src/models/_entities/users.rs
Normal file
56
src/models/_entities/users.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.20
|
||||
|
||||
use sea_orm::entity::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
||||
#[sea_orm(table_name = "users")]
|
||||
pub struct Model {
|
||||
pub created_at: DateTimeWithTimeZone,
|
||||
pub updated_at: DateTimeWithTimeZone,
|
||||
#[sea_orm(primary_key)]
|
||||
pub id: i32,
|
||||
pub pid: Uuid,
|
||||
#[sea_orm(unique)]
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
#[sea_orm(unique)]
|
||||
pub api_key: String,
|
||||
pub name: String,
|
||||
pub reset_token: Option<String>,
|
||||
pub reset_sent_at: Option<DateTimeWithTimeZone>,
|
||||
pub email_verification_token: Option<String>,
|
||||
pub email_verification_sent_at: Option<DateTimeWithTimeZone>,
|
||||
pub email_verified_at: Option<DateTimeWithTimeZone>,
|
||||
pub magic_link_token: Option<String>,
|
||||
pub magic_link_expiration: Option<DateTimeWithTimeZone>,
|
||||
pub theme: String,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||
pub enum Relation {
|
||||
#[sea_orm(has_many = "super::audio_albums::Entity")]
|
||||
AudioAlbums,
|
||||
#[sea_orm(has_many = "super::audit_logs::Entity")]
|
||||
AuditLogs,
|
||||
#[sea_orm(has_many = "super::blog_articles::Entity")]
|
||||
BlogArticles,
|
||||
}
|
||||
|
||||
impl Related<super::audio_albums::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AudioAlbums.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::audit_logs::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::AuditLogs.def()
|
||||
}
|
||||
}
|
||||
|
||||
impl Related<super::blog_articles::Entity> for Entity {
|
||||
fn to() -> RelationDef {
|
||||
Relation::BlogArticles.def()
|
||||
}
|
||||
}
|
||||
28
src/models/audio_albums.rs
Normal file
28
src/models/audio_albums.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
pub use super::_entities::audio_albums::{ActiveModel, Entity, Model};
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub type AudioAlbums = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
if !insert && self.updated_at.is_unchanged() {
|
||||
let mut this = self;
|
||||
this.updated_at = sea_orm::ActiveValue::Set(chrono::Utc::now().into());
|
||||
Ok(this)
|
||||
} else {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// implement your read-oriented logic here
|
||||
impl Model {}
|
||||
|
||||
// implement your write-oriented logic here
|
||||
impl ActiveModel {}
|
||||
|
||||
// implement your custom finders, selectors oriented logic here
|
||||
impl Entity {}
|
||||
22
src/models/audio_tags.rs
Normal file
22
src/models/audio_tags.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
pub use super::_entities::audio_tags::{ActiveModel, Entity, Model};
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub type AudioTags = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, _insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
// implement your read-oriented logic here
|
||||
impl Model {}
|
||||
|
||||
// implement your write-oriented logic here
|
||||
impl ActiveModel {}
|
||||
|
||||
// implement your custom finders, selectors oriented logic here
|
||||
impl Entity {}
|
||||
22
src/models/audio_track_tags.rs
Normal file
22
src/models/audio_track_tags.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
pub use super::_entities::audio_track_tags::{ActiveModel, Entity, Model};
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub type AudioTrackTags = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, _insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
// implement your read-oriented logic here
|
||||
impl Model {}
|
||||
|
||||
// implement your write-oriented logic here
|
||||
impl ActiveModel {}
|
||||
|
||||
// implement your custom finders, selectors oriented logic here
|
||||
impl Entity {}
|
||||
28
src/models/audio_tracks.rs
Normal file
28
src/models/audio_tracks.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
pub use super::_entities::audio_tracks::{ActiveModel, Entity, Model};
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub type AudioTracks = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
if !insert && self.updated_at.is_unchanged() {
|
||||
let mut this = self;
|
||||
this.updated_at = sea_orm::ActiveValue::Set(chrono::Utc::now().into());
|
||||
Ok(this)
|
||||
} else {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// implement your read-oriented logic here
|
||||
impl Model {}
|
||||
|
||||
// implement your write-oriented logic here
|
||||
impl ActiveModel {}
|
||||
|
||||
// implement your custom finders, selectors oriented logic here
|
||||
impl Entity {}
|
||||
22
src/models/audit_logs.rs
Normal file
22
src/models/audit_logs.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
pub use super::_entities::audit_logs::{ActiveModel, Entity, Model};
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub type AuditLogs = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, _insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
// implement your read-oriented logic here
|
||||
impl Model {}
|
||||
|
||||
// implement your write-oriented logic here
|
||||
impl ActiveModel {}
|
||||
|
||||
// implement your custom finders, selectors oriented logic here
|
||||
impl Entity {}
|
||||
28
src/models/blog_articles.rs
Normal file
28
src/models/blog_articles.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
pub use super::_entities::blog_articles::{ActiveModel, Entity, Model};
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub type BlogArticles = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
if !insert && self.updated_at.is_unchanged() {
|
||||
let mut this = self;
|
||||
this.updated_at = sea_orm::ActiveValue::Set(chrono::Utc::now().into());
|
||||
Ok(this)
|
||||
} else {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// implement your read-oriented logic here
|
||||
impl Model {}
|
||||
|
||||
// implement your write-oriented logic here
|
||||
impl ActiveModel {}
|
||||
|
||||
// implement your custom finders, selectors oriented logic here
|
||||
impl Entity {}
|
||||
9
src/models/mod.rs
Normal file
9
src/models/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
pub mod _entities;
|
||||
pub mod audio_albums;
|
||||
pub mod audio_tags;
|
||||
pub mod audio_track_tags;
|
||||
pub mod audio_tracks;
|
||||
pub mod audit_logs;
|
||||
pub mod blog_articles;
|
||||
pub mod site_pages;
|
||||
pub mod users;
|
||||
23
src/models/site_pages.rs
Normal file
23
src/models/site_pages.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
pub use super::_entities::site_pages::{ActiveModel, Entity, Model};
|
||||
use sea_orm::entity::prelude::*;
|
||||
pub type SitePages = Entity;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, insert: bool) -> std::result::Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
if !insert && self.updated_at.is_unchanged() {
|
||||
let mut this = self;
|
||||
this.updated_at = sea_orm::ActiveValue::Set(chrono::Utc::now().into());
|
||||
Ok(this)
|
||||
} else {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Model {}
|
||||
impl ActiveModel {}
|
||||
impl Entity {}
|
||||
369
src/models/users.rs
Normal file
369
src/models/users.rs
Normal file
@@ -0,0 +1,369 @@
|
||||
use async_trait::async_trait;
|
||||
use chrono::{offset::Local, Duration};
|
||||
use loco_rs::{auth::jwt, hash, prelude::*};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Map;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub use super::_entities::users::{self, ActiveModel, Entity, Model};
|
||||
|
||||
pub const MAGIC_LINK_LENGTH: i8 = 32;
|
||||
pub const MAGIC_LINK_EXPIRATION_MIN: i8 = 5;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct LoginParams {
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct RegisterParams {
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Validate, Deserialize)]
|
||||
pub struct Validator {
|
||||
#[validate(length(min = 2, message = "Name must be at least 2 characters long."))]
|
||||
pub name: String,
|
||||
#[validate(email(message = "invalid email"))]
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
impl Validatable for ActiveModel {
|
||||
fn validator(&self) -> Box<dyn Validate> {
|
||||
Box::new(Validator {
|
||||
name: self.name.as_ref().to_owned(),
|
||||
email: self.email.as_ref().to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl ActiveModelBehavior for super::_entities::users::ActiveModel {
|
||||
async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
|
||||
where
|
||||
C: ConnectionTrait,
|
||||
{
|
||||
self.validate()?;
|
||||
if insert {
|
||||
let mut this = self;
|
||||
this.pid = ActiveValue::Set(Uuid::new_v4());
|
||||
this.api_key = ActiveValue::Set(format!("lo-{}", Uuid::new_v4()));
|
||||
Ok(this)
|
||||
} else {
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Authenticable for Model {
|
||||
async fn find_by_api_key(db: &DatabaseConnection, api_key: &str) -> ModelResult<Self> {
|
||||
let user = users::Entity::find()
|
||||
.filter(
|
||||
model::query::condition()
|
||||
.eq(users::Column::ApiKey, api_key)
|
||||
.build(),
|
||||
)
|
||||
.one(db)
|
||||
.await?;
|
||||
user.ok_or_else(|| ModelError::EntityNotFound)
|
||||
}
|
||||
|
||||
async fn find_by_claims_key(db: &DatabaseConnection, claims_key: &str) -> ModelResult<Self> {
|
||||
Self::find_by_pid(db, claims_key).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Model {
|
||||
/// finds a user by the provided email
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When could not find user by the given token or DB query error
|
||||
pub async fn find_by_email(db: &DatabaseConnection, email: &str) -> ModelResult<Self> {
|
||||
let user = users::Entity::find()
|
||||
.filter(
|
||||
model::query::condition()
|
||||
.eq(users::Column::Email, email)
|
||||
.build(),
|
||||
)
|
||||
.one(db)
|
||||
.await?;
|
||||
user.ok_or_else(|| ModelError::EntityNotFound)
|
||||
}
|
||||
|
||||
/// finds a user by the provided verification token
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When could not find user by the given token or DB query error
|
||||
pub async fn find_by_verification_token(
|
||||
db: &DatabaseConnection,
|
||||
token: &str,
|
||||
) -> ModelResult<Self> {
|
||||
let user = users::Entity::find()
|
||||
.filter(
|
||||
model::query::condition()
|
||||
.eq(users::Column::EmailVerificationToken, token)
|
||||
.build(),
|
||||
)
|
||||
.one(db)
|
||||
.await?;
|
||||
user.ok_or_else(|| ModelError::EntityNotFound)
|
||||
}
|
||||
|
||||
/// finds a user by the magic token and verify and token expiration
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When could not find user by the given token or DB query error ot token expired
|
||||
pub async fn find_by_magic_token(db: &DatabaseConnection, token: &str) -> ModelResult<Self> {
|
||||
let user = users::Entity::find()
|
||||
.filter(
|
||||
query::condition()
|
||||
.eq(users::Column::MagicLinkToken, token)
|
||||
.build(),
|
||||
)
|
||||
.one(db)
|
||||
.await?;
|
||||
|
||||
let user = user.ok_or_else(|| ModelError::EntityNotFound)?;
|
||||
if let Some(expired_at) = user.magic_link_expiration {
|
||||
if expired_at >= Local::now() {
|
||||
Ok(user)
|
||||
} else {
|
||||
tracing::debug!(
|
||||
user_pid = user.pid.to_string(),
|
||||
token_expiration = expired_at.to_string(),
|
||||
"magic token expired for the user."
|
||||
);
|
||||
Err(ModelError::msg("magic token expired"))
|
||||
}
|
||||
} else {
|
||||
tracing::error!(
|
||||
user_pid = user.pid.to_string(),
|
||||
"magic link expiration time not exists"
|
||||
);
|
||||
Err(ModelError::msg("expiration token not exists"))
|
||||
}
|
||||
}
|
||||
|
||||
/// finds a user by the provided reset token
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When could not find user by the given token or DB query error
|
||||
pub async fn find_by_reset_token(db: &DatabaseConnection, token: &str) -> ModelResult<Self> {
|
||||
let user = users::Entity::find()
|
||||
.filter(
|
||||
model::query::condition()
|
||||
.eq(users::Column::ResetToken, token)
|
||||
.build(),
|
||||
)
|
||||
.one(db)
|
||||
.await?;
|
||||
user.ok_or_else(|| ModelError::EntityNotFound)
|
||||
}
|
||||
|
||||
/// finds a user by the provided pid
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When could not find user or DB query error
|
||||
pub async fn find_by_pid(db: &DatabaseConnection, pid: &str) -> ModelResult<Self> {
|
||||
let parse_uuid = Uuid::parse_str(pid).map_err(|e| ModelError::Any(e.into()))?;
|
||||
let user = users::Entity::find()
|
||||
.filter(
|
||||
model::query::condition()
|
||||
.eq(users::Column::Pid, parse_uuid)
|
||||
.build(),
|
||||
)
|
||||
.one(db)
|
||||
.await?;
|
||||
user.ok_or_else(|| ModelError::EntityNotFound)
|
||||
}
|
||||
|
||||
/// finds a user by the provided api key
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When could not find user by the given token or DB query error
|
||||
pub async fn find_by_api_key(db: &DatabaseConnection, api_key: &str) -> ModelResult<Self> {
|
||||
let user = users::Entity::find()
|
||||
.filter(
|
||||
model::query::condition()
|
||||
.eq(users::Column::ApiKey, api_key)
|
||||
.build(),
|
||||
)
|
||||
.one(db)
|
||||
.await?;
|
||||
user.ok_or_else(|| ModelError::EntityNotFound)
|
||||
}
|
||||
|
||||
/// Verifies whether the provided plain password matches the hashed password
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// when could not verify password
|
||||
#[must_use]
|
||||
pub fn verify_password(&self, password: &str) -> bool {
|
||||
hash::verify_password(password, &self.password)
|
||||
}
|
||||
|
||||
/// Asynchronously creates a user with a password and saves it to the
|
||||
/// database.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// When could not save the user into the DB
|
||||
pub async fn create_with_password(
|
||||
db: &DatabaseConnection,
|
||||
params: &RegisterParams,
|
||||
) -> ModelResult<Self> {
|
||||
let txn = db.begin().await?;
|
||||
|
||||
if users::Entity::find()
|
||||
.filter(
|
||||
model::query::condition()
|
||||
.eq(users::Column::Email, ¶ms.email)
|
||||
.build(),
|
||||
)
|
||||
.one(&txn)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Err(ModelError::EntityAlreadyExists {});
|
||||
}
|
||||
|
||||
let password_hash =
|
||||
hash::hash_password(¶ms.password).map_err(|e| ModelError::Any(e.into()))?;
|
||||
let user = users::ActiveModel {
|
||||
email: ActiveValue::set(params.email.to_string()),
|
||||
password: ActiveValue::set(password_hash),
|
||||
name: ActiveValue::set(params.name.to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
.insert(&txn)
|
||||
.await?;
|
||||
|
||||
txn.commit().await?;
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
/// Creates a JWT
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// when could not convert user claims to jwt token
|
||||
pub fn generate_jwt(&self, secret: &str, expiration: u64) -> ModelResult<String> {
|
||||
jwt::JWT::new(secret)
|
||||
.generate_token(expiration, self.pid.to_string(), Map::new())
|
||||
.map_err(ModelError::from)
|
||||
}
|
||||
}
|
||||
|
||||
impl ActiveModel {
|
||||
/// Sets the email verification information for the user and
|
||||
/// updates it in the database.
|
||||
///
|
||||
/// This method is used to record the timestamp when the email verification
|
||||
/// was sent and generate a unique verification token for the user.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// when has DB query error
|
||||
pub async fn set_email_verification_sent(
|
||||
mut self,
|
||||
db: &DatabaseConnection,
|
||||
) -> ModelResult<Model> {
|
||||
self.email_verification_sent_at = ActiveValue::set(Some(Local::now().into()));
|
||||
self.email_verification_token = ActiveValue::Set(Some(Uuid::new_v4().to_string()));
|
||||
self.update(db).await.map_err(ModelError::from)
|
||||
}
|
||||
|
||||
/// Sets the information for a reset password request,
|
||||
/// generates a unique reset password token, and updates it in the
|
||||
/// database.
|
||||
///
|
||||
/// This method records the timestamp when the reset password token is sent
|
||||
/// and generates a unique token for the user.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// when has DB query error
|
||||
pub async fn set_forgot_password_sent(mut self, db: &DatabaseConnection) -> ModelResult<Model> {
|
||||
self.reset_sent_at = ActiveValue::set(Some(Local::now().into()));
|
||||
self.reset_token = ActiveValue::Set(Some(Uuid::new_v4().to_string()));
|
||||
self.update(db).await.map_err(ModelError::from)
|
||||
}
|
||||
|
||||
/// Records the verification time when a user verifies their
|
||||
/// email and updates it in the database.
|
||||
///
|
||||
/// This method sets the timestamp when the user successfully verifies their
|
||||
/// email.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// when has DB query error
|
||||
pub async fn verified(mut self, db: &DatabaseConnection) -> ModelResult<Model> {
|
||||
self.email_verified_at = ActiveValue::set(Some(Local::now().into()));
|
||||
self.update(db).await.map_err(ModelError::from)
|
||||
}
|
||||
|
||||
/// Resets the current user password with a new password and
|
||||
/// updates it in the database.
|
||||
///
|
||||
/// This method hashes the provided password and sets it as the new password
|
||||
/// for the user.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// when has DB query error or could not hashed the given password
|
||||
pub async fn reset_password(
|
||||
mut self,
|
||||
db: &DatabaseConnection,
|
||||
password: &str,
|
||||
) -> ModelResult<Model> {
|
||||
self.password =
|
||||
ActiveValue::set(hash::hash_password(password).map_err(|e| ModelError::Any(e.into()))?);
|
||||
self.reset_token = ActiveValue::Set(None);
|
||||
self.reset_sent_at = ActiveValue::Set(None);
|
||||
self.update(db).await.map_err(ModelError::from)
|
||||
}
|
||||
|
||||
/// Creates a magic link token for passwordless authentication.
|
||||
///
|
||||
/// Generates a random token with a specified length and sets an expiration time
|
||||
/// for the magic link. This method is used to initiate the magic link authentication flow.
|
||||
///
|
||||
/// # Errors
|
||||
/// - Returns an error if database update fails
|
||||
pub async fn create_magic_link(mut self, db: &DatabaseConnection) -> ModelResult<Model> {
|
||||
let random_str = hash::random_string(MAGIC_LINK_LENGTH as usize);
|
||||
let expired = Local::now() + Duration::minutes(MAGIC_LINK_EXPIRATION_MIN.into());
|
||||
|
||||
self.magic_link_token = ActiveValue::set(Some(random_str));
|
||||
self.magic_link_expiration = ActiveValue::set(Some(expired.into()));
|
||||
self.update(db).await.map_err(ModelError::from)
|
||||
}
|
||||
|
||||
/// Verifies and invalidates the magic link after successful authentication.
|
||||
///
|
||||
/// Clears the magic link token and expiration time after the user has
|
||||
/// successfully authenticated using the magic link.
|
||||
///
|
||||
/// # Errors
|
||||
/// - Returns an error if database update fails
|
||||
pub async fn clear_magic_link(mut self, db: &DatabaseConnection) -> ModelResult<Model> {
|
||||
self.magic_link_token = ActiveValue::set(None);
|
||||
self.magic_link_expiration = ActiveValue::set(None);
|
||||
self.update(db).await.map_err(ModelError::from)
|
||||
}
|
||||
}
|
||||
1
src/tasks/mod.rs
Normal file
1
src/tasks/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
45
src/views/auth.rs
Normal file
45
src/views/auth.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::_entities::users;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct LoginResponse {
|
||||
pub token: String,
|
||||
pub pid: String,
|
||||
pub name: String,
|
||||
pub is_verified: bool,
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
impl LoginResponse {
|
||||
#[must_use]
|
||||
pub fn new(user: &users::Model, token: &String, is_admin: bool) -> Self {
|
||||
Self {
|
||||
token: token.to_string(),
|
||||
pid: user.pid.to_string(),
|
||||
name: user.name.clone(),
|
||||
is_verified: user.email_verified_at.is_some(),
|
||||
is_admin,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct CurrentResponse {
|
||||
pub pid: String,
|
||||
pub name: String,
|
||||
pub email: String,
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
impl CurrentResponse {
|
||||
#[must_use]
|
||||
pub fn new(user: &users::Model, is_admin: bool) -> Self {
|
||||
Self {
|
||||
pid: user.pid.to_string(),
|
||||
name: user.name.clone(),
|
||||
email: user.email.clone(),
|
||||
is_admin,
|
||||
}
|
||||
}
|
||||
}
|
||||
1
src/views/mod.rs
Normal file
1
src/views/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod auth;
|
||||
23
src/workers/downloader.rs
Normal file
23
src/workers/downloader.rs
Normal file
@@ -0,0 +1,23 @@
|
||||
use loco_rs::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub struct DownloadWorker {
|
||||
pub ctx: AppContext,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Serialize)]
|
||||
pub struct DownloadWorkerArgs {
|
||||
pub user_guid: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundWorker<DownloadWorkerArgs> for DownloadWorker {
|
||||
fn build(ctx: &AppContext) -> Self {
|
||||
Self { ctx: ctx.clone() }
|
||||
}
|
||||
async fn perform(&self, _args: DownloadWorkerArgs) -> Result<()> {
|
||||
// TODO: Some actual work goes here...
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
1
src/workers/mod.rs
Normal file
1
src/workers/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod downloader;
|
||||
Reference in New Issue
Block a user