1
use std::{collections::HashMap, error::Error as StdError};
2

            
3
use axum::{
4
    body::Body,
5
    extract::{Path, Request, State},
6
    response::IntoResponse,
7
    routing, Router,
8
};
9
use bytes::{Bytes, BytesMut};
10
use csv::WriterBuilder;
11
use futures_util::StreamExt;
12
use log::error;
13
use serde::{Deserialize, Serialize};
14
use serde_json::{Deserializer, Map, Value};
15

            
16
use sylvia_iot_corelib::err::ErrResp;
17

            
18
use super::{super::State as AppState, api_bridge, list_api_bridge, ListResp};
19

            
20
#[derive(Deserialize)]
21
struct UserIdPath {
22
    user_id: String,
23
}
24

            
25
#[derive(Deserialize, Serialize)]
26
struct User {
27
    account: String,
28
    #[serde(rename = "createdAt")]
29
    created_at: String,
30
    #[serde(rename = "modifiedAt")]
31
    modified_at: String,
32
    #[serde(rename = "verifiedAt")]
33
    verified_at: Option<String>,
34
    #[serde(skip_serializing)]
35
    roles: HashMap<String, bool>,
36
    #[serde(rename(serialize = "role"))]
37
    roles_str: Option<String>,
38
    name: String,
39
    #[serde(skip_serializing)]
40
    info: Map<String, Value>,
41
    #[serde(rename(serialize = "info"))]
42
    info_str: Option<String>,
43
}
44

            
45
const CSV_FIELDS: &'static [u8] =
46
    b"\xEF\xBB\xBFaccount,createdAt,modifiedAt,verifiedAt,roles,name,info\n";
