dog-auth 0.4.0

Authentication system for DogRS framework
Documentation
// Authentication service.

use std::sync::Arc;

use anyhow::Result;
use dog_core::errors::DogError;
use dog_core::DogApp;
use dog_core::HookContext;
use serde_json::{json, Value};

use crate::core::{
    AuthenticationBase, AuthenticationParams, AuthenticationRequest, AuthenticationResult,
    ConnectionEvent, JwtOverrides,
};
use crate::hooks::authenticate::AuthenticateHookParams;
use crate::options::AuthOptions;

pub const AUTHENTICATION_KEY: &str = "authentication";
pub const AUTHENTICATION_OPTIONS_KEY: &str = "authentication.options";

pub struct AuthenticationService<P>
where
    P: Send + Clone + 'static,
{
    pub base: Arc<AuthenticationBase<P>>,
}

impl<P> AuthenticationService<P>
where
    P: Send + Clone + 'static,
{
    pub fn builder(
        builder: &mut dog_core::DogAppBuilder<Value, P>,
        options: Option<AuthOptions>,
    ) -> Result<crate::core::AuthenticationBuilder<P>> {
        crate::core::AuthenticationBuilder::new(builder, AUTHENTICATION_OPTIONS_KEY, options)
    }

    pub fn new(base: Arc<AuthenticationBase<P>>) -> Self {
        Self { base }
    }

    pub fn install(
        builder: &mut dog_core::DogAppBuilder<Value, P>,
        auth: Arc<AuthenticationService<P>>,
    ) -> Arc<crate::service_adapter::AuthServiceAdapter<P>>
    where
        P: AuthenticateHookParams,
    {
        builder.set(AUTHENTICATION_KEY, auth.clone());
        let svc = Arc::new(crate::service_adapter::AuthServiceAdapter::new(
            auth.clone(),
        ));
        builder.register_service(
            AUTHENTICATION_KEY,
            Arc::clone(&svc) as Arc<dyn dog_core::DogService<Value, P>>,
        );
        svc
    }

    pub fn from_app(app: &DogApp<Value, P>) -> Option<Arc<Self>> {
        app.get(AUTHENTICATION_KEY)
    }

    pub fn configuration(&self) -> AuthOptions {
        self.base.configuration()
    }

    pub async fn authenticate(
        &self,
        authentication: &AuthenticationRequest,
        params: &AuthenticationParams,
        ctx: &mut HookContext<Value, P>,
        strategies: &[String],
    ) -> Result<AuthenticationResult> {
        self.base
            .authenticate(authentication, params, ctx, strategies)
            .await
    }

    pub async fn setup_validate(&self) -> Result<()> {
        let cfg = self.configuration();
        cfg.validate().map_err(|e| anyhow::anyhow!(e))?;

        Ok(())
    }

    pub async fn get_payload(
        &self,
        auth_result: &AuthenticationResult,
        params: &AuthenticationParams,
    ) -> Result<Value> {
        let mut payload = params.payload.clone().unwrap_or_else(|| json!({}));

        let cfg = self.configuration();
        let entity_key = cfg.entity.clone();
        let entity_id_claim = cfg
            .entity_id_claim
            .clone()
            .unwrap_or_else(|| "sub".to_string());

        // Feathers-like default: if entity attachment is configured, include the entity id in the JWT
        // payload so the JwtStrategy can resolve and attach the entity on authenticated requests.
        //
        // We only set the claim if it isn't already provided by the caller.
        let claim_exists = payload
            .get(&entity_id_claim)
            .and_then(|v| v.as_str())
            .map(|s| !s.trim().is_empty())
            .unwrap_or(false);

        if !claim_exists {
            if let Some(entity_key) = entity_key {
                if let Some(entity_id) = auth_result
                    .get(&entity_key)
                    .and_then(|e| e.get("id"))
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
                    .filter(|s| !s.trim().is_empty())
                {
                    if let Some(map) = payload.as_object_mut() {
                        map.insert(entity_id_claim, Value::String(entity_id));
                    }
                }
            }
        }

        Ok(payload)
    }

    pub async fn create(
        &self,
        authentication: &AuthenticationRequest,
        params: &AuthenticationParams,
        ctx: &mut HookContext<Value, P>,
        strategies: &[String],
        jwt_overrides: Option<JwtOverrides>,
    ) -> Result<AuthenticationResult> {
        if strategies.is_empty() {
            return Err(DogError::not_authenticated(
                "No authentication strategies allowed for creating a JWT (`authStrategies`)",
            )
            .into_anyhow());
        }

        let auth_result = self
            .authenticate(authentication, params, ctx, strategies)
            .await?;

        if auth_result
            .get("accessToken")
            .and_then(|v| v.as_str())
            .is_some()
        {
            return Ok(auth_result);
        }

        // Minimal Feathers-like behavior: sign the `params.payload` (or empty) as the JWT payload.
        let payload = self.get_payload(&auth_result, params).await?;
        let access_token = self
            .base
            .create_access_token(payload, jwt_overrides)
            .await?;

        let mut out = match auth_result {
            Value::Object(m) => m,
            other => {
                let mut m = serde_json::Map::new();
                m.insert("result".to_string(), other);
                m
            }
        };
        out.insert("accessToken".to_string(), Value::String(access_token));

        Ok(Value::Object(out))
    }

    pub async fn remove(
        &self,
        access_token: Option<&str>,
        params: &AuthenticationParams,
        ctx: &mut HookContext<Value, P>,
        strategies: &[String],
    ) -> Result<AuthenticationResult> {
        let token = access_token
            .map(|s| s.to_string())
            .or_else(|| crate::core::extract_bearer_token(&params.headers))
            .ok_or_else(|| DogError::not_authenticated("Invalid access token").into_anyhow())?;

        // Authenticate, then revoke the access token before reporting logout.
        let mut data = serde_json::Map::new();
        data.insert("accessToken".to_string(), Value::String(token.clone()));
        let auth_req = AuthenticationRequest {
            strategy: Some("jwt".to_string()),
            data,
        };

        let result = self
            .authenticate(&auth_req, params, ctx, strategies)
            .await?;
        self.base.revoke_access_token(&token).await?;
        Ok(result)
    }

    pub async fn handle_connection(
        &self,
        _event: ConnectionEvent,
        _connection: Arc<dyn std::any::Any + Send + Sync>,
        _auth_result: &AuthenticationResult,
    ) -> Result<()> {
        Ok(())
    }
}