Prototype API (#1)

* Add oauth2 client

* Update LICENSE.txt

* Create .env.example

* Add dotenv to example

* Add oauth2 types

* Update lib.rs

* Update Cargo.toml

* Update lib.rs

* Add games routes
This commit is contained in:
Guilherme Werner
2023-12-24 08:23:10 -03:00
committed by GitHub
parent 92d5adc03b
commit 21daa668f8
14 changed files with 472 additions and 22 deletions

171
src/client.rs Normal file
View File

@ -0,0 +1,171 @@
// Copyright (c) Tribufu. All Rights Reserved.
use crate::games::Game;
use crate::oauth2::*;
use crate::VERSION;
use alnilam_consts::TARGET_TRIPLE;
use anyhow::{Error, Result};
use reqwest::header;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::Client;
#[derive(Clone)]
pub struct TribufuClient {
client_id: u64,
client_secret: String,
token: Option<OAuth2TokenResponse>,
}
impl TribufuClient {
//const BASE_URL: &'static str = "https://api.tribufu.com";
const BASE_URL: &'static str = "http://localhost:5000";
pub fn new(id: u64, secret: impl Into<String>) -> Result<TribufuClient> {
Ok(TribufuClient {
client_id: id,
client_secret: secret.into(),
token: None,
})
}
#[inline]
pub fn id(&self) -> u64 {
self.client_id
}
#[inline]
pub fn user_agent() -> String {
format!(
"Tribufu/{} (+https://api.tribufu.com; {})",
VERSION, TARGET_TRIPLE
)
}
#[inline]
fn default_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert("X-Tribufu-Language", HeaderValue::from_static("rust"));
headers.insert("X-Tribufu-Version", HeaderValue::from_static(VERSION));
headers
}
fn http_client(&self) -> Result<Client> {
let user_agent = Self::user_agent();
let mut headers = Self::default_headers();
if let Some(token) = &self.token {
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", token.access_token))?,
);
}
let http = Client::builder()
.user_agent(user_agent)
.default_headers(headers)
.build()?;
Ok(http)
}
pub async fn get_token(&mut self, server_id: Option<u64>) -> Result<()> {
let server_id = if let Some(server_id) = server_id {
Some(server_id.to_string())
} else {
None
};
let body = OAuth2TokenRequest {
grant_type: OAuth2GrantType::ClientCredentials,
code: None,
refresh_token: None,
username: None,
password: None,
client_id: Some(self.client_id.to_string()),
client_secret: Some(self.client_secret.clone()),
redirect_uri: None,
server_id,
};
let url = format!("{}/v1/oauth2/token", Self::BASE_URL);
let response = self.http_client()?.post(url).form(&body).send().await?;
if response.status() != 200 {
return Err(Error::msg(format!(
"Failed to get token: {}",
response.status()
)));
}
self.token = Some(response.json().await?);
Ok(())
}
pub async fn refresh_token_token(&mut self) -> Result<()> {
let token = if let Some(token) = &self.token {
token
} else {
return Err(Error::msg(
format!("Failed to refresh: self.token == None",),
));
};
if token.refresh_token.is_none() {
return Err(Error::msg(format!(
"Failed to refresh: self.token.refresh_token == None",
)));
}
let body = OAuth2TokenRequest {
grant_type: OAuth2GrantType::RefreshToken,
code: None,
refresh_token: token.refresh_token.clone(),
username: None,
password: None,
client_id: Some(self.client_id.to_string()),
client_secret: Some(self.client_secret.clone()),
redirect_uri: None,
server_id: None,
};
let url = format!("{}/v1/oauth2/token", Self::BASE_URL);
let response = self.http_client()?.post(url).form(&body).send().await?;
if response.status() != 200 {
return Err(Error::msg(format!(
"Failed to get token: {}",
response.status()
)));
}
self.token = Some(response.json().await?);
Ok(())
}
pub async fn get_games(&self) -> Result<Vec<Game>> {
let url = format!("{}/v1/packages", Self::BASE_URL);
let response = self.http_client()?.get(url).send().await?;
Ok(response.json().await?)
}
pub async fn get_game(&self, id: u64) -> Result<Game> {
let url = format!("{}/v1/packages/{}", Self::BASE_URL, id);
let response = self.http_client()?.get(url).send().await?;
Ok(response.json().await?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_client() {
let client = TribufuClient::new(0, "client_secret").unwrap();
assert_eq!(client.id(), 0);
}
}

29
src/games.rs Normal file
View File

@ -0,0 +1,29 @@
// Copyright (c) Tribufu. All Rights Reserved.
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DisplayFromStr};
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Game {
#[serde_as(as = "DisplayFromStr")]
pub id: u64,
pub name: String,
pub description: Option<String>,
pub icon_url: Option<String>,
pub banner_url: Option<String>,
pub capsule_image_url: Option<String>,
pub library_image_url: Option<String>,
pub slug: Option<String>,
pub game_port: Option<u16>,
pub query_port: Option<u16>,
pub rcon_port: Option<u16>,
pub steam_app_id: Option<u32>,
pub steam_server_app_id: Option<u32>,
pub rust_gamedig_id: Option<String>,
pub node_gamedig_id: Option<String>,
pub server_connect_url: Option<String>,
pub created: NaiveDateTime,
pub updated: Option<NaiveDateTime>,
}

12
src/lib.rs Normal file
View File

@ -0,0 +1,12 @@
// Copyright (c) Tribufu. All Rights Reserved.
#![allow(dead_code)]
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub mod client;
pub mod games;
pub mod oauth2;
pub mod token;
pub use client::*;

153
src/oauth2.rs Normal file
View File

@ -0,0 +1,153 @@
// Copyright (c) Tribufu. All Rights Reserved.
use serde::{Deserialize, Serialize};
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuth2ResponseType {
Code,
Token,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuth2ClientType {
Confidential,
Public,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuth2TokenHintType {
AccessToken,
RefreshToken,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuth2GrantType {
AuthorizationCode,
ClientCredentials,
DeviceCode,
Password,
RefreshToken,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuth2AuthorizeError {
AccessDenied,
InvalidRequest,
InvalidScope,
ServerError,
TemporarilyUnavailable,
UnauthorizedClient,
UnsupportedResponseType,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OAuth2TokenType {
Bearer,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2AuthorizeRequest {
pub response_type: OAuth2ResponseType,
pub client_id: String,
pub client_secret: Option<String>,
pub redirect_uri: String,
pub scope: Option<String>,
pub state: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2CodeResponse {
pub code: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2ErrorResponse {
pub error: OAuth2AuthorizeError,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_uri: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2TokenRequest {
pub grant_type: OAuth2GrantType,
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_uri: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub server_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2TokenResponse {
pub token_type: OAuth2TokenType,
pub access_token: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
pub expires_in: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2RevokeRequest {
pub token: String,
pub token_type_hint: OAuth2TokenHintType,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OAuth2IntrospectionResponse {
pub active: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub exp: Option<i64>,
}
impl OAuth2IntrospectionResponse {
fn inative() -> Self {
Self {
active: false,
client_id: None,
username: None,
scope: None,
exp: None,
}
}
}

11
src/token.rs Normal file
View File

@ -0,0 +1,11 @@
// Copyright (c) Tribufu. All Rights Reserved.
use crate::oauth2::OAuth2TokenResponse;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Credentials {
ApiKey(String),
Token(OAuth2TokenResponse),
}