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
use super::*;
use crate::db::DBEntity;

use crate::db::User;
use crate::db::ZoneOwnership;
use crate::error_result_json;
use crate::utils::check_valid_tld;
use crate::zones::FileZone;
use axum::extract::Path;
use axum::Json;
use goatns_macros::check_api_auth;
use serde::Deserialize;
use serde::Serialize;
use tower_sessions::Session;

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct FileZoneResponse {
    pub message: String,
    pub zone: Option<FileZone>,
    pub id: Option<i64>,
}

#[async_trait]
impl APIEntity for FileZone {
    async fn api_create(
        State(state): State<GoatState>,
        session: Session,
        Json(payload): Json<serde_json::Value>,
    ) -> Result<Json<Box<Self>>, (StatusCode, Json<ErrorResult>)> {
        #[cfg(test)]
        println!("Got api_create payload: {payload:?}");
        log::debug!("Got api_create payload: {payload:?}");

        check_api_auth!();

        let zone: FileZone = match serde_json::from_value(payload) {
            Ok(val) => val,
            Err(err) => {
                log::debug!("Failed to deser payload: {err:?}");
                let res = format!("Invalid payload: {err:?}");
                return error_result_json!(res.as_str(), StatusCode::BAD_REQUEST);
            }
        };

        if !check_valid_tld(&zone.name, &state.read().await.config.allowed_tlds) {
            return error_result_json!("Invalid TLD for this system", StatusCode::BAD_REQUEST);
        }

        // check to see if the zone exists
        let mut txn = state.connpool().await.begin().await.unwrap();

        match FileZone::get_by_name(&mut txn, &zone.name).await {
            Ok(_) => {
                log::debug!("Zone {} already exists, user sent POST", zone.name);
                return error_result_json!("Zone already exists!", StatusCode::BAD_REQUEST);
            }
            Err(err) => match err {
                sqlx::Error::RowNotFound => {}
                _ => {
                    log::debug!(
                        "Couldn't get zone  {}, something went wrong: {err:?}",
                        zone.name
                    );
                    return error_result_json!(
                        "Server error querying zone!",
                        StatusCode::INTERNAL_SERVER_ERROR
                    );
                }
            },
        };

        // if they got here there were no issues with querying the DB and it doesn't exist already!

        if let Err(err) = zone.save_with_txn(&mut txn).await {
            log::debug!(
                "Couldn't create zone  {}, something went wrong during save: {err:?}",
                zone.name
            );
            return error_result_json!(
                "Server error creating zone!",
                StatusCode::INTERNAL_SERVER_ERROR
            );
        }

        if let Err(err) = txn.commit().await {
            log::debug!(
                "Couldn't create zone {}, something went wrong committing transaction: {err:?}",
                zone.name
            );
            return error_result_json!(
                "Server error creating zone!",
                StatusCode::INTERNAL_SERVER_ERROR
            );
        }
        // start a new transaction!
        let mut txn = state.connpool().await.begin().await.unwrap();

        let zone = FileZone::get_by_name(&mut txn, &zone.name).await.unwrap();

        let ownership = ZoneOwnership {
            id: None,
            userid: user.id.unwrap(),
            zoneid: zone.id.unwrap(),
        };

        if let Err(err) = ownership.save_with_txn(&mut txn).await {
            log::debug!(
                "Couldn't store zone ownership {ownership:?}, something went wrong: {err:?}"
            );
            return error_result_json!(
                "Server error creating zone ownership, contact the admins!",
                StatusCode::INTERNAL_SERVER_ERROR
            );
        };

        if let Err(err) = txn.commit().await {
            log::debug!(
                "Couldn't create zone {}, something went wrong committing transaction: {err:?}",
                zone.name
            );
            return error_result_json!(
                "Server error creating zone, contact the admins!",
                StatusCode::INTERNAL_SERVER_ERROR
            );
        }
        log::debug!("Zone created by user={} zone={zone:?}", user.id.unwrap());

        return Ok(Json(zone));
    }

    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!();

        println!("{user:?}");
        #[cfg(test)]
        println!("zone api_update payload: {payload:?}");
        #[cfg(not(test))]
        log::debug!("zone api_update payload: {payload:?}");

        // deserialize the zone
        println!("about to deser input");
        let zone: FileZone = match serde_json::from_value(payload) {
            Ok(val) => val,
            Err(err) => {
                // TODO: make this a better log
                println!("Failed to deserialize user input in api_update: {err:?}");
                return Err((
                    StatusCode::BAD_REQUEST,
                    Json(ErrorResult {
                        message: "Invalid input".to_string(),
                    }),
                ));
            }
        };
        println!("deser'd zone: {zone:?}");

        if zone.id.is_none() {
            return error_result_json!("No zone ID specified", StatusCode::BAD_REQUEST);
        }
        if !check_valid_tld(&zone.name, &state.read().await.config.allowed_tlds) {
            return error_result_json!("Invalid TLD for this system", StatusCode::BAD_REQUEST);
        }

