summaryrefslogtreecommitdiffstats
path: root/src/api/users.rs
blob: 24bcf9700e1924c0cf02b8ebd96251f4acba4d2b (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
use std::str::FromStr;

use axum::{
    extract::{Path, State},
    response::IntoResponse,
    Json,
};
use axum_extra::routing::Resource;
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use time::OffsetDateTime;
use uuid::Uuid;

use crate::{
    auth::{credentials::Credential, AccessClaims},
    state::{AppState, KVStore},
};

use super::error::Error;

pub fn router() -> Resource<AppState> {
    Resource::named("users").create(create).show(show)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct User {
    pub id: Uuid,
    pub name: String,
    pub email: String,
    pub created_at: OffsetDateTime,
    pub updated_at: OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Registration {
    pub name: String,
    pub email: String,
    pub password: String,
}

pub async fn create(
    State(state): State<AppState>,
    Json(Registration {
        name,
        email,
        password,
    }): Json<Registration>,
) -> Result<impl IntoResponse, Error> {
    email_address::EmailAddress::from_str(&email)?;

    // TODO: Move this into a micro service, possibly behind a feature flag.
    let (status, (access, refresh)) =
        crate::auth::credentials::create(State(state.pool.clone()), Json(Credential { password }))
            .await?;

    let user = User {
        id: refresh.sub,
        name,
        email,
        created_at: OffsetDateTime::now_utc(),
        updated_at: OffsetDateTime::now_utc(),
    };

    let tx = state.kv_store.transaction();
    tx.put(refresh.sub, serde_json::to_vec(&user).unwrap())
        .unwrap();

    Ok((status, access, refresh, Json(user)))
}

pub async fn show(
    Path(uuid): Path<Uuid>,
    State(state): State<AppState>,
    _: AccessClaims,
) -> Result<Json<User>, Error> {
    let tx = state.kv_store.transaction();
    Ok(tx
        .get(uuid)
        .unwrap()
        .ok_or_else(|| Error::UserNotFound)
        .map(|s| serde_json::from_slice(&s))?
        .map(Json)
        .unwrap())
    //sqlx::query_as!(User, "SELECT * FROM user_ WHERE id = $1 LIMIT 1", uuid)
    //    .fetch_optional(&pool)
    //    .await?
    //    .ok_or_else(|| Error::UserNotFound)
    //    .map(Json)
}

#[cfg(test)]
mod tests {
    use super::*;

    use axum::{
        body::Body,
        http::{
            header::{CONTENT_TYPE, COOKIE},
            Request, StatusCode,
        },
        Router,
    };

    use http_body_util::BodyExt;
    use tower::ServiceExt;

    use crate::{
        auth::AccessClaims,
        tests::{setup_test_env, TestResult},
    };

    const USER_ID: Uuid = uuid::uuid!("4c14f795-86f0-4361-a02f-0edb966fb145");
    const USER_NAME: &str = "Arthur Dent";
    const USER_EMAIL: &str = "adent@earth.sol";
    const USER_PASSWORD: &str = "solongandthanksforallthefish";

    #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))]
    async fn test_get_ok_self(pool: PgPool) -> TestResult {
        setup_test_env();

        let router = Router::new()
            .merge(router())
            .with_state(AppState::with_pool(pool, "./rocks.db"));

        let request = Request::builder()
            .uri(format!("/users/{}", USER_ID))
            .header(
                COOKIE,
                AccessClaims::issue(USER_ID).as_cookie()?.to_string(),
            )
            .body(Body::empty())?;

        let response = router.oneshot(request).await?;

        assert_eq!(StatusCode::OK, response.status());

        let body_bytes = response.into_body().collect().await?.to_bytes();
        let User {
            id, name, email, ..
        } = serde_json::from_slice(&body_bytes)?;

        assert_eq!(USER_ID, id);
        assert_eq!(USER_NAME, name);
        assert_eq!(USER_EMAIL, email);

        Ok(())
    }

    #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))]
    async fn test_get_ok_other(pool: PgPool) -> TestResult {
        setup_test_env();

        let router = Router::new()
            .merge(router())
            .with_state(AppState::with_pool(pool, "./rocks.db"));

        let request = Request::builder()
            .uri(format!("/users/{}", USER_ID))
            .header(
                COOKIE,
                AccessClaims::issue(uuid::Uuid::new_v4())
                    .as_cookie()?
                    .to_string(),
            )
            .body(Body::empty())?;

        let response = router.oneshot(request).await?;

        assert_eq!(StatusCode::OK, response.status());

        let body_bytes = response.into_body().collect().await?.to_bytes();
        let User {
            id, name, email, ..
        } = serde_json::from_slice(&body_bytes)?;

        assert_eq!(USER_ID, id);
        assert_eq!(USER_NAME, name);
        assert_eq!(USER_EMAIL, email);

        Ok(())
    }

    #[sqlx::test]
    async fn test_get_not_found(pool: PgPool) -> TestResult {
        setup_test_env();

        let router = Router::new()
            .merge(router())
            .with_state(AppState::with_pool(pool, "./rocks.db"));

        let request = Request::builder()
            .uri(format!("/users/{}", USER_ID))
            .header(
                COOKIE,
                AccessClaims::issue(USER_ID).as_cookie()?.to_string(),
            )
            .body(Body::empty())?;

        let response = router.oneshot(request).await?;

        assert_eq!(StatusCode::NOT_FOUND, response.status());

        Ok(())
    }

    #[sqlx::test]
    async fn test_get_unauthorized_invalid_token_format(pool: PgPool) -> TestResult {
        setup_test_env();

        let router = Router::new()
            .merge(router())
            .with_state(AppState::with_pool(pool, "./rocks.db"));

        let request = Request::builder()
            .uri(format!("/users/{}", USER_ID))
            .header(COOKIE, "token=sadfasdfsdfs")
            .body(Body::empty())?;

        let response = router.oneshot(request).await?;

        assert_eq!(StatusCode::UNPROCESSABLE_ENTITY, response.status());

        Ok(())
    }

    #[sqlx::test]
    async fn test_get_unauthorized_missing_token(pool: PgPool) -> TestResult {
        setup_test_env();

        let router = Router::new()
            .merge(router())
            .with_state(AppState::with_pool(pool, "./rocks.db"));

        let request = Request::builder()
            .uri(format!("/users/{}", USER_ID))
            .body(Body::empty())?;

        let response = router.oneshot(request).await?;

        assert_eq!(StatusCode::UNAUTHORIZED, response.status());

        Ok(())
    }

    #[sqlx::test]
    async fn test_post_created(pool: PgPool) -> TestResult {
        setup_test_env();

        let router = Router::new()
            .merge(router())
            .with_state(AppState::with_pool(pool, "./rocks.db"));

        let user = serde_json::json!( {
            "name": USER_NAME,
            "email": USER_EMAIL,
            "password": USER_PASSWORD,
        });

        let request = Request::builder()
            .uri("/users")
            .method("POST")
            .header(CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())
            .body(Body::from(serde_json::to_vec(&user)?))?;

        let response = router.oneshot(request).await?;

        assert_eq!(StatusCode::CREATED, response.status());

        let body_bytes = response.into_body().collect().await?.to_bytes();
        let User { name, email, .. } = serde_json::from_slice(&body_bytes)?;

        assert_eq!(USER_NAME, name);
        assert_eq!(USER_EMAIL, email);

        Ok(())
    }

    #[sqlx::test(fixtures(path = "../../fixtures", scripts("users")))]
    async fn test_post_conflict(pool: PgPool) -> TestResult {
        setup_test_env();

        let router = Router::new()
            .merge(router())
            .with_state(AppState::with_pool(pool, "./rocks.db"));

        let user = serde_json::json!( {
            "name": USER_NAME,
            "email": USER_EMAIL,
            "password": USER_PASSWORD,
        });

        let request = Request::builder()
            .uri("/users")
            .method("POST")
            .header(CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())
            .body(Body::from(serde_json::to_vec(&user)?))?;

        let response = router.oneshot(request).await?;

        assert_eq!(StatusCode::CONFLICT, response.status());

        Ok(())
    }
}