1use crate::database::Database;
2use crate::model::{DatabaseError, LabelCreate, TokenPermission};
3use databeam::prelude::DefaultReturn;
4
5use axum::response::IntoResponse;
6use axum::{
7 extract::{Path, State},
8 Json,
9};
10use axum_extra::extract::cookie::CookieJar;
11
12pub async fn get_request(
14 State(database): State<Database>,
15 Path(id): Path<i64>,
16) -> impl IntoResponse {
17 let label = match database.get_label(id).await {
19 Ok(i) => i,
20 Err(e) => return Json(e.to_json()),
21 };
22
23 Json(DefaultReturn {
25 success: true,
26 message: id.to_string(),
27 payload: Some(label),
28 })
29}
30
31pub async fn create_request(
33 jar: CookieJar,
34 State(database): State<Database>,
35 Json(props): Json<LabelCreate>,
36) -> impl IntoResponse {
37 let auth_user = match jar.get("__Secure-Token") {
39 Some(c) => {
40 let token = c.value_trimmed();
41
42 match database.get_profile_by_unhashed(token).await {
43 Ok(ua) => {
44 if !ua
46 .token_context_from_token(&token)
47 .can_do(TokenPermission::ManageAssets)
48 {
49 return Json(DatabaseError::NotAllowed.to_json());
50 }
51
52 ua
54 }
55 Err(e) => return Json(e.to_json()),
56 }
57 }
58 None => return Json(DatabaseError::NotAllowed.to_json()),
59 };
60
61 let label = match database
63 .create_label(&props.name, props.id, &auth_user.id)
64 .await
65 {
66 Ok(m) => m,
67 Err(e) => return Json(e.to_json()),
68 };
69
70 Json(DefaultReturn {
71 success: true,
72 message: "Label created".to_string(),
73 payload: Some(label),
74 })
75}
76
77pub async fn delete_request(
79 jar: CookieJar,
80 Path(id): Path<i64>,
81 State(database): State<Database>,
82) -> impl IntoResponse {
83 let auth_user = match jar.get("__Secure-Token") {
85 Some(c) => match database.get_profile_by_unhashed(c.value_trimmed()).await {
86 Ok(ua) => ua,
87 Err(e) => return Json(e.to_json()),
88 },
89 None => return Json(DatabaseError::NotAllowed.to_json()),
90 };
91
92 if let Err(e) = database.delete_label(id, auth_user).await {
94 return Json(e.to_json());
95 }
96
97 Json(DefaultReturn {
98 success: true,
99 message: "Label deleted".to_string(),
100 payload: (),
101 })
102}