        // get a db transaction
        let connpool = state.connpool().await.clone();
        // TODO getting a transaction might fail
        let mut txn = match connpool.begin().await {
            Ok(val) => val,
            Err(err) => {
                log::error!("failed to get connection to the database: {err:?}");
                return error_result_json!(
                    "Failed to get a connection to the database!",
                    StatusCode::INTERNAL_SERVER_ERROR
                );
            }
        };
        // check the user owns the zone
        if let Err(err) =
            ZoneOwnership::get_ownership_by_userid(&mut txn, &user.id.unwrap(), &zone.id.unwrap())
                .await
        {
            // TODO: make this a better log
            println!("Failed to validate user owns zone: {err:?}");
            return Err((
                StatusCode::UNAUTHORIZED,
                Json(ErrorResult {
                    message: "".to_string(),
                }),
            ));
        };
        println!("looks like user owns zone");

        // save the zone data

        if let Err(err) = zone.save_with_txn(&mut txn).await {
            // TODO: make this a better log
            println!("Failed to save zone: {err:?}");
            return Err((
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResult {
                    message: "failed to save zone".to_string(),
                }),
            ));
        };
        if let Err(err) = txn.commit().await {
            // TODO: make this a better log
            println!("Failed to commit transaction while saving zone: {err:?}");
            return Err((
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResult {
                    message: "failed to save zone".to_string(),
                }),
            ));
        };
        Ok(Json("success".to_string()))
    }

    async fn api_delete(
        State(state): State<GoatState>,
        session: Session,
        Path(id): Path<i64>,
    ) -> Result<StatusCode, (StatusCode, Json<ErrorResult>)> {
        // let id = id;

        check_api_auth!();

        // let zone_id: i64 = match payload.get("id") {
        //     None => {
        //         log::debug!("api_delete for filezone and zone id not specified!");
        //         return error_result_json!(
        //             "Please include the field 'id' to specify the zone's domain id.",
        //             StatusCode::BAD_REQUEST
        //         );
        //     }
        //     Some(val) => val.as_i64().unwrap(),
        // };

        let mut txn = match state.connpool().await.begin().await {
            Ok(val) => val,
            Err(err) => {
                log::error!("Error getting txn: {err:?}");
                return error_result_json!(
                    "Internal server error",
                    StatusCode::INTERNAL_SERVER_ERROR
                );
            }
        };
        // get the zoneownership
        match ZoneOwnership::get_ownership_by_userid(&mut txn, &user.id.unwrap(), &id).await {
            Ok(val) => val,
            Err(err) => {
                log::error!(
                    "Failed to get ZoneOwnership userid={} zoneid={} error=\"{err:?}\"",
                    user.id.unwrap(),
                    id
                );
                match err {
                    sqlx::Error::RowNotFound => {
                        return error_result_json!(
                            format!("Zone ID {} not found", id).as_str(),
                            StatusCode::NOT_FOUND
                        )
                    }
                    _ => {
                        return error_result_json!(
                            "Internal server error",
                            StatusCode::INTERNAL_SERVER_ERROR
                        )
                    }
                };
            }
        };

        // get the zone
        let zone = match FileZone::get_with_txn(&mut txn, &id).await {
            Ok(val) => val,
            Err(err) => {
                log::error!(
                    "Failed to get Zone during api_delete zoneid={} error=\"{err:?}\"",
                    id
                );
                return error_result_json!(
                    "Internal server error",
                    StatusCode::INTERNAL_SERVER_ERROR
                );
            }
        };

        let res = match zone.delete_with_txn(&mut txn).await {
            Ok(_) => Ok(StatusCode::OK),
            Err(err) => {
                log::error!(
                    "Failed to delete Zone during api_delete zoneid={} error=\"{err:?}\"",
                    id
                );
                return error_result_json!(
                    "Internal server error",
                    StatusCode::INTERNAL_SERVER_ERROR
                );
            }
        };

        if let Err(err) = txn.commit().await {
            log::error!("Failed to commit txn for zone.delete during api_delete zoneid={} error=\"{err:?}\"", id);
            return error_result_json!("Internal server error", StatusCode::INTERNAL_SERVER_ERROR);
        };
        res
    }
    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 mut txn = state.connpool().await.begin().await.unwrap();

        if ZoneOwnership::get_ownership_by_userid(&mut txn, &user.id.unwrap(), &id)
            .await
            .is_err()
        {
            log::error!(
                "User {} not authorized for zoneid={}",
                &user.id.unwrap(),
                id
            );
            return error_result_json!("", StatusCode::UNAUTHORIZED);
        };

        log::debug!("Searching for zone id {id:?}");
        let zone = match FileZone::get(&state.connpool().await, id).await {
            Ok(val) => val,
            Err(err) => todo!("{err:?}"),
        };

        Ok(Json::from(zone))
    }
}