initial commit

- login works
- basic documentation
This commit is contained in:
2026-05-09 06:28:09 +02:00
commit d2a2baebc8
16 changed files with 2524 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
use std::fmt::Display;
use serde::Deserialize;
#[derive(Debug, Deserialize, thiserror::Error)]
pub struct AuthError {
error: String,
error_description: Option<String>,
}
impl Display for AuthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let error = &self.error;
if let Some(ref error_description) = self.error_description {
writeln!(f, "authentication type '{error}' with message '{error_description:?}'")
} else {
writeln!(f, "authentication type '{error}'")
}
}
}
+95
View File
@@ -0,0 +1,95 @@
use std::{
ffi::OsStr,
fs::File,
io::{self},
};
use curl::easy::{Easy, List};
use serde::Deserialize;
mod api;
#[derive(Debug, Deserialize)]
pub struct KeycloakAPI {
base_url: String,
default_realm: String,
client_id: String,
client_secret: String,
}
#[derive(Debug, thiserror::Error)]
pub enum LoadError {
#[error("opening configuration: {0}")]
OpenConfig(#[from] io::Error),
#[error("parsing configuration: {0}")]
ParseConfig(#[from] serde_json::Error),
}
#[derive(Debug, thiserror::Error)]
pub enum LoginError {
#[error("on POST request: {0}")]
Fetch(#[from] curl::Error),
#[error("unexpected API response: {0}")]
InvalidAPIResponse(#[from] serde_json::Error),
#[error("from the API: {0}")]
InvalidLogin(#[from] api::AuthError),
}
fn curl_request(uri: &str, body: &[u8], header: &str) -> Result<(u32, Vec<u8>), curl::Error> {
let mut easy = Easy::new();
easy.post(true)?;
let mut headers = List::new();
headers.append(header)?;
easy.http_headers(headers)?;
easy.url(uri)?;
easy.post_fields_copy(body)?;
let mut response_data = Vec::new();
{
let mut transfer = easy.transfer();
transfer.write_function(|data| {
response_data.extend_from_slice(data);
Ok(data.len())
})?;
transfer.perform()?;
}
Ok((easy.response_code()?, response_data))
}
impl KeycloakAPI {
pub fn load_from_configuration(cfg: &OsStr) -> Result<Self, LoadError> {
let f = File::open(cfg)?;
Ok(serde_json::from_reader(f)?)
}
pub fn check_credentials(&self, username: &str, password: &str) -> Result<(), LoginError> {
let body = format!(
"grant_type=password&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}&username={USERNAME}&password={PASSWORD}",
CLIENT_ID = urlencoding::encode(&self.client_id),
CLIENT_SECRET = urlencoding::encode(&self.client_secret),
USERNAME = urlencoding::encode(username),
PASSWORD = urlencoding::encode(password),
);
let (status_code, body) = curl_request(
&format!(
"{}/realms/{}/protocol/openid-connect/token",
self.base_url, self.default_realm,
),
body.as_bytes(),
"Content-Type: application/x-www-form-urlencoded",
)?;
if status_code == 200 {
Ok(())
} else {
Err(LoginError::InvalidLogin(serde_json::from_slice(&body)?))
}
}
}