commit a133ed8ab5205f409180ba90ec07961b59996942 Author: Andy Kolibri Vendetti Date: Wed Oct 8 20:26:14 2025 +0300 Initial commit diff --git a/.gitea/workflows/rust-ci.yml b/.gitea/workflows/rust-ci.yml new file mode 100644 index 0000000..9f0805f --- /dev/null +++ b/.gitea/workflows/rust-ci.yml @@ -0,0 +1,28 @@ +name: Build and Push Docker Image +on: + create: + tags: + +jobs: + build-and-push: + runs-on: ubuntu-24.04 + steps: + - name: Login to Gitea Container Image Registry + uses: docker/login-action@v3 + with: + registry: ${{ secrets.REGISTRY_URL }} + username: ${{ gitea.actor }} + password: ${{ secrets.PUSH_TOKEN }} + - name: Checkout repository + uses: actions/checkout@v4 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + - name: Build and push Docker image + uses: docker/build-push-action@v5 + with: + context: . + file: ./Dockerfile + push: true + tags: | + ${{ secrets.REGISTRY_TAG }}/${{ gitea.repository }}:latest + ${{ secrets.REGISTRY_TAG }}/${{ gitea.repository }}:${{ gitea.ref_name }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d6fdf70 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target +/Cargo.lock +/.env +/postgresdata \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..68e31d7 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "shortlink-rs" +version = "0.1.0" +edition = "2024" + +[dependencies] +axum = "0.8.6" +tokio = { version = "1.47.1", features = ["full"] } +sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "time"] } +time = { version = "0.3.44", features = ["serde-well-known"] } +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.145" +rand = { version = "0.9.2", features = ["std_rng"] } +dotenv = "0.15.0" +tracing = "0.1.41" +tracing-subscriber = { version = "0.3.20", features = ["env-filter"] } +tower-http = { version = "0.6.6", features = ["fs"] } \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..b7434e9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,31 @@ +FROM rust:1-trixie as builder + +RUN apt-get update && apt-get install -y libpq-dev pkg-config + +WORKDIR /usr/src/app + +RUN cargo init --bin . +COPY ./Cargo.toml ./ + +RUN cargo build --release +RUN rm src/*.rs + +COPY ./src ./src +COPY ./static ./static +COPY ./migrations ./migrations + +RUN cargo build --release + +FROM debian:trixie-slim + +# RUN apt-get update && apt-get install -y ca-certificates libpq5 && rm -rf /var/lib/apt/lists/* + +WORKDIR /usr/src/app + +COPY --from=builder /usr/src/app/target/release/shortlink-rs . + +COPY --from=builder /usr/src/app/static ./static + +EXPOSE 3000 + +CMD ["./shortlink-rs"] \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a4acf3f --- /dev/null +++ b/LICENSE @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright 2025 andy@vendetti.ru + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7593228 --- /dev/null +++ b/README.md @@ -0,0 +1,12 @@ +# About the project +This simple shortlink server targets portable network devices and other low-performance machines. + +It comes in form of AMD64 Docker Image, but you can use it on any other platform (tested natively on MacOS 26.0.1 Tahoe) and without Docker. +# Set up +Before launching the program: + +- perform database migrations (in `./migrations` directory) manually or with your favourite tool; +- change Postgres password in `docker-compose.yml` and `.env`; +- change API_KEY to **LONG AND SECURE STRING** in `.env`. + +# This code is licensed under Apache-2.0 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..38bcb37 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,28 @@ +services: + db: + image: postgres:17.6 + container_name: shortlink-rs-db + restart: unless-stopped + volumes: + - ./postgresdata:/var/lib/postgresql/data + environment: + - POSTGRES_USER=shortlink + - POSTGRES_PASSWORD=password + - POSTGRES_INITDB_ARGS=--encoding=UTF-8 --lc-collate=C --lc-ctype=C + deploy: + resources: + limits: + memory: 256M + + service: + image: git.vendetti.ru/andy/shortlink-rs:0.1.0 + container_name: shortlink-rs-service + restart: unless-stopped + volumes: + - ./.env:/usr/src/app/.env:ro + ports: + - "127.0.0.1:12121:3000" + deploy: + resources: + limits: + memory: 256M \ No newline at end of file diff --git a/migrations/create_links_table.sql b/migrations/create_links_table.sql new file mode 100644 index 0000000..5dbec42 --- /dev/null +++ b/migrations/create_links_table.sql @@ -0,0 +1,19 @@ +CREATE TABLE links ( + id SERIAL PRIMARY KEY, + short_code VARCHAR(16) NOT NULL UNIQUE, + target_url TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE UNIQUE INDEX idx_links_short_code ON links(short_code); + +CREATE TABLE redirect_logs ( + id BIGSERIAL PRIMARY KEY, + link_id INTEGER NOT NULL REFERENCES links(id) ON DELETE CASCADE, + ip_address INET, + user_agent TEXT, + redirected_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX idx_redirect_logs_link_id ON redirect_logs(link_id); \ No newline at end of file diff --git a/src/handlers.rs b/src/handlers.rs new file mode 100644 index 0000000..e6128c7 --- /dev/null +++ b/src/handlers.rs @@ -0,0 +1,296 @@ +use crate::models::{AppState, CreateLinkPayload, Link, RedirectLog, UpdateLinkPayload}; +use axum::{ + extract::{ConnectInfo, Path, Request, State}, + http::{HeaderMap, StatusCode}, + middleware::Next, + response::{IntoResponse, Json, Redirect, Response}, +}; +use rand::{distr::Alphanumeric, Rng}; +use serde_json::json; +use sqlx::PgPool; +use std::net::SocketAddr; +use tracing::{error, info, warn}; + +pub async fn auth_middleware( + State(state): State, + request: Request, + next: Next, +) -> Result { + let auth_header = request + .headers() + .get("X-Api-Key") + .and_then(|header| header.to_str().ok()); + + match auth_header { + Some(key) if key == state.api_key => Ok(next.run(request).await), + _ => { + warn!("Unauthorized API access attempt"); + Err(StatusCode::UNAUTHORIZED) + } + } +} + +pub async fn root_handler() -> &'static str { + "Welcome to the Rust Link Shortener! Use a short code to be redirected." +} + +pub async fn update_link_handler( + State(state): State, + Path(id): Path, + Json(payload): Json, +) -> impl IntoResponse { + let mut link_to_update = match sqlx::query_as::<_, Link>("SELECT * FROM links WHERE id = $1") + .bind(id) + .fetch_one(&state.db_pool) + .await + { + Ok(link) => link, + Err(sqlx::Error::RowNotFound) => { + warn!("Link with id {} not found for update", id); + return (StatusCode::NOT_FOUND, Json(json!({"error": "Link not found"}))).into_response(); + } + Err(e) => { + error!("DB error fetching link for update: {}", e); + return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "Database error"}))).into_response(); + } + }; + + if let Some(new_short_code) = payload.short_code { + if new_short_code != link_to_update.short_code { + let conflict_check = sqlx::query("SELECT id FROM links WHERE short_code = $1") + .bind(&new_short_code) + .fetch_optional(&state.db_pool) + .await; + + match conflict_check { + Ok(Some(_)) => { + warn!("Attempted to update to a conflicting short_code: {}", new_short_code); + return (StatusCode::CONFLICT, Json(json!({"error": "Этот короткий код уже используется"}))).into_response(); + } + Err(e) => { + error!("DB error checking short_code conflict: {}", e); + return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "Database error"}))).into_response(); + } + _ => {} + } + link_to_update.short_code = new_short_code; + } + } + + if let Some(new_target_url) = payload.target_url { + link_to_update.target_url = new_target_url; + } + + let result = sqlx::query_as::<_, Link>( + "UPDATE links SET target_url = $1, short_code = $2, updated_at = NOW() WHERE id = $3 RETURNING *", + ) + .bind(&link_to_update.target_url) + .bind(&link_to_update.short_code) + .bind(id) + .fetch_one(&state.db_pool) + .await; + + match result { + Ok(updated_link) => { + info!("Successfully updated link id: {}", id); + (StatusCode::OK, Json(updated_link)).into_response() + } + Err(e) => { + error!("Failed to save updated link id {}: {}", id, e); + (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": "Database error during final update"}))).into_response() + } + } +} + +pub async fn delete_link_handler( + State(state): State, + Path(id): Path, +) -> impl IntoResponse { + info!("Deleting link with id: {}", id); + let result = sqlx::query("DELETE FROM links WHERE id = $1") + .bind(id) + .execute(&state.db_pool) + .await; + match result { + Ok(query_result) => { + if query_result.rows_affected() > 0 { + info!("Successfully deleted link with id: {}", id); + StatusCode::NO_CONTENT + } else { + warn!("Link with id {} not found for deletion", id); + StatusCode::NOT_FOUND + } + } + Err(e) => { + error!("Failed to delete link with id {}: {}", id, e); + StatusCode::INTERNAL_SERVER_ERROR + } + } +} + +pub async fn get_link_stats_handler( + State(state): State, + Path(id): Path, +) -> impl IntoResponse { + info!("Fetching stats for link_id: {}", id); + let result = sqlx::query_as::<_, RedirectLog>( + "SELECT id, link_id, redirected_at, ip_address::text, user_agent FROM redirect_logs WHERE link_id = $1 ORDER BY redirected_at DESC", + ) + .bind(id) + .fetch_all(&state.db_pool) + .await; + match result { + Ok(logs) => (StatusCode::OK, Json(logs)).into_response(), + Err(e) => { + error!("Failed to fetch stats for link_id {}: {}", id, e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ "error": "Failed to fetch stats" })), + ) + .into_response() + } + } +} + +pub async fn list_links_handler(State(state): State) -> impl IntoResponse { + info!("Fetching all links"); + let result = sqlx::query_as::<_, Link>("SELECT * FROM links ORDER BY created_at DESC") + .fetch_all(&state.db_pool) + .await; + match result { + Ok(links) => (StatusCode::OK, Json(links)).into_response(), + Err(e) => { + error!("Failed to fetch links: {}", e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ "error": "Failed to fetch links" })), + ) + .into_response() + } + } +} + +pub async fn create_link_handler( + State(state): State, + Json(payload): Json, +) -> impl IntoResponse { + if let Some(custom_code) = payload.short_code { + info!("Attempting to create link with custom code: {}", &custom_code); + return create_link_with_code(&state.db_pool, &payload.target_url, &custom_code).await; + } + info!("Generating random short code for: {}", &payload.target_url); + for i in 0..10 { + let short_code: String = rand::rng() + .sample_iter(&Alphanumeric) + .take(6) + .map(char::from) + .collect(); + let response = + create_link_with_code(&state.db_pool, &payload.target_url, &short_code).await; + if response.status() != StatusCode::CONFLICT { + return response; + } + warn!( + "Collision detected for short_code: {}. Retrying... ({}/10)", + short_code, + i + 1 + ); + } + error!("Failed to generate a unique short_code after 10 attempts."); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ "error": "Could not generate a unique short link" })), + ) + .into_response() +} + +async fn create_link_with_code(db_pool: &PgPool, target_url: &str, short_code: &str) -> Response { + let result = sqlx::query_as::<_, Link>( + "INSERT INTO links (short_code, target_url) VALUES ($1, $2) RETURNING *", + ) + .bind(short_code) + .bind(target_url) + .fetch_one(db_pool) + .await; + match result { + Ok(new_link) => { + info!( + "Successfully created link with id {} and code {}", + new_link.id, short_code + ); + (StatusCode::CREATED, Json(new_link)).into_response() + } + Err(sqlx::Error::Database(err)) if err.is_unique_violation() => ( + StatusCode::CONFLICT, + Json(json!({"error": "Этот короткий код уже используется"})), + ) + .into_response(), + Err(e) => { + error!("Failed to create link with code {}: {}", short_code, e); + ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({ "error": "Failed to create link" })), + ) + .into_response() + } + } +} + +pub async fn redirect_handler( + State(state): State, + Path(short_code): Path, + ConnectInfo(addr): ConnectInfo, + headers: HeaderMap, +) -> impl IntoResponse { + info!( + "Redirect request for code: '{}' from IP: {}", + short_code, + addr.ip() + ); + let find_link_result = sqlx::query_as::<_, Link>("SELECT * FROM links WHERE short_code = $1") + .bind(&short_code) + .fetch_optional(&state.db_pool) + .await; + match find_link_result { + Ok(Some(link)) => { + info!( + "Found link: id={}, target_url={}", + link.id, link.target_url + ); + let user_agent = headers + .get("user-agent") + .and_then(|value| value.to_str().ok()) + .unwrap_or("Unknown") + .to_string(); + let db_pool = state.db_pool.clone(); + let link_id = link.id; + let ip_address = addr.ip().to_string(); + tokio::spawn(async move { + let log_result = sqlx::query( + "INSERT INTO redirect_logs (link_id, ip_address, user_agent) VALUES ($1, $2::inet, $3)", + ) + .bind(link_id) + .bind(ip_address) + .bind(user_agent) + .execute(&db_pool) + .await; + match log_result { + Ok(_) => info!("Successfully logged redirect for link_id: {}", link_id), + Err(e) => error!("Failed to log redirect: {}", e), + } + }); + Ok(Redirect::permanent(&link.target_url)) + } + Ok(None) => { + warn!("Short code not found: {}", short_code); + Err((StatusCode::NOT_FOUND, "Link not found".to_string())) + } + Err(e) => { + error!("Database error while fetching link: {}", e); + Err(( + StatusCode::INTERNAL_SERVER_ERROR, + "Internal server error".to_string(), + )) + } + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..3387dde --- /dev/null +++ b/src/main.rs @@ -0,0 +1,81 @@ +mod handlers; +mod models; + +use axum::{ + middleware, + routing::{get, get_service, put}, + Router, +}; +use models::AppState; +use sqlx::PgPool; +use std::net::SocketAddr; +use tower_http::services::ServeFile; +use tracing::info; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; + +use handlers::{ + auth_middleware, create_link_handler, delete_link_handler, get_link_stats_handler, + list_links_handler, redirect_handler, root_handler, update_link_handler, +}; + +#[tokio::main] +async fn main() { + tracing_subscriber::registry() + .with( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "shortlink-rs=debug,tower_http=debug".into()), + ) + .with(tracing_subscriber::fmt::layer()) + .init(); + + info!("Initializing application..."); + + dotenv::dotenv().ok(); + + let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); + let api_key = std::env::var("API_KEY").expect("API_KEY must be set"); + + let db_pool = PgPool::connect(&database_url) + .await + .expect("Failed to create database connection pool"); + + info!("Database connection pool created successfully."); + + let app_state = AppState { db_pool, api_key }; + + let api_routes = Router::new() + .route( + "/links", + get(list_links_handler).post(create_link_handler), + ) + .route( + "/links/{id}", + put(update_link_handler).delete(delete_link_handler), + ) + .route("/links/{id}/stats", get(get_link_stats_handler)) + .layer(middleware::from_fn_with_state( + app_state.clone(), + auth_middleware, + )); + + let app = Router::new() + .route("/", get(root_handler)) + .route_service( + "/admin", + get_service(ServeFile::new("static/admin.html")), + ) + .route("/{short_code}", get(redirect_handler)) + .nest("/api", api_routes) + .with_state(app_state); + + let addr = SocketAddr::from(([0, 0, 0, 0], 3000)); + info!("Server listening on {}", addr); + + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); +} \ No newline at end of file diff --git a/src/models.rs b/src/models.rs new file mode 100644 index 0000000..668594b --- /dev/null +++ b/src/models.rs @@ -0,0 +1,41 @@ +use serde::{Deserialize, Serialize}; +use sqlx::{types::time::OffsetDateTime, PgPool}; + +#[derive(Clone)] +pub struct AppState { + pub db_pool: PgPool, + pub api_key: String, +} + +#[derive(Debug, Serialize, sqlx::FromRow)] +pub struct Link { + pub id: i32, + pub short_code: String, + pub target_url: String, + #[serde(with = "time::serde::rfc3339")] + pub created_at: OffsetDateTime, + #[serde(with = "time::serde::rfc3339")] + pub updated_at: OffsetDateTime, +} + +#[derive(Debug, Serialize, sqlx::FromRow)] +pub struct RedirectLog { + pub id: i64, + pub link_id: i32, + #[serde(with = "time::serde::rfc3339")] + pub redirected_at: OffsetDateTime, + pub ip_address: String, + pub user_agent: Option, +} + +#[derive(Deserialize)] +pub struct CreateLinkPayload { + pub target_url: String, + pub short_code: Option, +} + +#[derive(Deserialize)] +pub struct UpdateLinkPayload { + pub target_url: Option, + pub short_code: Option, +} \ No newline at end of file diff --git a/static/admin.html b/static/admin.html new file mode 100644 index 0000000..ec43f64 --- /dev/null +++ b/static/admin.html @@ -0,0 +1,354 @@ + + + + + + Сокращатель ссылок + + + + +
+
+

Панель администратора

+

Управление короткими ссылками и просмотр статистики

+
+ +
+

API Ключ

+

Этот ключ необходим для доступа к API. Он будет сохранен в вашем браузере.

+
+ + +
+

+
+ +
+
+

Создать новую ссылку

+ +

+
+ +
+

Существующие ссылки

+ +
+
+
+ + + + + + \ No newline at end of file