Initial commit

This commit is contained in:
2025-10-08 20:26:14 +03:00
commit a133ed8ab5
12 changed files with 984 additions and 0 deletions

View File

@@ -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 }}

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
/target
/Cargo.lock
/.env
/postgresdata

17
Cargo.toml Normal file
View File

@@ -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"] }

31
Dockerfile Normal file
View File

@@ -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"]

73
LICENSE Normal file
View File

@@ -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.

12
README.md Normal file
View File

@@ -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

28
docker-compose.yml Normal file
View File

@@ -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

View File

@@ -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);

296
src/handlers.rs Normal file
View File

@@ -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<AppState>,
request: Request,
next: Next,
) -> Result<Response, StatusCode> {
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<AppState>,
Path(id): Path<i32>,
Json(payload): Json<UpdateLinkPayload>,
) -> 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<AppState>,
Path(id): Path<i32>,
) -> 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<AppState>,
Path(id): Path<i32>,
) -> 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<AppState>) -> 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<AppState>,
Json(payload): Json<CreateLinkPayload>,
) -> 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<AppState>,
Path(short_code): Path<String>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
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(),
))
}
}
}

81
src/main.rs Normal file
View File

@@ -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::<SocketAddr>(),
)
.await
.unwrap();
}

41
src/models.rs Normal file
View File

@@ -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<String>,
}
#[derive(Deserialize)]
pub struct CreateLinkPayload {
pub target_url: String,
pub short_code: Option<String>,
}
#[derive(Deserialize)]
pub struct UpdateLinkPayload {
pub target_url: Option<String>,
pub short_code: Option<String>,
}

354
static/admin.html Normal file
View File

