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

Builtin basic auth fang #191

Merged
merged 2 commits into from
Jun 26, 2024
Merged
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
3 changes: 2 additions & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ members = [
"hello",
"openai",
"realworld",
"basic_auth",
"quick_start",
"static_files",
"json_response",
Expand All @@ -20,4 +21,4 @@ tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.7.3", features = ["runtime-tokio-native-tls", "postgres", "macros", "chrono", "uuid"] }
tracing = "0.1"
tracing-subscriber = "0.3"
chrono = "0.4"
chrono = "0.4"
8 changes: 8 additions & 0 deletions examples/basic_auth/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "basic_auth"
version = "0.1.0"
edition = "2021"

[dependencies]
ohkami = { workspace = true }
tokio = { workspace = true }
16 changes: 16 additions & 0 deletions examples/basic_auth/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use ohkami::prelude::*;
use ohkami::builtin::fang::BasicAuth;

#[tokio::main]
async fn main() {
Ohkami::new((
"/hello".GET(|| async {"Hello, public!"}),
"/private".By(Ohkami::with(
BasicAuth {
username: "master of hello",
password: "world"
},
"/hello".GET(|| async {"Hello, private :)"})
))
)).howl("localhost:8888").await
}
7 changes: 5 additions & 2 deletions ohkami/src/builtin/fang.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
pub(crate) mod jwt;
pub use jwt::JWT;

pub(crate) mod cors;
pub use cors::CORS;

pub(crate) mod jwt;
pub use jwt::JWT;
pub(crate) mod basicauth;
pub use basicauth::BasicAuth;

#[cfg(any(feature="rt_tokio",feature="rt_async-std"))]
pub(crate) mod timeout;
Expand Down
115 changes: 115 additions & 0 deletions ohkami/src/builtin/fang/basicauth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
use crate::prelude::*;


/// # Builtin fang for Basic Auth
///
/// - `BasicAuth { username, password }` verifies each request to have the
/// `username` and `password`
/// - `[BasicAuth; N]` verifies each request to have one of the pairs of
/// `username` and `password`
///
/// <br>
///
/// Note : **NEVER** hardcode `username` and `password` in your code
/// if you are pushing your source code to GitHub or other public repository!!!
///
/// <br>
///
/// *example*
/// ```rust,no_run
/// use ohkami::prelude::*;
/// use ohkami::builtin::fang::BasicAuth;
///
/// #[tokio::main]
/// async fn main() {
/// Ohkami::new((
/// "/hello".GET(|| async {"Hello, public!"}),
/// "/private".By(Ohkami::with(
/// BasicAuth {
/// username: "master of hello",
/// password: "world"
/// },
/// "/hello".GET(|| async {"Hello, private :)"})
/// ))
/// )).howl("localhost:8888").await
/// }
/// ```
#[derive(Clone)]
pub struct BasicAuth<S>
where
S: AsRef<str> + Clone + Send + Sync + 'static
{
pub username: S,
pub password: S
}

impl<S> BasicAuth<S>
where
S: AsRef<str> + Clone + Send + Sync + 'static
{
#[inline]
fn matches(&self,
username: &str,
password: &str
) -> bool {
self.username.as_ref() == username &&
self.password.as_ref() == password
}
}

const _: () = {
fn unauthorized() -> Response {
Response::Unauthorized().with_headers(|h|h
.WWWAuthenticate("Basic realm=\"Secure Area\"")
)
}

#[inline]
fn basic_credential_of(req: &Request) -> Result<String, Response> {
let credential_base64 = req.headers
.Authorization().ok_or_else(unauthorized)?
.strip_prefix("Basic ").ok_or_else(unauthorized)?;

let credential = String::from_utf8(
ohkami_lib::base64::decode(credential_base64.as_bytes())
).map_err(|_| unauthorized())?;

Ok(credential)
}

impl<S> FangAction for BasicAuth<S>
where
S: AsRef<str> + Clone + Send + Sync + 'static
{
#[inline]
async fn fore<'a>(&'a self, req: &'a mut Request) -> Result<(), Response> {
let credential = basic_credential_of(req)?;
let (username, password) = credential.split_once(':')
.ok_or_else(unauthorized)?;

self.matches(username, password).then_some(())
.ok_or_else(unauthorized)?;

Ok(())
}
}

impl<S, const N: usize> FangAction for [BasicAuth<S>; N]
where
S: AsRef<str> + Clone + Send + Sync + 'static
{
#[inline]
async fn fore<'a>(&'a self, req: &'a mut Request) -> Result<(), Response> {
let credential = basic_credential_of(req)?;
let (username, password) = credential.split_once(':')
.ok_or_else(unauthorized)?;

self.iter()
.map(|candidate| candidate.matches(username, password))
.any(|matched| matched).then_some(())
.ok_or_else(unauthorized)?;

Ok(())
}
}
};
21 changes: 20 additions & 1 deletion ohkami/src/builtin/fang/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,25 @@ use crate::{Fang, FangProc, IntoResponse, Request, Response};
///
/// <br>
///
/// ## fang
///
/// For each request, get JWT token and verify based on given config and `Payload: Deserialize`.
///
/// ## helper
///
/// `.issue(/* Payload: Serialize */)` generates a JWT token on the config.
///
/// <br>
///
/// ## default config
///
/// - get token: from `Authorization: Bearer <here>`
/// - customizable by `.get_token_by( 〜 )`
/// - verifying algorithm: `HMAC-SHA256`
/// - `HMAC-SHA{256, 384, 512}` are available now
///
/// <br>
///
/// *example.rs*
/// ```no_run
/// use ohkami::prelude::*;
Expand All @@ -34,7 +53,7 @@ use crate::{Fang, FangProc, IntoResponse, Request, Response};
/// Ohkami::new((
/// "/auth".GET(auth),
/// "/private".By(Ohkami::with(/*
/// Automatically verify `Authorization` header
/// Automatically verify JWT token
/// of a request and early returns an error
/// response if it's invalid.
/// If `Authorization` is valid, momorize the JWT
Expand Down
5 changes: 3 additions & 2 deletions ohkami/src/response/headers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ macro_rules! Header {
}
}
};
} Header! {44;
} Header! {45;
AcceptRanges: b"Accept-Ranges",
AccessControlAllowCredentials: b"Access-Control-Allow-Credentials",
AccessControlAllowHeaders: b"Access-Control-Allow-Headers",
Expand Down Expand Up @@ -289,6 +289,7 @@ macro_rules! Header {
Upgrade: b"Upgrade",
Vary: b"Vary",
Via: b"Via",
WWWAuthenticate: b"WWW-Authenticate",
XContentTypeOptions: b"X-Content-Type-Options",
XFrameOptions: b"X-Frame-Options",
}
Expand Down Expand Up @@ -423,7 +424,7 @@ impl Headers {
#[inline]
pub(crate) fn new() -> Self {
Self {
standard: Box::new([const {None}; N_SERVER_HEADERS]),
standard: Box::new([const {None}; N_SERVER_HEADERS]),
insertlog: Vec::with_capacity(8),
custom: None,
setcookie: None,
Expand Down
Loading