Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HTTP API #115

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 84 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ duration-str = "0.11.2"
version-compare = "0.2"
mail-send = "0.4.7"
mail-builder = "0.3.2"
axum = "0.7.5"
axum-extra = {version = "0.9.3", features = ["typed-header"]}
headers = "0.4.0"

[target.'cfg(windows)'.build-dependencies]
winres = "0.1"
Expand Down
13 changes: 13 additions & 0 deletions config/Config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,19 @@ generate_pub = false
# Server language. Should match a ron file in the lang directory
lang = "en"

[api]
# Set to true to enable the REOSERV HTTP API
enabled = false

# Host IP the API will listen for incoming requests on
host = "0.0.0.0"

# Host Port the API will listen for incoming requests on
port = "3000"

# Minutes a user access token is considered valid
access_token_ttl = 20

[database]
host = "127.0.0.1"
port = "3306"
Expand Down
13 changes: 13 additions & 0 deletions db-init/1-init.sql
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,19 @@ CREATE TABLE `QuestProgress` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `AccessToken`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `AccessToken` (
`id` INT NOT NULL AUTO_INCREMENT,
`account_id` INT NOT NULL,
`token` VARCHAR(32) NOT NULL,
`ttl` TINYINT(3) NOT NULL DEFAULT '20',
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
CONSTRAINT `access_token_account_id` FOREIGN KEY (`account_id`) REFERENCES `Account` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
Expand Down
8 changes: 8 additions & 0 deletions src/api/account.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#[derive(Debug, Serialize)]
pub struct Account {
pub id: i32,
pub username: String,
pub email: String,
pub real_name: String,
pub location: String,
}
27 changes: 27 additions & 0 deletions src/api/app_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};

#[derive(Debug)]
pub struct AppError(anyhow::Error);

// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
error!("Application error: {:#}", self.0);

(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong").into_response()
}
}

// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into
// `Result<_, AppError>`. That way you don't need to do that manually.
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}
22 changes: 22 additions & 0 deletions src/api/app_state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
use axum::extract::FromRef;
use mysql_async::Pool;

use crate::world::WorldHandle;

#[derive(Clone)]
pub struct AppState {
pub pool: Pool,
pub world: WorldHandle,
}

impl FromRef<AppState> for Pool {
fn from_ref(state: &AppState) -> Self {
state.pool.clone()
}
}

impl FromRef<AppState> for WorldHandle {
fn from_ref(state: &AppState) -> Self {
state.world.clone()
}
}
7 changes: 7 additions & 0 deletions src/api/generate_access_token.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};

pub fn generate_access_token() -> String {
let mut rng = thread_rng();
(0..32).map(|_| rng.sample(Alphanumeric) as char).collect()
}
11 changes: 11 additions & 0 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
mod account;
mod app_state;
mod generate_access_token;
mod run_api;
use app_state::AppState;
mod user;
pub use run_api::run_api;
use user::User;
mod app_error;
mod routes;
use app_error::AppError;
49 changes: 49 additions & 0 deletions src/api/routes/account.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use axum::{extract::State, response::IntoResponse, Json};
use mysql_async::{params, prelude::Queryable, Params, Pool, Row};

use crate::api::{
account::Account,
user::{AuthError, User},
};

pub async fn get_account(
user: User,
State(pool): State<Pool>,
) -> Result<impl IntoResponse, AuthError> {
let mut conn = match pool.get_conn().await {
Ok(conn) => conn,
Err(e) => {
error!("Failed to get database connection: {}", e);
return Err(AuthError);
}
};

let row = match conn
.exec_first::<Row, &str, Params>(
include_str!("../../sql/get_account.sql"),
params! {
"id" => &user.id
},
)
.await
{
Ok(Some(row)) => row,
Ok(None) => {
return Err(AuthError);
}
Err(e) => {
error!("Error getting account: {}", e);
return Err(AuthError);
}
};

let account = Account {
id: row.get::<i32, &str>("id").unwrap(),
username: row.get::<String, &str>("name").unwrap(),
email: row.get::<String, &str>("email").unwrap(),
real_name: row.get::<String, &str>("real_name").unwrap(),
location: row.get::<String, &str>("location").unwrap(),
};

Ok(Json(account))
}
30 changes: 30 additions & 0 deletions src/api/routes/classes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use axum::{extract::Path, http::StatusCode, response::IntoResponse, Json};

use crate::CLASS_DB;

pub async fn get_class_list() -> impl IntoResponse {
let classes = CLASS_DB
.classes
.iter()
.take_while(|class| class.name != "eof")
.enumerate()
.map(|(index, class)| ClassListClass {
id: index as i32 + 1,
name: class.name.clone(),
})
.collect::<Vec<_>>();
Json(classes).into_response()
}

pub async fn get_class(Path(id): Path<i32>) -> impl IntoResponse {
match CLASS_DB.classes.get(id as usize - 1) {
Some(class) => Json(class).into_response(),
None => (StatusCode::NOT_FOUND).into_response(),
}
}

#[derive(Serialize)]
struct ClassListClass {
id: i32,
name: String,
}
Loading