@@ -0,0 +1,354 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Сокращатель ссылок</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
body { font-family: 'Inter', sans-serif; }
.modal { display: none; }
.modal.is-open { display: flex; }
.hidden-area { display: none; }
</style>
</head>
<body class="bg-gray-100 text-gray-800">
<div class="container mx-auto p-4 md:p-8">
<header class="mb-8">
<h1 class="text-3xl font-bold text-gray-900">Панель администратора</h1>
<p class="text-gray-600">Управление короткими ссылками и просмотр статистики</p>
</header>
<div class="bg-white p-6 rounded-lg shadow-md mb-8">
<h2 class="text-xl font-semibold mb-2">API Ключ</h2>
<p class="text-sm text-gray-500 mb-4">Этот ключ необходим для доступа к API. Он будет сохранен в вашем браузере.</p>
<div class="flex flex-col sm:flex-row gap-4">
<input type="password" id="api-key-input" placeholder="Введите API ключ"
class="flex-grow p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition">
<button id="save-api-key-btn"
class="bg-green-600 text-white font-bold py-3 px-6 rounded-md hover:bg-green-700 transition-colors duration-300">
Войти
</button>
</div>
<p id="api-key-status" class="text-sm mt-2 h-4"></p>
</div>
<div id="main-content" class="hidden-area">
<div class="bg-white p-6 rounded-lg shadow-md mb-8">
<h2 class="text-xl font-semibold mb-4">Создать новую ссылку</h2>
<form id="create-link-form">
<div class="flex flex-col sm:flex-row gap-4">
<input type="url" id="target-url" placeholder="https://example.com/dlinnyy/url" required
class="flex-grow p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition">
<input type="text" id="custom-code" placeholder="Свой код (необязательно)"
class="w-full sm:w-48 p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition">
<button type="submit"
class="bg-blue-600 text-white font-bold py-3 px-6 rounded-md hover:bg-blue-700 transition-colors duration-300 disabled:bg-gray-400">
Сократить
</button>
</div>
</form>
<p id="form-message" class="text-sm mt-2 h-4"></p>
</div>
<div>
<h2 class="text-xl font-semibold mb-4">Существующие ссылки</h2>
<div id="links-container" class="space-y-4">
</div>
</div>
</div>
</div>
<div id="stats-modal" class="modal fixed inset-0 bg-black bg-opacity-50 justify-center items-center p-4">
<div class="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] flex flex-col">
<div class="p-4 border-b flex justify-between items-center">
<h3 class="text-lg font-semibold">Статистика переходов</h3>
<button id="close-modal-btn" class="text-gray-500 hover:text-gray-800">&times;</button>
</div>
<div id="stats-content" class="p-4 overflow-y-auto">
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const API_BASE = '/api';
const apiKeyInput = document.getElementById('api-key-input');
const saveApiKeyBtn = document.getElementById('save-api-key-btn');
const apiKeyStatus = document.getElementById('api-key-status');
const mainContent = document.getElementById('main-content');
const createForm = document.getElementById('create-link-form');
const targetUrlInput = document.getElementById('target-url');
const customCodeInput = document.getElementById('custom-code');
const formMessage = document.getElementById('form-message');
const linksContainer = document.getElementById('links-container');
const statsModal = document.getElementById('stats-modal');
const statsContent = document.getElementById('stats-content');
const closeModalBtn = document.getElementById('close-modal-btn');
let currentApiKey = null;
function saveAndCheckApiKey() {
const key = apiKeyInput.value.trim();
if (!key) {
apiKeyStatus.textContent = 'Ключ не может быть пустым.';
apiKeyStatus.className = 'text-sm mt-2 h-4 text-red-500';
return;
}
authedFetch('/links', { method: 'GET' }, key)
.then(response => {
if (response.ok) {
localStorage.setItem('apiKey', key);
currentApiKey = key;
apiKeyStatus.textContent = 'Ключ принят. Доступ разрешен.';
apiKeyStatus.className = 'text-sm mt-2 h-4 text-green-600';
mainContent.style.display = 'block';
fetchLinks();
} else {
throw new Error('Неверный API ключ');
}
})
.catch(error => {
localStorage.removeItem('apiKey');
currentApiKey = null;
apiKeyStatus.textContent = `Ошибка: ${error.message}`;
apiKeyStatus.className = 'text-sm mt-2 h-4 text-red-500';
mainContent.style.display = 'none';
});
}
function loadApiKey() {
const storedKey = localStorage.getItem('apiKey');
if (storedKey) {
apiKeyInput.value = storedKey;
saveAndCheckApiKey();
}
}
async function authedFetch(endpoint, options = {}, keyOverride = null) {
const key = keyOverride || currentApiKey;
if (!key) {
throw new Error("API ключ не установлен");
}
const headers = {
...options.headers,
'Content-Type': 'application/json',
'X-Api-Key': key
};
return fetch(`${API_BASE}${endpoint}`, { ...options, headers });
}
async function fetchLinks() {
linksContainer.innerHTML = '<p>Загрузка ссылок...</p>';
try {
const response = await authedFetch('/links');
if (response.status === 401) throw new Error('Неверный API ключ');
if (!response.ok) throw new Error('Ошибка при загрузке ссылок');
const links = await response.json();
renderLinks(links);
} catch (error) {
linksContainer.innerHTML = `<p class="text-red-500">Ошибка: ${error.message}. Проверьте ваш API ключ.</p>`;
}
}
async function createLink(targetUrl, customCode) {
try {
const payload = { target_url: targetUrl };
if (customCode) {
if (/\s|\//.test(customCode)) {
throw new Error('Короткий код не должен содержать пробелы или слэши.');
}
payload.short_code = customCode;
}
const response = await authedFetch('/links', {
method: 'POST',
body: JSON.stringify(payload)
});
if (response.status === 409) {
const errorData = await response.json();
throw new Error(errorData.error || 'Этот код уже используется.');
}
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || 'Не удалось создать ссылку');
}
formMessage.textContent = 'Ссылка успешно создана!';
formMessage.className = 'text-sm mt-2 h-4 text-green-600';
createForm.reset();
fetchLinks();
} catch (error) {
formMessage.textContent = `Ошибка: ${error.message}`;
formMessage.className = 'text-sm mt-2 h-4 text-red-500';
} finally {
setTimeout(() => formMessage.textContent = '', 5000);
}
}
async function updateLink(linkId, payload) {
try {
const response = await authedFetch(`/links/${linkId}`, {
method: 'PUT',
body: JSON.stringify(payload)
});
if (response.status === 409) { // HTTP Conflict
const errorData = await response.json();
throw new Error(errorData.error || 'Этот короткий код уже используется.');
}
if (!response.ok) throw new Error('Ошибка при обновлении ссылки');
fetchLinks();
} catch (error) {
alert(`Не удалось обновить ссылку: ${error.message}`);
}
}
async function deleteLink(linkId) {
if (!confirm('Вы уверены, что хотите удалить эту ссылку?')) return;
try {
const response = await authedFetch(`/links/${linkId}`, {
method: 'DELETE'
});
if (!response.ok) throw new Error('Ошибка при удалении');
fetchLinks();
} catch (error) {
alert(`Не удалось удалить ссылку: ${error.message}`);
}
}
async function fetchStats(linkId) {
statsContent.innerHTML = '<p>Загрузка статистики...</p>';
statsModal.classList.add('is-open');
try {
const response = await authedFetch(`/links/${linkId}/stats`);
if (!response.ok) throw new Error('Ошибка при загрузке статистики');
const stats = await response.json();
renderStats(stats);
} catch(error) {
statsContent.innerHTML = `<p class="text-red-500">Ошибка: ${error.message}</p>`;
}
}
function renderLinks(links) {
linksContainer.innerHTML = '';
if (links.length === 0) {
linksContainer.innerHTML = '<p>Пока нет ни одной ссылки. Создайте первую!</p>';
return;
}
links.forEach(link => {
const shortUrl = `${window.location.origin}/${link.short_code}`;
const card = document.createElement('div');
card.className = 'bg-white p-4 rounded-lg shadow-md flex flex-col md:flex-row md:items-center gap-4';
card.innerHTML = `
<div class="flex-grow">
<a href="${shortUrl}" target="_blank" class="text-lg font-semibold text-blue-600 hover:underline">${shortUrl}</a>
<p class="text-sm text-gray-500 truncate" title="${link.target_url}">
${link.target_url}
</p>
</div>
<div class="flex items-center gap-2 flex-shrink-0 flex-wrap">
<button data-stats-id="${link.id}" class="stats-btn text-sm bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-4 rounded-md transition">Статистика</button>
<button data-edit-url-id="${link.id}" data-current-url="${link.target_url}" class="edit-url-btn text-sm bg-yellow-400 hover:bg-yellow-500 text-gray-800 font-semibold py-2 px-4 rounded-md transition">Ред. URL</button>
<button data-edit-code-id="${link.id}" data-current-code="${link.short_code}" class="edit-code-btn text-sm bg-yellow-400 hover:bg-yellow-500 text-gray-800 font-semibold py-2 px-4 rounded-md transition">Ред. код</button>
<button data-delete-id="${link.id}" class="delete-btn text-sm bg-red-500 hover:bg-red-600 text-white font-semibold py-2 px-4 rounded-md transition">Удалить</button>
</div>
`;
linksContainer.appendChild(card);
});
}
function renderStats(stats) {
if (stats.length === 0) {
statsContent.innerHTML = '<p>По этой ссылке еще не было переходов.</p>';
return;
}
const table = document.createElement('table');
table.className = 'w-full text-left text-sm';
table.innerHTML = `
<thead class="bg-gray-100">
<tr>
<th class="p-2">Время</th>
<th class="p-2">IP Адрес</th>
<th class="p-2">User Agent</th>
</tr>
</thead>
<tbody>
${stats.map(log => `
<tr class="border-b">
<td class="p-2">${new Date(log.redirected_at).toLocaleString()}</td>
<td class="p-2">${log.ip_address}</td>
<td class="p-2 text-xs text-gray-600 truncate" title="${log.user_agent || ''}">${log.user_agent || 'N/A'}</td>
</tr>
`).join('')}
</tbody>
`;
statsContent.innerHTML = '';
statsContent.appendChild(table);
}
saveApiKeyBtn.addEventListener('click', saveAndCheckApiKey);
apiKeyInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') saveAndCheckApiKey();
});
createForm.addEventListener('submit', (e) => {
e.preventDefault();
const targetUrl = targetUrlInput.value;
const customCode = customCodeInput.value.trim();
if (targetUrl) {
createLink(targetUrl, customCode || null);
}
});
linksContainer.addEventListener('click', (e) => {
const target = e.target;
if (target.matches('.delete-btn')) {
deleteLink(target.dataset.deleteId);
}
if (target.matches('.stats-btn')) {
fetchStats(target.dataset.statsId);
}
if (target.matches('.edit-url-btn')) {
const linkId = target.dataset.editUrlId;
const currentUrl = target.dataset.currentUrl;
const newUrl = prompt('Введите новый целевой URL:', currentUrl);
if (newUrl && newUrl.trim() !== '' && newUrl !== currentUrl) {
updateLink(linkId, { target_url: newUrl.trim() });
}
}
if (target.matches('.edit-code-btn')) {
const linkId = target.dataset.editCodeId;
const currentCode = target.dataset.currentCode;
const newCode = prompt('Введите новый короткий код:', currentCode);
if (newCode && newCode.trim() !== '' && newCode !== currentCode) {
if (/\s|\//.test(newCode.trim())) {
alert('Короткий код не должен содержать пробелы или слэши.');
return;
}
updateLink(linkId, { short_code: newCode.trim() });
}
}
});
closeModalBtn.addEventListener('click', () => statsModal.classList.remove('is-open'));
statsModal.addEventListener('click', (e) => {
if (e.target === statsModal) {
statsModal.classList.remove('is-open');
}
});
loadApiKey();
});
</script>
</body>
</html>