233 lines
8.6 KiB
Rust
233 lines
8.6 KiB
Rust
//! Promo codes. An admin makes a batch for one package; a logged-in user
|
||||
|
|
//! redeems a code once and gets that package (an order with source `promo`).
|
|||
|
|
//! Unused codes can be withdrawn. Failed redemptions are rate limited per
|
|||
|
|
//! user, so codes cannot be guessed.
|
|||
|
|
|
|||
|
|
use axum::Json;
|
|||
|
|
use axum::extract::{Path, Query, State};
|
|||
|
|
use axum::http::StatusCode;
|
|||
|
|
use axum_extra::extract::WithRejection;
|
|||
|
|
use serde::Deserialize;
|
|||
|
|
use serde_json::{Value, json};
|
|||
|
|
use time::OffsetDateTime;
|
|||
|
|
use uuid::Uuid;
|
|||
|
|
|
|||
|
|
use super::payments::holdings;
|
|||
|
|
use super::{Body, IdPath, St};
|
|||
|
|
use crate::auth::{AdminUser, AuthUser};
|
|||
|
|
use crate::error::{ApiError, ApiResult};
|
|||
|
|
use crate::packages::{self, Source};
|
|||
|
|
use crate::views::{rfc3339, rfc3339_opt};
|
|||
|
|
|
|||
|
|
/// Characters of a code (12 × ~5 bits: not guessable within the rate limit).
|
|||
|
|
const CODE_LEN: usize = 12;
|
|||
|
|
const MAX_BATCH: i64 = 500;
|
|||
|
|
|
|||
|
|
/// `ABCD-EFGH-JKLM`: the stored code in groups of four.
|
|||
|
|
fn display(code: &str) -> String {
|
|||
|
|
code.as_bytes().chunks(4).map(|c| String::from_utf8_lossy(c).into_owned()).collect::<Vec<_>>().join("-")
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// What the user typed, as stored: upper case, without spaces and dashes.
|
|||
|
|
fn normalize(input: &str) -> String {
|
|||
|
|
input.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_uppercase()).collect()
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[derive(Deserialize)]
|
|||
|
|
#[serde(deny_unknown_fields)]
|
|||
|
|
pub struct NewCodes {
|
|||
|
|
package: String,
|
|||
|
|
count: i64,
|
|||
|
|
note: Option<String>,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// Admin: makes `count` new codes for a package.
|
|||
|
|
pub async fn create(
|
|||
|
|
State(state): St,
|
|||
|
|
admin: AdminUser,
|
|||
|
|
WithRejection(Json(req), _): Body<NewCodes>,
|
|||
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
|||
|
|
let package = packages::find(&req.package).ok_or(ApiError::NotFound("package"))?;
|
|||
|
|
if !(1..=MAX_BATCH).contains(&req.count) {
|
|||
|
|
return Err(ApiError::BadRequest(format!("count must be 1 to {MAX_BATCH}")));
|
|||
|
|
}
|
|||
|
|
let note = req.note.map(|n| n.trim().chars().take(200).collect::<String>()).filter(|n| !n.is_empty());
|
|||
|
|
let mut tx = state.db.begin().await?;
|
|||
|
|
let mut codes = Vec::new();
|
|||
|
|
while (codes.len() as i64) < req.count {
|
|||
|
|
let code = db::random_code(CODE_LEN);
|
|||
|
|
// A clash is practically impossible; skipped if it happens.
|
|||
|
|
let inserted = sqlx::query(
|
|||
|
|
"INSERT INTO promo_codes (id, code, package, note, created_by) VALUES ($1, $2, $3, $4, $5) \
|
|||
|
|
ON CONFLICT (code) DO NOTHING",
|
|||
|
|
)
|
|||
|
|
.bind(Uuid::now_v7())
|
|||
|
|
.bind(&code)
|
|||
|
|
.bind(package.id)
|
|||
|
|
.bind(¬e)
|
|||
|
|
.bind(admin.0.id())
|
|||
|
|
.execute(&mut *tx)
|
|||
|
|
.await?
|
|||
|
|
.rows_affected();
|
|||
|
|
if inserted == 1 {
|
|||
|
|
codes.push(display(&code));
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
tx.commit().await?;
|
|||
|
|
tracing::info!(admin = %admin.0.id(), package = package.id, count = codes.len(), "promo codes created");
|
|||
|
|
Ok((StatusCode::CREATED, Json(json!({ "package": package.id, "note": note, "codes": codes }))))
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[derive(Deserialize)]
|
|||
|
|
#[serde(deny_unknown_fields)]
|
|||
|
|
pub struct CodeQuery {
|
|||
|
|
/// `unused` (default), `used`, `revoked` or `all`.
|
|||
|
|
status: Option<String>,
|
|||
|
|
package: Option<String>,
|
|||
|
|
/// Part of the code, the note or the redeemer's e-mail.
|
|||
|
|
q: Option<String>,
|
|||
|
|
limit: Option<i64>,
|
|||
|
|
offset: Option<i64>,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
type Row = (
|
|||
|
|
Uuid,
|
|||
|
|
String,
|
|||
|
|
String,
|
|||
|
|
Option<String>,
|
|||
|
|
OffsetDateTime,
|
|||
|
|
Option<OffsetDateTime>,
|
|||
|
|
Option<OffsetDateTime>,
|
|||
|
|
Option<String>,
|
|||
|
|
Option<String>,
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
/// Admin: the codes, newest first, filtered.
|
|||
|
|
pub async fn list(
|
|||
|
|
State(state): St,
|
|||
|
|
_admin: AdminUser,
|
|||
|
|
WithRejection(Query(query), _): WithRejection<Query<CodeQuery>, ApiError>,
|
|||
|
|
) -> ApiResult<Json<Value>> {
|
|||
|
|
let status = query.status.as_deref().unwrap_or("unused");
|
|||
|
|
let condition = match status {
|
|||
|
|
"unused" => "p.redeemed_at IS NULL AND p.revoked_at IS NULL",
|
|||
|
|
"used" => "p.redeemed_at IS NOT NULL",
|
|||
|
|
"revoked" => "p.revoked_at IS NOT NULL",
|
|||
|
|
"all" => "true",
|
|||
|
|
other => return Err(ApiError::BadRequest(format!("unknown status '{other}'"))),
|
|||
|
|
};
|
|||
|
|
let limit = query.limit.unwrap_or(100).clamp(1, 500);
|
|||
|
|
let offset = query.offset.unwrap_or(0).max(0);
|
|||
|
|
let package = query.package.filter(|p| !p.is_empty());
|
|||
|
|
let search = query.q.map(|q| q.trim().to_string()).filter(|q| !q.is_empty());
|
|||
|
|
// A code is searched for without its dashes.
|
|||
|
|
let code_search = search.as_deref().map(normalize).filter(|c| !c.is_empty());
|
|||
|
|
let filter = format!(
|
|||
|
|
"FROM promo_codes p LEFT JOIN users u ON u.id = p.redeemed_by \
|
|||
|
|
WHERE {condition} AND ($1::text IS NULL OR p.package = $1) \
|
|||
|
|
AND ($2::text IS NULL OR p.note ILIKE '%' || $2 || '%' OR u.email ILIKE '%' || $2 || '%' \
|
|||
|
|
OR ($3::text IS NOT NULL AND p.code LIKE '%' || $3 || '%'))"
|
|||
|
|
);
|
|||
|
|
let rows: Vec<Row> = sqlx::query_as(&format!(
|
|||
|
|
"SELECT p.id, p.code, p.package, p.note, p.created_at, p.redeemed_at, p.revoked_at, u.email, u.display_name \
|
|||
|
|
{filter} ORDER BY p.created_at DESC, p.id DESC LIMIT $4 OFFSET $5"
|
|||
|
|
))
|
|||
|
|
.bind(&package)
|
|||
|
|
.bind(&search)
|
|||
|
|
.bind(&code_search)
|
|||
|
|
.bind(limit)
|
|||
|
|
.bind(offset)
|
|||
|
|
.fetch_all(&state.db)
|
|||
|
|
.await?;
|
|||
|
|
let total: i64 = sqlx::query_scalar(&format!("SELECT count(*) {filter}"))
|
|||
|
|
.bind(&package)
|
|||
|
|
.bind(&search)
|
|||
|
|
.bind(&code_search)
|
|||
|
|
.fetch_one(&state.db)
|
|||
|
|
.await?;
|
|||
|
|
let codes: Vec<Value> = rows
|
|||
|
|
.into_iter()
|
|||
|
|
.map(|(id, code, package, note, created, redeemed, revoked, email, name)| {
|
|||
|
|
json!({
|
|||
|
|
"id": id,
|
|||
|
|
"code": display(&code),
|
|||
|
|
"package": package,
|
|||
|
|
"package_name": packages::find(&package).map(|p| p.name),
|
|||
|
|
"note": note,
|
|||
|
|
"created_at": rfc3339(created),
|
|||
|
|
"redeemed_at": rfc3339_opt(redeemed),
|
|||
|
|
"revoked_at": rfc3339_opt(revoked),
|
|||
|
|
"redeemed_by": email.map(|e| json!({ "email": e, "name": name })),
|
|||
|
|
})
|
|||
|
|
})
|
|||
|
|
.collect();
|
|||
|
|
Ok(Json(json!({ "codes": codes, "total": total, "status": status, "limit": limit, "offset": offset })))
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// Admin: withdraws an unused code.
|
|||
|
|
pub async fn revoke(State(state): St, _admin: AdminUser, WithRejection(Path(id), _): IdPath) -> ApiResult<StatusCode> {
|
|||
|
|
let result = sqlx::query(
|
|||
|
|
"UPDATE promo_codes SET revoked_at = now() WHERE id = $1 AND redeemed_at IS NULL AND revoked_at IS NULL",
|
|||
|
|
)
|
|||
|
|
.bind(id)
|
|||
|
|
.execute(&state.db)
|
|||
|
|
.await?;
|
|||
|
|
if result.rows_affected() == 0 {
|
|||
|
|
return Err(ApiError::conflict("promo_not_open", "Csak fel nem használt kódot lehet visszavonni."));
|
|||
|
|
}
|
|||
|
|
Ok(StatusCode::NO_CONTENT)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
#[derive(Deserialize)]
|
|||
|
|
#[serde(deny_unknown_fields)]
|
|||
|
|
pub struct Redeem {
|
|||
|
|
code: String,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// Redeems a code: the user gets its package. One use per code.
|
|||
|
|
pub async fn redeem(
|
|||
|
|
State(state): St,
|
|||
|
|
auth: AuthUser,
|
|||
|
|
WithRejection(Json(req), _): Body<Redeem>,
|
|||
|
|
) -> ApiResult<Json<Value>> {
|
|||
|
|
let key = format!("promo:{}", auth.id());
|
|||
|
|
state.login_limiter.check(&key)?;
|
|||
|
|
let code = normalize(&req.code);
|
|||
|
|
let mut tx = state.db.begin().await?;
|
|||
|
|
let found: Option<(Uuid, String, Option<OffsetDateTime>, Option<OffsetDateTime>)> =
|
|||
|
|
sqlx::query_as("SELECT id, package, redeemed_at, revoked_at FROM promo_codes WHERE code = $1 FOR UPDATE")
|
|||
|
|
.bind(&code)
|
|||
|
|
.fetch_optional(&mut *tx)
|
|||
|
|
.await?;
|
|||
|
|
let (id, package_id) = match found {
|
|||
|
|
Some((id, package, None, None)) => (id, package),
|
|||
|
|
Some((_, _, Some(_), _)) => {
|
|||
|
|
state.login_limiter.failed(&key);
|
|||
|
|
return Err(ApiError::conflict("promo_used", "Ezt a kódot már felhasználták."));
|
|||
|
|
}
|
|||
|
|
Some((_, _, _, Some(_))) => {
|
|||
|
|
state.login_limiter.failed(&key);
|
|||
|
|
return Err(ApiError::conflict("promo_revoked", "Ez a kód már nem érvényes."));
|
|||
|
|
}
|
|||
|
|
None => {
|
|||
|
|
state.login_limiter.failed(&key);
|
|||
|
|
return Err(ApiError::conflict("promo_unknown", "Nincs ilyen kód. Ellenőrizd, hogy pontosan írtad-e be."));
|
|||
|
|
}
|
|||
|
|
};
|
|||
|
|
let package = packages::find(&package_id).ok_or(ApiError::NotFound("package"))?;
|
|||
|
|
let note = format!("promo code {}", display(&code));
|
|||
|
|
let order = packages::grant(&mut tx, auth.id(), package, Source::Promo, None, Some(¬e)).await?;
|
|||
|
|
sqlx::query("UPDATE promo_codes SET redeemed_by = $2, redeemed_at = now(), order_id = $3 WHERE id = $1")
|
|||
|
|
.bind(id)
|
|||
|
|
.bind(auth.id())
|
|||
|
|
.bind(order)
|
|||
|
|
.execute(&mut *tx)
|
|||
|
|
.await?;
|
|||
|
|
tx.commit().await?;
|
|||
|
|
state.login_limiter.succeeded(&key);
|
|||
|
|
tracing::info!(user = %auth.id(), package = package.id, "promo code redeemed");
|
|||
|
|
let mut body = holdings(&state, &auth).await?;
|
|||
|
|
body["package"] = json!({ "id": package.id, "name": package.name });
|
|||
|
|
Ok(Json(body))
|
|||
|
|
}
|