|
| 1 | +use axum::{Json, extract::State, http::HeaderMap}; |
| 2 | +use serde::Serialize; |
| 3 | +use utoipa::ToSchema; |
| 4 | + |
| 5 | +use crate::error::{IntegrationError, Result}; |
| 6 | +use crate::state::AppState; |
| 7 | + |
| 8 | +#[derive(Debug, Serialize, ToSchema)] |
| 9 | +pub struct ConnectSessionResponse { |
| 10 | + pub token: String, |
| 11 | + pub expires_at: String, |
| 12 | +} |
| 13 | + |
| 14 | +#[utoipa::path( |
| 15 | + post, |
| 16 | + path = "/connect-session", |
| 17 | + responses( |
| 18 | + (status = 200, description = "Connect session created", body = ConnectSessionResponse), |
| 19 | + (status = 401, description = "Unauthorized"), |
| 20 | + (status = 500, description = "Internal server error"), |
| 21 | + ), |
| 22 | + tag = "integration", |
| 23 | + security( |
| 24 | + ("bearer_auth" = []) |
| 25 | + ) |
| 26 | +)] |
| 27 | +pub async fn create_connect_session( |
| 28 | + State(state): State<AppState>, |
| 29 | + headers: HeaderMap, |
| 30 | +) -> Result<Json<ConnectSessionResponse>> { |
| 31 | + let auth_token = extract_token(&headers)?; |
| 32 | + |
| 33 | + let auth = state |
| 34 | + .config |
| 35 | + .auth |
| 36 | + .as_ref() |
| 37 | + .ok_or_else(|| IntegrationError::Auth("Auth not configured".to_string()))?; |
| 38 | + |
| 39 | + let claims = auth |
| 40 | + .verify_token(auth_token) |
| 41 | + .await |
| 42 | + .map_err(|e| IntegrationError::Auth(e.to_string()))?; |
| 43 | + let user_id = claims.sub; |
| 44 | + |
| 45 | + let req = hypr_nango::NangoConnectSessionRequest { |
| 46 | + end_user: hypr_nango::NangoConnectSessionRequestUser { |
| 47 | + id: user_id, |
| 48 | + display_name: None, |
| 49 | + email: None, |
| 50 | + }, |
| 51 | + organization: None, |
| 52 | + allowed_integrations: vec![], |
| 53 | + integrations_config_defaults: None, |
| 54 | + }; |
| 55 | + |
| 56 | + let res = state.nango.create_connect_session(req).await?; |
| 57 | + |
| 58 | + match res { |
| 59 | + hypr_nango::NangoConnectSessionResponse::Ok { token, expires_at } => { |
| 60 | + Ok(Json(ConnectSessionResponse { token, expires_at })) |
| 61 | + } |
| 62 | + hypr_nango::NangoConnectSessionResponse::Error { code } => { |
| 63 | + Err(IntegrationError::Nango(code)) |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +fn extract_token(headers: &HeaderMap) -> Result<&str> { |
| 69 | + let auth_header = headers |
| 70 | + .get("Authorization") |
| 71 | + .and_then(|h| h.to_str().ok()) |
| 72 | + .ok_or_else(|| IntegrationError::Auth("Missing Authorization header".to_string()))?; |
| 73 | + |
| 74 | + hypr_supabase_auth::SupabaseAuth::extract_token(auth_header) |
| 75 | + .ok_or_else(|| IntegrationError::Auth("Invalid Authorization header".to_string())) |
| 76 | +} |
0 commit comments