summaryrefslogtreecommitdiff
path: root/src/lib.rs
blob: 900b4dcb2b52151f35897f962ad48401a1bec936 (plain)
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use axum::Json;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::{post, put};
use axum::{Router, routing::get};
use serde_json::json;
use sqlx::SqlitePool;

// Derive OpenApi for models

mod auth;

fn error_response(status: StatusCode, message: &str) -> axum::response::Response {
    (status, Json(json!({"error": message}))).into_response()
}

async fn not_found() -> axum::response::Response {
    error_response(StatusCode::NOT_FOUND, "Not Found")
}

mod users_api {
    use super::*;
    use crate::auth::AuthUser;
    use crate::users::{User, UserRepository, UserRole};
    use axum::{
        Json,
        extract::{Path, State},
    };
    use serde::Deserialize;
    use std::sync::Arc;

    #[derive(Deserialize)]
    pub struct CreateUser {
        pub role: Option<UserRole>,
    }

    #[derive(Deserialize)]
    pub struct UpdateUser {
        pub role: UserRole,
    }

    pub async fn list_users(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<Json<Vec<User>>, String> {
        let repo = UserRepository { db: &pool };
        repo.list_users().await.map(Json).map_err(|e| e.to_string())
    }

    pub async fn get_user(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<Json<User>, String> {
        let repo = UserRepository { db: &pool };
        repo.get_user_by_id(id)
            .await
            .map_err(|e| e.to_string())?
            .map(Json)
            .ok_or_else(|| "User not found".to_string())
    }

    pub async fn create_user(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<CreateUser>,
    ) -> Result<Json<User>, String> {
        let repo = UserRepository { db: &pool };
        repo.create_user(None, payload.role)
            .await
            .map(Json)
            .map_err(|e| e.to_string())
    }

    pub async fn update_user(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<UpdateUser>,
    ) -> Result<Json<User>, String> {
        let repo = UserRepository { db: &pool };
        repo.update_user(id, payload.role)
            .await
            .map(Json)
            .map_err(|e| e.to_string())
    }

    pub async fn delete_user(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<(), String> {
        let repo = UserRepository { db: &pool };
        repo.delete_user(id).await.map_err(|e| e.to_string())
    }
}

mod locations_api {
    use super::*;
    use crate::auth::AuthUser;
    use crate::locations::{Location, LocationRepository};
    use axum::{
        Json,
        extract::{Path, State},
    };
    use serde::Deserialize;
    use std::sync::Arc;

    #[derive(Deserialize)]
    pub struct CreateLocation {
        pub latitude: f64,
        pub longitude: f64,
        pub user_id: i64,
    }

    #[derive(Deserialize)]
    pub struct UpdateLocation {
        pub latitude: f64,
        pub longitude: f64,
    }

    pub async fn list_locations(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<Json<Vec<Location>>, String> {
        let repo = LocationRepository { db: &pool };
        repo.list_locations()
            .await
            .map(Json)
            .map_err(|e| e.to_string())
    }

    pub async fn get_location(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<Json<Location>, String> {
        let repo = LocationRepository { db: &pool };
        repo.get_location(id)
            .await
            .map_err(|e| e.to_string())?
            .map(Json)
            .ok_or_else(|| "Location not found".to_string())
    }

    pub async fn create_location(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<CreateLocation>,
    ) -> Result<Json<Location>, String> {
        let repo = LocationRepository { db: &pool };
        repo.create_location(payload.latitude, payload.longitude, payload.user_id)
            .await
            .map(Json)
            .map_err(|e| e.to_string())
    }

    pub async fn update_location(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<UpdateLocation>,
    ) -> Result<Json<Location>, String> {
        let repo = LocationRepository { db: &pool };
        // user_id is not updated
        repo.update_location(id, payload.latitude, payload.longitude)
            .await
            .map(Json)
            .map_err(|e| e.to_string())
    }

    pub async fn delete_location(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<(), String> {
        let repo = LocationRepository { db: &pool };
        repo.delete_location(id).await.map_err(|e| e.to_string())
    }
}

mod thresholds_api {
    use super::*;
    use crate::auth::AuthUser;
    use crate::weather_thresholds::{WeatherThreshold, WeatherThresholdRepository};
    use axum::{
        Json,
        extract::{Path, Query, State},
    };
    use serde::Deserialize;
    use std::sync::Arc;

    #[derive(Deserialize)]
    pub struct CreateThreshold {
        pub user_id: i64,
        pub condition_type: String,
        pub threshold_value: f64,
        pub operator: String,
        pub enabled: bool,
        pub description: Option<String>,
    }

    #[derive(Deserialize)]
    pub struct UpdateThreshold {
        pub user_id: i64,
        pub condition_type: String,
        pub threshold_value: f64,
        pub operator: String,
        pub enabled: bool,
        pub description: Option<String>,
    }

    pub async fn list_thresholds(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Query(query): Query<std::collections::HashMap<String, String>>,
    ) -> impl axum::response::IntoResponse {
        let repo = WeatherThresholdRepository { db: &pool };
        let user_id = query
            .get("user_id")
            .and_then(|s| s.parse().ok())
            .ok_or_else(|| "user_id required as query param".to_string())?;
        repo.list_thresholds(user_id)
            .await
            .map(Json)
            .map_err(|e| e.to_string())
    }

    pub async fn get_threshold(
        Path((id, user_id)): Path<(i64, i64)>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<Json<WeatherThreshold>, String> {
        let repo = WeatherThresholdRepository { db: &pool };
        repo.get_threshold(id, user_id)
            .await
            .map_err(|e| e.to_string())?
            .map(Json)
            .ok_or_else(|| "Threshold not found".to_string())
    }

    pub async fn create_threshold(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<CreateThreshold>,
    ) -> Result<Json<WeatherThreshold>, String> {
        let repo = WeatherThresholdRepository { db: &pool };
        repo.create_threshold(
            payload.user_id,
            payload.condition_type,
            payload.threshold_value,
            payload.operator,
            payload.enabled,
            payload.description,
        )
        .await
        .map(Json)
        .map_err(|e| e.to_string())
    }

    pub async fn update_threshold(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<UpdateThreshold>,
    ) -> Result<Json<WeatherThreshold>, String> {
        let repo = WeatherThresholdRepository { db: &pool };
        repo.update_threshold(
            id,
            payload.user_id,
            payload.condition_type,
            payload.threshold_value,
            payload.operator,
            payload.enabled,
            payload.description,
        )
        .await
        .map(Json)
        .map_err(|e| e.to_string())
    }

    pub async fn delete_threshold(
        Path((id, user_id)): Path<(i64, i64)>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<(), String> {
        let repo = WeatherThresholdRepository { db: &pool };
        repo.delete_threshold(id, user_id)
            .await
            .map_err(|e| e.to_string())
    }
}

mod notifications_api {
    use super::*;
    use crate::auth::AuthUser;
    use crate::notifications::{
        NtfySettings, NtfySettingsRepository, SmtpSettings, SmtpSettingsRepository,
    };
    use axum::{
        Json,
        extract::{Path, State},
    };
    use serde::Deserialize;
    use std::sync::Arc;

    // NTFY
    #[derive(Deserialize)]
    pub struct CreateNtfy {
        pub user_id: i64,
        pub enabled: bool,
        pub topic: String,
        pub server_url: String,
        pub priority: i32,
        pub title_template: Option<String>,
        pub message_template: Option<String>,
    }
    #[derive(Deserialize)]
    pub struct UpdateNtfy {
        pub enabled: bool,
        pub topic: String,
        pub server_url: String,
        pub priority: i32,
        pub title_template: Option<String>,
        pub message_template: Option<String>,
    }
    pub async fn get_ntfy_settings(
        Path(user_id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<Json<NtfySettings>, String> {
        let repo = NtfySettingsRepository { db: &pool };
        repo.get_by_user(user_id)
            .await
            .map_err(|e| e.to_string())?
            .map(Json)
            .ok_or_else(|| "NTFY settings not found".to_string())
    }
    pub async fn create_ntfy_settings(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<CreateNtfy>,
    ) -> Result<Json<NtfySettings>, String> {
        let repo = NtfySettingsRepository { db: &pool };
        repo.create(
            payload.user_id,
            payload.enabled,
            payload.topic,
            payload.server_url,
            payload.priority,
            payload.title_template,
            payload.message_template,
        )
        .await
        .map(Json)
        .map_err(|e| e.to_string())
    }
    pub async fn update_ntfy_settings(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<UpdateNtfy>,
    ) -> Result<Json<NtfySettings>, String> {
        let repo = NtfySettingsRepository { db: &pool };
        repo.update(
            id,
            payload.enabled,
            payload.topic,
            payload.server_url,
            payload.priority,
            payload.title_template,
            payload.message_template,
        )
        .await
        .map(Json)
        .map_err(|e| e.to_string())
    }
    pub async fn delete_ntfy_settings(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<(), String> {
        let repo = NtfySettingsRepository { db: &pool };
        repo.delete(id).await.map_err(|e| e.to_string())
    }

    // SMTP
    #[derive(Deserialize)]
    pub struct CreateSmtp {
        pub user_id: i64,
        pub enabled: bool,
        pub email: String,
        pub smtp_server: String,
        pub smtp_port: i32,
        pub username: Option<String>,
        pub password: Option<String>,
        pub use_tls: bool,
        pub from_email: Option<String>,
        pub from_name: Option<String>,
        pub subject_template: Option<String>,
        pub body_template: Option<String>,
    }
    #[derive(Deserialize)]
    pub struct UpdateSmtp {
        pub enabled: bool,
        pub email: String,
        pub smtp_server: String,
        pub smtp_port: i32,
        pub username: Option<String>,
        pub password: Option<String>,
        pub use_tls: bool,
        pub from_email: Option<String>,
        pub from_name: Option<String>,
        pub subject_template: Option<String>,
        pub body_template: Option<String>,
    }
    pub async fn get_smtp_settings(
        Path(user_id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<Json<SmtpSettings>, String> {
        let repo = SmtpSettingsRepository { db: &pool };
        repo.get_by_user(user_id)
            .await
            .map_err(|e| e.to_string())?
            .map(Json)
            .ok_or_else(|| "SMTP settings not found".to_string())
    }
    pub async fn create_smtp_settings(
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<CreateSmtp>,
    ) -> Result<Json<SmtpSettings>, String> {
        let repo = SmtpSettingsRepository { db: &pool };
        repo.create(
            payload.user_id,
            payload.enabled,
            payload.email,
            payload.smtp_server,
            payload.smtp_port,
            payload.username,
            payload.password,
            payload.use_tls,
            payload.from_email,
            payload.from_name,
            payload.subject_template,
            payload.body_template,
        )
        .await
        .map(Json)
        .map_err(|e| e.to_string())
    }
    pub async fn update_smtp_settings(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
        Json(payload): Json<UpdateSmtp>,
    ) -> Result<Json<SmtpSettings>, String> {
        let repo = SmtpSettingsRepository { db: &pool };
        repo.update(
            id,
            payload.enabled,
            payload.email,
            payload.smtp_server,
            payload.smtp_port,
            payload.username,
            payload.password,
            payload.use_tls,
            payload.from_email,
            payload.from_name,
            payload.subject_template,
            payload.body_template,
        )
        .await
        .map(Json)
        .map_err(|e| e.to_string())
    }
    pub async fn delete_smtp_settings(
        Path(id): Path<i64>,
        AuthUser(_): AuthUser,
        State(pool): State<Arc<SqlitePool>>,
    ) -> Result<(), String> {
        let repo = SmtpSettingsRepository { db: &pool };
        repo.delete(id).await.map_err(|e| e.to_string())
    }
}

pub fn app_with_state(pool: std::sync::Arc<SqlitePool>) -> Router {
    Router::new()
        .route("/health", get(crate::health::health_handler))
        .nest("/api/users",
            Router::new()
                .route("/", get(users_api::list_users).post(users_api::create_user))
                .route("/{id}", get(users_api::get_user).put(users_api::update_user).delete(users_api::delete_user))
        )
        .nest("/api/locations",
            Router::new()
                .route("/", get(locations_api::list_locations).post(locations_api::create_location))
                .route("/{id}", get(locations_api::get_location).put(locations_api::update_location).delete(locations_api::delete_location))
        )
        .nest("/api/weather-thresholds",
            Router::new()
                .route("/", get(|auth_user, state, query: axum::extract::Query<std::collections::HashMap<String, String>>| async move {
                    thresholds_api::list_thresholds(auth_user, state, query).await
                }).post(thresholds_api::create_threshold))
                .route("/{id}/{user_id}", get(thresholds_api::get_threshold).put(thresholds_api::update_threshold).delete(thresholds_api::delete_threshold))
        )
        .nest("/api/ntfy-settings",
            Router::new()
                .route("/user/{user_id}", get(notifications_api::get_ntfy_settings))
                .route("/", post(notifications_api::create_ntfy_settings))
                .route("/{id}", put(notifications_api::update_ntfy_settings).delete(notifications_api::delete_ntfy_settings))
        )
        .nest("/api/smtp-settings",
            Router::new()
                .route("/user/{user_id}", get(notifications_api::get_smtp_settings))
                .route("/", post(notifications_api::create_smtp_settings))
                .route("/{id}", put(notifications_api::update_smtp_settings).delete(notifications_api::delete_smtp_settings))
        )
        .fallback(not_found)
        .with_state(pool)
}

pub mod health;
pub mod locations;
pub mod notifications;
pub mod users;
pub mod weather_poller;
pub mod weather_thresholds;

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::body::to_bytes;
    use axum::http::{Request, StatusCode};
    use tower::ServiceExt; // for `oneshot`

    #[tokio::test]
    async fn test_health_endpoint() {
        let app = app_with_state(std::sync::Arc::new(
            sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap(),
        ));
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), 1024).await.unwrap();
        assert_eq!(&body[..], b"{\"status\":\"ok\"}");
    }
}