use std::collections::HashMap;
use std::fmt;
use std::net::SocketAddr;
use std::sync::Arc;
use futures_util::future::BoxFuture;
use serde::{Deserialize, Serialize};
use tokio::sync::OnceCell;
use crate::authorization::Authorization;
use crate::errors::Result;
use crate::oauth::OidcConfig;
use crate::types::{Profile, TokenSet};
use crate::user::OAuthUser;
pub type UrlValues = HashMap<String, Vec<String>>;
pub type ProfileFn = Arc<dyn Fn(&Profile, &TokenSet) -> Result<OAuthUser> + Send + Sync>;
pub type CredentialsAuthorizeFn = Arc<
dyn Fn(
HashMap<String, String>,
CredentialsRequest,
) -> BoxFuture<'static, Result<Option<OAuthUser>>>
+ Send
+ Sync,
>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderType {
OAuth,
Oidc,
Email,
Credentials,
Passkey,
}
impl ProviderType {
pub fn as_str(&self) -> &'static str {
match self {
ProviderType::OAuth => "oauth",
ProviderType::Oidc => "oidc",
ProviderType::Email => "email",
ProviderType::Credentials => "credentials",
ProviderType::Passkey => "passkey",
}
}
}
impl fmt::Display for ProviderType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Check {
Pkce,
State,
Nonce,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PublicProvider {
pub id: String,
pub name: String,
#[serde(rename = "type")]
pub type_: String,
#[serde(rename = "signinUrl")]
pub sign_in_url: String,
#[serde(rename = "callbackUrl")]
pub callback_url: String,
}
pub trait Provider: Send + Sync + 'static {
fn id(&self) -> &str;
fn name(&self) -> &str;
fn type_(&self) -> ProviderType;
fn as_oauth(&self) -> Option<&OAuthProvider> {
None
}
fn as_credentials(&self) -> Option<&CredentialsProvider> {
None
}
}
#[derive(Default)]
pub struct OAuthProvider {
pub provider_id: String,
pub display_name: String,
pub kind: Option<ProviderType>,
pub client_id: String,
pub client_secret: String,
pub issuer: String,
pub authorization_url: String,
pub authorization_params: UrlValues,
pub token_url: String,
pub user_info_url: String,
pub scopes: Vec<String>,
pub checks: Vec<Check>,
pub profile: Option<ProfileFn>,
pub authorization_style: String,
pub discovered: OnceCell<OidcConfig>,
}
impl fmt::Debug for OAuthProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OAuthProvider")
.field("provider_id", &self.provider_id)
.field("display_name", &self.display_name)
.field("kind", &self.kind)
.field("issuer", &self.issuer)
.field("authorization_url", &self.authorization_url)
.field("token_url", &self.token_url)
.field("user_info_url", &self.user_info_url)
.field("scopes", &self.scopes)
.field("checks", &self.checks)
.field("authorization_style", &self.authorization_style)
.finish()
}
}
impl OAuthProvider {
pub fn authorization_endpoint(&self) -> String {
self.endpoint(&self.authorization_url, |cfg| &cfg.authorization_endpoint)
}
pub fn token_endpoint(&self) -> String {
self.endpoint(&self.token_url, |cfg| &cfg.token_endpoint)
}
pub fn user_info_endpoint(&self) -> String {
self.endpoint(&self.user_info_url, |cfg| &cfg.userinfo_endpoint)
}
fn endpoint(&self, configured: &str, pick: impl Fn(&OidcConfig) -> &String) -> String {
if !configured.is_empty() {
return configured.to_string();
}
self.discovered
.get()
.map(|cfg| pick(cfg).clone())
.unwrap_or_default()
}
}
impl Provider for OAuthProvider {
fn id(&self) -> &str {
&self.provider_id
}
fn name(&self) -> &str {
&self.display_name
}
fn type_(&self) -> ProviderType {
self.kind.unwrap_or(ProviderType::OAuth)
}
fn as_oauth(&self) -> Option<&OAuthProvider> {
Some(self)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CredentialField {
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub label: String,
#[serde(rename = "type", default, skip_serializing_if = "String::is_empty")]
pub type_: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub placeholder: String,
}
#[derive(Debug, Clone)]
pub struct CredentialsRequest {
pub method: http::Method,
pub uri: http::Uri,
pub headers: http::HeaderMap,
pub remote_addr: Option<SocketAddr>,
}
#[derive(Default)]
pub struct CredentialsProvider {
pub provider_id: String,
pub display_name: String,
pub fields: Vec<CredentialField>,
pub authorize: Option<CredentialsAuthorizeFn>,
}
impl fmt::Debug for CredentialsProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CredentialsProvider")
.field("provider_id", &self.provider_id)
.field("display_name", &self.display_name)
.field("fields", &self.fields)
.field("authorize", &self.authorize.is_some())
.finish()
}
}
impl Provider for CredentialsProvider {
fn id(&self) -> &str {
&self.provider_id
}
fn name(&self) -> &str {
&self.display_name
}
fn type_(&self) -> ProviderType {
ProviderType::Credentials
}
fn as_credentials(&self) -> Option<&CredentialsProvider> {
Some(self)
}
}
impl Authorization {
pub fn find_provider(&self, id: &str) -> Option<&Arc<dyn Provider>> {
self.providers().iter().find(|p| p.id() == id)
}
}