47

            
48
506
pub fn new_service(scope_path: &str, state: &AppState) -> Router {
49
506
    Router::new().nest(
50
506
        scope_path,
51
506
        Router::new()
52
506
            .route(
53
506
                "/",
54
506
                routing::get(get_user)
55
506
                    .patch(patch_user)
56
506
                    .post(post_admin_user),
57
506
            )
58
506
            .route("/count", routing::get(get_admin_user_count))
59
506
            .route("/list", routing::get(get_admin_user_list))
60
506
            .route(
61
506
                "/{user_id}",
62
506
                routing::get(get_admin_user)
63
506
                    .patch(patch_admin_user)
64
506
                    .delete(delete_admin_user),
65
506
            )
66
506
            .with_state(state.clone()),
67
506
    )
68
506
}
69

            
70
/// `GET /{base}/api/v1/user`
71
4
async fn get_user(state: State<AppState>, req: Request) -> impl IntoResponse {
72
    const FN_NAME: &'static str = "get_user";
73
4
    let api_path = format!("{}/api/v1/user", state.auth_base);
74
4
    let client = state.client.clone();
75
4

            
76
4
    api_bridge(FN_NAME, &client, req, api_path.as_str()).await
77
4
}
78

            
79
/// `PATCH /{base}/api/v1/user`
80
4
async fn patch_user(state: State<AppState>, req: Request) -> impl IntoResponse {
81
    const FN_NAME: &'static str = "patch_user";
82
4
    let api_path = format!("{}/api/v1/user", state.auth_base);
83
4
    let client = state.client.clone();
84
4

            
85
4
    api_bridge(FN_NAME, &client, req, api_path.as_str()).await
86
4
}
87

            
88
/// `POST /{base}/api/v1/user`
89
4
async fn post_admin_user(state: State<AppState>, req: Request) -> impl IntoResponse {
90
    const FN_NAME: &'static str = "post_admin_user";
91
4
    let api_path = format!("{}/api/v1/user", state.auth_base);
92
4
    let client = state.client.clone();
93
4

            
94
4
    api_bridge(FN_NAME, &client, req, api_path.as_str()).await
95
4
}
96

            
97
/// `GET /{base}/api/v1/user/count`
98
12
async fn get_admin_user_count(state: State<AppState>, req: Request) -> impl IntoResponse {
99
    const FN_NAME: &'static str = "get_admin_user_count";
100
12
    let api_path = format!("{}/api/v1/user/count", state.auth_base.as_str());
101
12
    let client = state.client.clone();
102
12

            
103
12
    api_bridge(FN_NAME, &client, req, api_path.as_str()).await
104
12
}
105

            
106
/// `GET /{base}/api/v1/user/list`
107
28
async fn get_admin_user_list(state: State<AppState>, req: Request) -> impl IntoResponse {
108
    const FN_NAME: &'static str = "get_admin_user_list";
109
28
    let api_path = format!("{}/api/v1/user/list", state.auth_base.as_str());
110
28
    let api_path = api_path.as_str();
111
28
    let client = state.client.clone();
112

            
113
4
    let (api_resp, resp_builder) =
114
28
        match list_api_bridge(FN_NAME, &client, req, api_path, false, "user").await {
115
24
            ListResp::Axum(resp) => return resp,
116
4
            ListResp::ArrayStream(api_resp, resp_builder) => (api_resp, resp_builder),
117
4
        };
118
4

            
119
4
    let mut resp_stream = api_resp.bytes_stream();
120
4
    let body = Body::from_stream(async_stream::stream! {
121
4
        yield Ok(Bytes::from(CSV_FIELDS));
122
4

            
123
4
        let mut buffer = BytesMut::new();
124
4
        while let Some(body) = resp_stream.next().await {
125
4
            match body {
126
4
                Err(e) => {
127
4
                    error!("[{}] get body error: {}", FN_NAME, e);
128
4
                    let err: Box<dyn StdError + Send + Sync> = Box::new(e);
129
4
                    yield Err(err);
130
4
                    break;
131
4
                }
132
4
                Ok(body) => buffer.extend_from_slice(&body[..]),
133
4
            }
134
4

            
135
4
            let mut json_stream = Deserializer::from_slice(&buffer[..]).into_iter::<User>();
136
4
            let mut index = 0;
137
4
            let mut finish = false;
138
4
            loop {
139
4
                if let Some(Ok(mut v)) = json_stream.next() {
140
4
                    if let Ok(roles_str) = serde_json::to_string(&v.roles) {
141
4
                        v.roles_str = Some(roles_str);
142
4
                    }
143
4
                    if let Ok(info_str) = serde_json::to_string(&v.info) {
144
4
                        v.info_str = Some(info_str);
145
4
                    }
146
4
                    let mut writer = WriterBuilder::new().has_headers(false).from_writer(vec![]);
147
4
                    if let Err(e) = writer.serialize(v) {
148
4
                        let err: Box<dyn StdError + Send + Sync> = Box::new(e);
149
4
                        yield Err(err);
150
4
                        finish = true;
151
4
                        break;
152
4
                    }
153
4
                    match writer.into_inner() {
154
4
                        Err(e) => {
155
4
                            let err: Box<dyn StdError + Send + Sync> = Box::new(e);
156
4
                            yield Err(err);
157
4
                            finish = true;
158
4
                            break;
159
4
                        }
160
4
                        Ok(row) => yield Ok(Bytes::copy_from_slice(row.as_slice())),
161
4
                    }
162
4
                    continue;
163
4
                }
164
4
                let offset = json_stream.byte_offset();
165
4
                if buffer.len() <= index + offset {
166
4
                    index = buffer.len();
167
4
                    break;
168
4
                }
169
4
                match buffer[index+offset] {
170
4
                    b'[' | b',' => {
171
4
                        index += offset + 1;
172
4
                        if buffer.len() <= index {
173
4
                            break;
174
4
                        }
175
4
                        json_stream =
176
4
                            Deserializer::from_slice(&buffer[index..]).into_iter::<User>();
177
4
                    }
178
4
                    b']' => {
179
4
                        finish = true;
180
4
                        break;
181
4
                    }
182
4
                    _ => break,
183
4
                }
184
4
            }
185
4
            if finish {
186
4
                break;
187
4
            }
188
4
            buffer = buffer.split_off(index);
189
4
        }
190
4
    });
191
4
    match resp_builder.body(body) {
192
        Err(e) => ErrResp::ErrRsc(Some(e.to_string())).into_response(),
193
4
        Ok(resp) => resp,
194
    }
195
28
}
196

            
197
/// `GET /{base}/api/v1/user/{userId}`
198
4
async fn get_admin_user(
199
4
    state: State<AppState>,
200
4
    Path(param): Path<UserIdPath>,
201
4
    req: Request,
202
4
) -> impl IntoResponse {
203
    const FN_NAME: &'static str = "get_admin_user";
204
4
    let api_path = format!("{}/api/v1/user/{}", state.auth_base, param.user_id);
205
4
    let client = state.client.clone();
206
4

            
207
4
    api_bridge(FN_NAME, &client, req, api_path.as_str()).await
208
4
}
209

            
210
/// `PATCH /{base}/api/v1/user/{userId}`
211
4
async fn patch_admin_user(
212
4
    state: State<AppState>,
213
4
    Path(param): Path<UserIdPath>,
214
4
    req: Request,
215
4
) -> impl IntoResponse {
216
    const FN_NAME: &'static str = "patch_admin_user";
217
4
    let api_path = format!("{}/api/v1/user/{}", state.auth_base, param.user_id);
218
4
    let client = state.client.clone();
219
4

            
220
4
    api_bridge(FN_NAME, &client, req, api_path.as_str()).await
221
4
}
222

            
223
/// `DELETE /{base}/api/v1/user/{userId}`
224
4
async fn delete_admin_user(
225
4
    state: State<AppState>,
226
4
    Path(param): Path<UserIdPath>,
227
4
    req: Request,
228
4
) -> impl IntoResponse {
229
    const FN_NAME: &'static str = "delete_admin_user";
230
4
    let api_path = format!("{}/api/v1/user/{}", state.auth_base, param.user_id);
231
4
    let client = state.client.clone();
232
4

            
233
4
    api_bridge(FN_NAME, &client, req, api_path.as_str()).await
234
4
}