affinidi_did_resolver_cache_server/
session.rs1use crate::{SharedData, common::create_session_id, errors::ErrorResponse};
2use axum::{
3 Json,
4 extract::{FromRef, FromRequestParts},
5 http::{StatusCode, request::Parts},
6 response::{IntoResponse, Response},
7};
8use serde::Serialize;
9use serde_json::json;
10use std::{
11 fmt::{Debug, Display},
12 net::SocketAddr,
13};
14use tracing::{info, warn};
15
16#[derive(Debug)]
17#[non_exhaustive]
18pub enum SessionError {
19 SessionError(String),
20}
21
22impl Display for SessionError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 match self {
25 SessionError::SessionError(message) => {
26 write!(f, "Error: {message}")
27 }
28 }
29 }
30}
31
32impl IntoResponse for SessionError {
33 fn into_response(self) -> Response {
34 let status = match self {
35 SessionError::SessionError(_) => StatusCode::BAD_REQUEST,
36 };
37 let body = Json(json!(ErrorResponse {
38 sessionId: "UNAUTHORIZED".into(),
39 httpCode: status.as_u16(),
40 errorCode: status.as_u16(),
41 errorCodeStr: status.to_string(),
42 message: self.to_string(),
43 }));
44 (status, body).into_response()
45 }
46}
47
48#[derive(Clone, Debug, Serialize)]
49pub struct Session {
50 pub session_id: String, }
52
53impl<S> FromRequestParts<S> for Session
54where
55 SharedData: FromRef<S>,
56 S: Send + Sync + Debug,
57{
58 type Rejection = SessionError;
59 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
60 if let Some(address) = parts
61 .extensions
62 .get::<axum::extract::ConnectInfo<SocketAddr>>()
63 .map(|ci| ci.0)
64 {
65 address.to_string()
66 } else {
67 warn!("No remote address in request!");
68 return Err(SessionError::SessionError(
69 "No remote address in request!".into(),
70 ));
71 };
72
73 let session_id = create_session_id();
74
75 info!("{}: Connection accepted", &session_id);
76
77 let session = Session { session_id };
78
79 Ok(session)
80 }
81}