···
-
use actix_web::{web, HttpResponse, Responder, HttpRequest};
-
use jsonwebtoken::{encode, Header, EncodingKey};use crate::{error::AppError, models::{AuthResponse, Claims, CreateLink, Link, LoginRequest, RegisterRequest, User, UserResponse}, AppState};
-
use argon2::{password_hash::{rand_core::OsRng, SaltString}, PasswordVerifier};
-
use lazy_static::lazy_static;
-
use argon2::{Argon2, PasswordHash, PasswordHasher};
use crate::auth::AuthenticatedUser;
static ref VALID_CODE_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_-]{1,32}$").unwrap();
···
payload: web::Json<CreateLink>,
) -> Result<impl Responder, AppError> {
tracing::debug!("Creating short URL with user_id: {}", user.user_id);
validate_url(&payload.url)?;
let short_code = if let Some(ref custom_code) = payload.custom_code {
validate_custom_code(custom_code)?;
tracing::debug!("Checking if custom code {} exists", custom_code);
// Check if code is already taken
-
if let Some(_) = sqlx::query_as::<_, Link>(
-
"SELECT * FROM links WHERE short_code = $1"
-
.fetch_optional(&state.db)
return Err(AppError::InvalidInput(
-
"Custom code already taken".to_string()
let mut tx = state.db.begin().await?;
tracing::debug!("Inserting new link with short_code: {}", short_code);
let link = sqlx::query_as::<_, Link>(
-
"INSERT INTO links (original_url, short_code, user_id) VALUES ($1, $2, $3) RETURNING *"
if let Some(ref source) = payload.source {
tracing::debug!("Adding click source: {}", source);
-
"INSERT INTO clicks (link_id, source) VALUES ($1, $2)"
Ok(HttpResponse::Created().json(link))
···
"Custom code must be 1-32 characters long and contain only letters, numbers, underscores, and hyphens".to_string()
// Add reserved words check
let reserved_words = ["api", "health", "admin", "static", "assets"];
if reserved_words.contains(&code.to_lowercase().as_str()) {
return Err(AppError::InvalidInput(
-
"This code is reserved and cannot be used".to_string()
···
return Err(AppError::InvalidInput("URL cannot be empty".to_string()));
if !url.starts_with("http://") && !url.starts_with("https://") {
-
return Err(AppError::InvalidInput("URL must start with http:// or https://".to_string()));
···
) -> Result<impl Responder, AppError> {
let short_code = path.into_inner();
// Extract query source if present
-
let query_source = req.uri()
.and_then(|q| web::Query::<std::collections::HashMap<String, String>>::from_query(q).ok())
.and_then(|params| params.get("source").cloned());
···
let mut tx = state.db.begin().await?;
let link = sqlx::query_as::<_, Link>(
-
"UPDATE links SET clicks = clicks + 1 WHERE short_code = $1 RETURNING *"
.fetch_optional(&mut *tx)
···
// Record click with both user agent and query source
-
let user_agent = req.headers()
.and_then(|h| h.to_str().ok())
-
"INSERT INTO clicks (link_id, source, query_source) VALUES ($1, $2, $3)"
Ok(HttpResponse::TemporaryRedirect()
.append_header(("Location", link.original_url))
None => Err(AppError::NotFound),
···
) -> Result<impl Responder, AppError> {
let links = sqlx::query_as::<_, Link>(
-
"SELECT * FROM links WHERE user_id = $1 ORDER BY created_at DESC"
···
Ok(HttpResponse::Ok().json(links))
-
pub async fn health_check(
-
state: web::Data<AppState>,
match sqlx::query("SELECT 1").execute(&state.db).await {
Ok(_) => HttpResponse::Ok().json("Healthy"),
Err(_) => HttpResponse::ServiceUnavailable().json("Database unavailable"),
···
fn generate_short_code() -> String {
let uuid = Uuid::new_v4();
encode(uuid.as_u128() as u64).chars().take(8).collect()
···
state: web::Data<AppState>,
payload: web::Json<RegisterRequest>,
) -> Result<impl Responder, AppError> {
-
let exists = sqlx::query!(
-
"SELECT id FROM users WHERE email = $1",
-
.fetch_optional(&state.db)
return Err(AppError::Auth("Email already registered".to_string()));
···
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
-
let password_hash = argon2.hash_password(payload.password.as_bytes(), &salt)
.map_err(|e| AppError::Auth(e.to_string()))?
···
-
&EncodingKey::from_secret(secret.as_bytes())
-
).map_err(|e| AppError::Auth(e.to_string()))?;
Ok(HttpResponse::Ok().json(AuthResponse {
···
state: web::Data<AppState>,
payload: web::Json<LoginRequest>,
) -> Result<impl Responder, AppError> {
-
let user = sqlx::query_as!(
-
"SELECT * FROM users WHERE email = $1",
-
.fetch_optional(&state.db)
-
.ok_or_else(|| AppError::Auth("Invalid credentials".to_string()))?;
let argon2 = Argon2::default();
-
let parsed_hash = PasswordHash::new(&user.password_hash)
-
.map_err(|e| AppError::Auth(e.to_string()))?;
-
if argon2.verify_password(payload.password.as_bytes(), &parsed_hash).is_err() {
return Err(AppError::Auth("Invalid credentials".to_string()));
···
-
&EncodingKey::from_secret(secret.as_bytes())
-
).map_err(|e| AppError::Auth(e.to_string()))?;
Ok(HttpResponse::Ok().json(AuthResponse {
···
···
use crate::auth::AuthenticatedUser;
+
AuthResponse, Claims, CreateLink, Link, LoginRequest, RegisterRequest, User, UserResponse,
+
use actix_web::{web, HttpRequest, HttpResponse, Responder};
+
password_hash::{rand_core::OsRng, SaltString},
+
use argon2::{Argon2, PasswordHash, PasswordHasher};
+
use jsonwebtoken::{encode, EncodingKey, Header};
+
use lazy_static::lazy_static;
static ref VALID_CODE_REGEX: Regex = Regex::new(r"^[a-zA-Z0-9_-]{1,32}$").unwrap();
···
payload: web::Json<CreateLink>,
) -> Result<impl Responder, AppError> {
tracing::debug!("Creating short URL with user_id: {}", user.user_id);
validate_url(&payload.url)?;
let short_code = if let Some(ref custom_code) = payload.custom_code {
validate_custom_code(custom_code)?;
tracing::debug!("Checking if custom code {} exists", custom_code);
// Check if code is already taken
+
if let Some(_) = sqlx::query_as::<_, Link>("SELECT * FROM links WHERE short_code = $1")
+
.fetch_optional(&state.db)
return Err(AppError::InvalidInput(
+
"Custom code already taken".to_string(),
let mut tx = state.db.begin().await?;
tracing::debug!("Inserting new link with short_code: {}", short_code);
let link = sqlx::query_as::<_, Link>(
+
"INSERT INTO links (original_url, short_code, user_id) VALUES ($1, $2, $3) RETURNING *",
if let Some(ref source) = payload.source {
tracing::debug!("Adding click source: {}", source);
+
sqlx::query("INSERT INTO clicks (link_id, source) VALUES ($1, $2)")
Ok(HttpResponse::Created().json(link))
···
"Custom code must be 1-32 characters long and contain only letters, numbers, underscores, and hyphens".to_string()
// Add reserved words check
let reserved_words = ["api", "health", "admin", "static", "assets"];
if reserved_words.contains(&code.to_lowercase().as_str()) {
return Err(AppError::InvalidInput(
+
"This code is reserved and cannot be used".to_string(),
···
return Err(AppError::InvalidInput("URL cannot be empty".to_string()));
if !url.starts_with("http://") && !url.starts_with("https://") {
+
return Err(AppError::InvalidInput(
+
"URL must start with http:// or https://".to_string(),
···
) -> Result<impl Responder, AppError> {
let short_code = path.into_inner();
// Extract query source if present
.and_then(|q| web::Query::<std::collections::HashMap<String, String>>::from_query(q).ok())
.and_then(|params| params.get("source").cloned());
···
let mut tx = state.db.begin().await?;
let link = sqlx::query_as::<_, Link>(
+
"UPDATE links SET clicks = clicks + 1 WHERE short_code = $1 RETURNING *",
.fetch_optional(&mut *tx)
···
// Record click with both user agent and query source
.and_then(|h| h.to_str().ok())
+
sqlx::query("INSERT INTO clicks (link_id, source, query_source) VALUES ($1, $2, $3)")
Ok(HttpResponse::TemporaryRedirect()
.append_header(("Location", link.original_url))
None => Err(AppError::NotFound),
···
) -> Result<impl Responder, AppError> {
let links = sqlx::query_as::<_, Link>(
+
"SELECT * FROM links WHERE user_id = $1 ORDER BY created_at DESC",
···
Ok(HttpResponse::Ok().json(links))
+
pub async fn health_check(state: web::Data<AppState>) -> impl Responder {
match sqlx::query("SELECT 1").execute(&state.db).await {
Ok(_) => HttpResponse::Ok().json("Healthy"),
Err(_) => HttpResponse::ServiceUnavailable().json("Database unavailable"),
···
fn generate_short_code() -> String {
let uuid = Uuid::new_v4();
encode(uuid.as_u128() as u64).chars().take(8).collect()
···
state: web::Data<AppState>,
payload: web::Json<RegisterRequest>,
) -> Result<impl Responder, AppError> {
+
let exists = sqlx::query!("SELECT id FROM users WHERE email = $1", payload.email)
+
.fetch_optional(&state.db)
return Err(AppError::Auth("Email already registered".to_string()));
···
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
+
let password_hash = argon2
+
.hash_password(payload.password.as_bytes(), &salt)
.map_err(|e| AppError::Auth(e.to_string()))?
···
+
&EncodingKey::from_secret(secret.as_bytes()),
+
.map_err(|e| AppError::Auth(e.to_string()))?;
Ok(HttpResponse::Ok().json(AuthResponse {
···
state: web::Data<AppState>,
payload: web::Json<LoginRequest>,
) -> Result<impl Responder, AppError> {
+
let user = sqlx::query_as!(User, "SELECT * FROM users WHERE email = $1", payload.email)
+
.fetch_optional(&state.db)
+
.ok_or_else(|| AppError::Auth("Invalid credentials".to_string()))?;
let argon2 = Argon2::default();
+
PasswordHash::new(&user.password_hash).map_err(|e| AppError::Auth(e.to_string()))?;
+
.verify_password(payload.password.as_bytes(), &parsed_hash)
return Err(AppError::Auth("Invalid credentials".to_string()));
···
+
&EncodingKey::from_secret(secret.as_bytes()),
+
.map_err(|e| AppError::Auth(e.to_string()))?;
Ok(HttpResponse::Ok().json(AuthResponse {
···
+
pub async fn delete_link(
+
state: web::Data<AppState>,
+
user: AuthenticatedUser,
+
) -> Result<impl Responder, AppError> {
+
let link_id = path.into_inner();
+
let mut tx = state.db.begin().await?;
+
// Verify the link belongs to the user
+
let link = sqlx::query!(
+
"SELECT id FROM links WHERE id = $1 AND user_id = $2",
+
.fetch_optional(&mut *tx)
+
return Err(AppError::NotFound);
+
// Delete associated clicks first due to foreign key constraint
+
sqlx::query!("DELETE FROM clicks WHERE link_id = $1", link_id)
+
sqlx::query!("DELETE FROM links WHERE id = $1", link_id)
+
Ok(HttpResponse::NoContent().finish())