summaryrefslogtreecommitdiffstats
path: root/crates/auth/src/server/grpc/auth.rs
blob: fb00291d1ac6c4f6e221194acb1639c99d180673 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
use std::str::FromStr;

use jsonwebtoken::DecodingKey;
use sellershut_core::auth::{ValidationRequest, ValidationResponse, auth_server::Auth};
use tonic::{Request, Response, Status, async_trait};
use tower_sessions::{SessionStore, session::Id};
use tracing::warn;

use crate::{auth::Claims, state::AppHandle};

#[async_trait]
impl Auth for AppHandle {
    async fn validate_auth_token(
        &self,
        request: Request<ValidationRequest>,
    ) -> Result<Response<ValidationResponse>, Status> {
        let token = request.into_inner().token;

        let token = jsonwebtoken::decode::<Claims>(
            &token,
            &DecodingKey::from_secret(self.local_config.oauth.jwt_encoding_key.as_bytes()),
            &jsonwebtoken::Validation::default(),
        );

        match token {
            Ok(value) => {
                let session_id = value.claims.sid;
                let store = &self.session_store;
                match Id::from_str(&session_id) {
                    Ok(ref id) => {
                        if let Ok(Some(_)) = store.load(id).await {
                            return Ok(Response::new(ValidationResponse { valid: true }));
                        } else {
                            return Ok(Response::new(Default::default()));
                        }
                    }
                    Err(e) => {
                        warn!("{e}");

                        return Ok(Response::new(Default::default()));
                    }
                }
            }
            Err(e) => {
                warn!("{e}");
                Ok(Response::new(ValidationResponse::default()))
            }
        }
    }
}