DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 6f6fb6cf5d5da74bf4f8fc516713b1143c4742d7 deck-builder/shared/src/api/user/mod.rs -rw-r--r-- 2.0 KiB
6f6fb6cfJonni Liljamo feat(shared): relocate types, add gamestate consts 1 year, 9 months ago
                                                                                
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
/*
 * This file is part of laurelin/shared
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use reqwest;
use serde::{Deserialize, Serialize};

use crate::{error::api::APIError, types::user::User};

use super::macros::extract_cookie;

#[derive(Serialize)]
pub struct PostLogin {
    pub email: String,
    pub password: String,
}

#[derive(Deserialize)]
#[serde(untagged)]
pub enum ResponseLogin {
    Error(APIError),
    Ok(User),
}

#[derive(Deserialize)]
pub struct ResponseLoginWrapper {
    pub response: ResponseLogin,
    pub cookie: String,
}

pub fn login(api_address: &str, email: &str, password: &str) -> ResponseLoginWrapper {
    let client = reqwest::blocking::Client::new();

    let resp = client
        .post(&format!("{}/user/login", api_address))
        .json(&PostLogin {
            email: email.to_string(),
            password: password.to_string(),
        })
        .send()
        .unwrap();

    ResponseLoginWrapper {
        cookie: extract_cookie!(resp),
        response: resp.json().unwrap(),
    }
}

#[derive(Serialize)]
pub struct PostRegister {
    pub username: String,
    pub email: String,
    pub password: String,
}

#[derive(Deserialize)]
#[serde(untagged)]
pub enum ResponseRegister {
    Error(APIError),
    Ok(User),
}

#[derive(Deserialize)]
pub struct ResponseRegisterWrapper {
    pub response: ResponseRegister,
    pub cookie: String,
}

pub fn register(
    api_address: &str,
    username: &str,
    email: &str,
    password: &str,
) -> ResponseRegisterWrapper {
    let client = reqwest::blocking::Client::new();

    let resp = client
        .post(&format!("{}/user", api_address))
        .json(&PostRegister {
            username: username.to_string(),
            email: email.to_string(),
            password: password.to_string(),
        })
        .send()
        .unwrap();

    ResponseRegisterWrapper {
        cookie: extract_cookie!(resp),
        response: resp.json().unwrap(),
    }
}