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
use crate::db::{DBEntity, User, ZoneOwnership};
use crate::error_result_json;
use crate::zones::FileZoneRecord;
use goatns_macros::check_api_auth;
use tower_sessions::Session;

use super::*;

#[async_trait]
impl APIEntity for FileZoneRecord {
    /// Save the entity to the database
    async fn api_create(
        State(state): State<GoatState>,
        session: Session,
        Json(payload): Json<serde_json::Value>,
    ) -> Result<Json<Box<Self>>, (StatusCode, Json<ErrorResult>)> {
        check_api_auth!();

        let record: Self = match serde_json::from_value(payload) {
            Ok(val) => val,
            Err(err) => {
                eprintln!("Failed to parse object: {err:?}");
                return error_result_json!("Failed to parse object", StatusCode::BAD_REQUEST);
            }
        };

        let mut txn = state.connpool().await.begin().await.unwrap();
        println!(
            "looking for ZO for user: {} zoneid: {}",
            user.id.unwrap(),
            record.zoneid.unwrap()
        );
        if let Err(err) = ZoneOwnership::get_ownership_by_userid(
            &mut txn,
            &user.id.unwrap(),
            &record.zoneid.unwrap(),
        )
        .await
        {
            eprintln!("Error getting ownership: {err:?}");
            return error_result_json!("", StatusCode::UNAUTHORIZED);
        };

        match record.save_with_txn(&mut txn).await {
            Err(err) => {
                eprintln!("Error saving record: {err:?}");
                // TODO: this needs to handle index conflicts
                error_result_json!("Error saving record", StatusCode::BAD_REQUEST)
            }
            Ok(val) => {
                if let Err(err) = txn.commit().await {
                    // TODO: This error message needs improving
                    eprintln!("error committing transaction! {err:?}");
                    return error_result_json!(
                        "Error saving record, see the admins",
                        StatusCode::INTERNAL_SERVER_ERROR
                    );
                }
                Ok(Json(val))
            }
        }
    }
    /// HTTP Put <https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT>
    async fn api_update(
        State(state): State<GoatState>,
        session: Session,
        Json(payload): Json<serde_json::Value>,
    ) -> Result<Json<String>, (StatusCode, Json<ErrorResult>)> {
        check_api_auth!();

        let record: Self = match serde_json::from_value(payload) {
            Ok(val) => val,
            Err(err) => {
                eprintln!("Failed to parse object: {err:?}");
                return error_result_json!("Failed to parse object", StatusCode::BAD_REQUEST);
            }
        };
        let mut txn = state.connpool().await.begin().await.unwrap();

        let res = match record.update_with_txn(&mut txn).await {
            Ok(val) => val,
            Err(err) => {
                // TODO: this should handle missing OR failures
                eprintln!("Error getting record: {err:?}");
                return error_result_json!("", StatusCode::NOT_FOUND);
            }
        };

        if let Err(err) = ZoneOwnership::get_ownership_by_userid(
            &mut txn,
            &user.id.unwrap(),
            &res.zoneid.unwrap(),
        )
        .await
        {
            eprintln!("Error getting ownership: {err:?}");
            return error_result_json!("", StatusCode::UNAUTHORIZED);
        };

        Ok(Json(serde_json::to_string(&res).unwrap()))
    }
    async fn api_get(
        State(state): State<GoatState>,
        session: Session,
        Path(id): Path<i64>,
    ) -> Result<Json<Box<Self>>, (StatusCode, Json<ErrorResult>)> {
        check_api_auth!();

        let pool = state.connpool().await;
        let res = match FileZoneRecord::get(&pool, id).await {
            Ok(val) => val,
            Err(err) => {
                // TODO: this should handle missing OR failures
                eprintln!("Error getting record: {err:?}");
                return error_result_json!("", StatusCode::NOT_FOUND);
            }
        };
        Ok(Json(res))
    }

    /// Delete an object
    /// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE>
    async fn api_delete(
        State(state): State<GoatState>,
        session: Session,
        Path(id): Path<i64>,
    ) -> Result<StatusCode, (StatusCode, Json<ErrorResult>)> {
        check_api_auth!();

        let mut txn = state.connpool().await.begin().await.unwrap();

        let record = match FileZoneRecord::get_with_txn(&mut txn, &id).await {
            Ok(val) => val,
            Err(err) => {
                let resmsg = format!("error getting record: {err:?}");
                return error_result_json!(resmsg.as_str(), StatusCode::UNAUTHORIZED);
            }
        };

        if let Err(err) = ZoneOwnership::get_ownership_by_userid(
            &mut txn,
            &user.id.unwrap(),
            &record.zoneid.unwrap(),
        )
        .await
        {
            eprintln!("Error getting ownership: {err:?}");
            return error_result_json!("no zone ownership found", StatusCode::UNAUTHORIZED);
        };

        if let Err(err) = record.delete_with_txn(&mut txn).await {
            // TODO: This error message needs improving
            eprintln!("error committing transaction! {err:?}");
            return error_result_json!(
                "Error deleting record, see the admins",
                StatusCode::INTERNAL_SERVER_ERROR
            );
        }
        if let Err(err) = txn.commit().await {
            // TODO: This error message needs improving
            eprintln!("error committing transaction! {err:?}");
            return error_result_json!(
                "Error deleting record, see the admins",
                StatusCode::INTERNAL_SERVER_ERROR
            );
        };

        Ok(StatusCode::OK)
    }
}