/*
* 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;
use super::types::User;
#[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();
let mut cookie = String::from("");
for c in resp.cookies() {
if c.name() == "id" {
cookie = c.value().to_string();
}
}
ResponseLoginWrapper {
response: resp.json().unwrap(),
cookie,
}
}
#[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();
let mut cookie = String::from("");
for c in resp.cookies() {
if c.name() == "id" {
cookie = c.value().to_string();
}
}
ResponseRegisterWrapper {
response: resp.json().unwrap(),
cookie,
}
}