-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfull.rs
More file actions
428 lines (360 loc) · 11.3 KB
/
full.rs
File metadata and controls
428 lines (360 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! Full-featured project template
use super::common;
use anyhow::Result;
use tokio::fs;
pub async fn generate(name: &str, features: &[String]) -> Result<()> {
// Add recommended features for full template
let mut all_features: Vec<String> = vec![
"extras-jwt".to_string(),
"extras-cors".to_string(),
"extras-rate-limit".to_string(),
"extras-config".to_string(),
];
// Add user-specified features
for f in features {
if !all_features.contains(f) {
all_features.push(f.clone());
}
}
// Cargo.toml
let cargo_toml = format!(
r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
[dependencies]
rustapi-rs = {{ version = "0.1"{features} }}
tokio = {{ version = "1", features = ["full"] }}
serde = {{ version = "1", features = ["derive"] }}
tracing = "0.1"
tracing-subscriber = {{ version = "0.3", features = ["env-filter"] }}
uuid = {{ version = "1", features = ["v4"] }}
"#,
name = name,
features = common::features_to_cargo(&all_features),
);
fs::write(format!("{name}/Cargo.toml"), cargo_toml).await?;
// Create directories
fs::create_dir_all(format!("{name}/src/handlers")).await?;
fs::create_dir_all(format!("{name}/src/models")).await?;
fs::create_dir_all(format!("{name}/src/middleware")).await?;
// main.rs
let main_rs = r#"mod handlers;
mod models;
mod middleware;
use rustapi_rs::prelude::*;
use std::sync::Arc;
use tokio::sync::RwLock;
pub type AppState = Arc<RwLock<models::Store>>;
#[rustapi_rs::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Load environment variables
load_dotenv();
// Initialize tracing
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::from_default_env()
.add_directive("info".parse().unwrap()),
)
.init();
// Get configuration
let env = Environment::current();
let host = env_or("HOST", "127.0.0.1");
let port = env_or("PORT", "8080");
let addr = format!("{}:{}", host, port);
// Create shared state
let state: AppState = Arc::new(RwLock::new(models::Store::new()));
tracing::info!("🚀 Starting server in {:?} mode", env);
tracing::info!("📡 Listening on http://{}", addr);
tracing::info!("📚 API docs at http://{}/docs", addr);
RustApi::new()
.state(state)
// Middleware
.layer(CorsLayer::permissive())
.layer(RateLimitLayer::new(100, std::time::Duration::from_secs(60)))
// Health check
.route("/health", get(handlers::health))
// Auth endpoints
.route("/auth/login", post(handlers::auth::login))
.route("/auth/me", get(handlers::auth::me))
// Protected items endpoints (require JWT)
.mount_route(handlers::items::list_route())
.mount_route(handlers::items::get_route())
.mount_route(handlers::items::create_route())
.mount_route(handlers::items::update_route())
.mount_route(handlers::items::delete_route())
// Documentation
.docs_with_info(
"/docs",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_VERSION"),
Some("Full-featured RustAPI application"),
)
.run(&addr)
.await
}
"#;
fs::write(format!("{name}/src/main.rs"), main_rs).await?;
// handlers/mod.rs
let handlers_mod = r#"//! Request handlers
pub mod auth;
pub mod items;
use rustapi_rs::prelude::*;
use serde::Serialize;
#[derive(Serialize, Schema)]
pub struct HealthResponse {
pub status: String,
pub version: String,
pub environment: String,
}
pub async fn health() -> Json<HealthResponse> {
Json(HealthResponse {
status: "ok".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
environment: std::env::var("RUSTAPI_ENV").unwrap_or_else(|_| "development".to_string()),
})
}
"#;
fs::write(format!("{name}/src/handlers/mod.rs"), handlers_mod).await?;
// handlers/auth.rs
let handlers_auth = r#"//! Authentication handlers
use rustapi_rs::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Schema)]
pub struct LoginRequest {
pub username: String,
pub password: String,
}
#[derive(Debug, Serialize, Schema)]
pub struct LoginResponse {
pub token: String,
pub token_type: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Schema)]
pub struct UserClaims {
pub sub: String,
pub username: String,
pub exp: usize,
}
/// Login and get a JWT token
#[rustapi_rs::post("/auth/login")]
#[rustapi_rs::tag("Authentication")]
#[rustapi_rs::summary("Login with username and password")]
pub async fn login(Json(body): Json<LoginRequest>) -> Result<Json<LoginResponse>> {
// TODO: Validate credentials against your database
if body.username == "admin" && body.password == "password" {
let jwt_secret = std::env::var("JWT_SECRET")
.unwrap_or_else(|_| "dev-secret-change-in-production".to_string());
let claims = UserClaims {
sub: "1".to_string(),
username: body.username,
exp: (chrono_now() + 86400) as usize, // 24 hours
};
let token = create_token(&claims, &jwt_secret)
.map_err(|e| ApiError::internal(format!("Failed to create token: {}", e)))?;
Ok(Json(LoginResponse {
token,
token_type: "Bearer".to_string(),
}))
} else {
Err(ApiError::unauthorized("Invalid credentials"))
}
}
/// Get current user info
#[rustapi_rs::get("/auth/me")]
#[rustapi_rs::tag("Authentication")]
#[rustapi_rs::summary("Get current authenticated user")]
pub async fn me(auth: AuthUser<UserClaims>) -> Json<UserClaims> {
Json(auth.0)
}
fn chrono_now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
"#;
fs::write(format!("{name}/src/handlers/auth.rs"), handlers_auth).await?;
// handlers/items.rs
let handlers_items = r#"//! Item handlers
use crate::handlers::auth::UserClaims;
use crate::models::{Item, CreateItem, UpdateItem};
use crate::AppState;
use rustapi_rs::prelude::*;
/// List all items
#[rustapi_rs::get("/items")]
#[rustapi_rs::tag("Items")]
#[rustapi_rs::summary("List all items")]
pub async fn list(
_auth: AuthUser<UserClaims>,
State(state): State<AppState>,
) -> Json<Vec<Item>> {
let store = state.read().await;
Json(store.items.values().cloned().collect())
}
/// Get an item by ID
#[rustapi_rs::get("/items/{id}")]
#[rustapi_rs::tag("Items")]
#[rustapi_rs::summary("Get item by ID")]
pub async fn get(
_auth: AuthUser<UserClaims>,
Path(id): Path<String>,
State(state): State<AppState>,
) -> Result<Json<Item>> {
let store = state.read().await;
store.items
.get(&id)
.cloned()
.map(Json)
.ok_or_else(|| ApiError::not_found(format!("Item {} not found", id)))
}
/// Create a new item
#[rustapi_rs::post("/items")]
#[rustapi_rs::tag("Items")]
#[rustapi_rs::summary("Create a new item")]
pub async fn create(
auth: AuthUser<UserClaims>,
State(state): State<AppState>,
Json(body): Json<CreateItem>,
) -> Json<Item> {
let item = Item::new(body.name, body.description, auth.0.sub.clone());
let mut store = state.write().await;
store.items.insert(item.id.clone(), item.clone());
tracing::info!("User {} created item {}", auth.0.username, item.id);
Json(item)
}
/// Update an item
#[rustapi_rs::put("/items/{id}")]
#[rustapi_rs::tag("Items")]
#[rustapi_rs::summary("Update an item")]
pub async fn update(
_auth: AuthUser<UserClaims>,
Path(id): Path<String>,
State(state): State<AppState>,
Json(body): Json<UpdateItem>,
) -> Result<Json<Item>> {
let mut store = state.write().await;
let item = store.items
.get_mut(&id)
.ok_or_else(|| ApiError::not_found(format!("Item {} not found", id)))?;
if let Some(name) = body.name {
item.name = name;
}
if let Some(description) = body.description {
item.description = Some(description);
}
item.updated_at = chrono_now();
Ok(Json(item.clone()))
}
/// Delete an item
#[rustapi_rs::delete("/items/{id}")]
#[rustapi_rs::tag("Items")]
#[rustapi_rs::summary("Delete an item")]
pub async fn delete(
auth: AuthUser<UserClaims>,
Path(id): Path<String>,
State(state): State<AppState>,
) -> Result<NoContent> {
let mut store = state.write().await;
store.items
.remove(&id)
.ok_or_else(|| ApiError::not_found(format!("Item {} not found", id)))?;
tracing::info!("User {} deleted item {}", auth.0.username, id);
Ok(NoContent)
}
fn chrono_now() -> String {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs().to_string())
.unwrap_or_default()
}
"#;
fs::write(format!("{name}/src/handlers/items.rs"), handlers_items).await?;
// models/mod.rs
let models_mod = r#"//! Data models
use serde::{Deserialize, Serialize};
use rustapi_rs::prelude::Schema;
use std::collections::HashMap;
pub struct Store {
pub items: HashMap<String, Item>,
}
impl Store {
pub fn new() -> Self {
Self {
items: HashMap::new(),
}
}
}
impl Default for Store {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Schema)]
pub struct Item {
pub id: String,
pub name: String,
#[serde(default)]
pub description: Option<String>,
pub created_by: String,
pub created_at: String,
pub updated_at: String,
}
impl Item {
pub fn new(name: String, description: Option<String>, created_by: String) -> Self {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs().to_string())
.unwrap_or_default();
Self {
id: uuid::Uuid::new_v4().to_string(),
name,
description,
created_by,
created_at: now.clone(),
updated_at: now,
}
}
}
#[derive(Debug, Deserialize, Schema)]
pub struct CreateItem {
pub name: String,
#[serde(default)]
pub description: Option<String>,
}
#[derive(Debug, Deserialize, Schema)]
pub struct UpdateItem {
pub name: Option<String>,
pub description: Option<String>,
}
"#;
fs::write(format!("{name}/src/models/mod.rs"), models_mod).await?;
// middleware/mod.rs
let middleware_mod = r#"//! Custom middleware
// Add your custom middleware here
// Example:
// pub mod logging;
// pub mod auth_check;
"#;
fs::write(format!("{name}/src/middleware/mod.rs"), middleware_mod).await?;
// .env.example with JWT secret
let env_example = r#"# Server configuration
HOST=127.0.0.1
PORT=8080
# Environment (development, production)
RUSTAPI_ENV=development
# JWT Secret (CHANGE THIS IN PRODUCTION!)
JWT_SECRET=your-super-secret-key-change-in-production
# Rate limiting
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_WINDOW_SECS=60
# Logging
RUST_LOG=info
"#;
fs::write(format!("{name}/.env.example"), env_example).await?;
// Copy .env.example to .env for development
fs::copy(format!("{name}/.env.example"), format!("{name}/.env")).await?;
// .gitignore
common::generate_gitignore(name).await?;
Ok(())
}