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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use super::response;
use crate::fairings::auth::SessionInfo;
use crate::utils;
use data::session::SessionResponse;
use log::info;
use minerva_data as data;
use minerva_rpc as rpc;
use response::{ErrorResponse, RestResult};
use rocket::serde::json::Json;
use rocket::Route;
use rocket_okapi::{okapi::openapi3::OpenApi, openapi, openapi_get_routes_spec};
use std::env;
use tonic::Request;
pub fn routes() -> (Vec<Route>, OpenApi) {
openapi_get_routes_spec![login, logout]
}
pub fn get_endpoint() -> String {
let port = env::var("SESSION_SERVICE_PORT").expect("Unable to read SESSION_SERVICE_PORT");
let srv = env::var("SESSION_SERVICE_SERVER").expect("Unable to read SESSION_SERVICE_SERVER");
format!("http://{}:{}", srv, port)
}
#[openapi(tag = "Authentication")]
#[post("/<tenant>/login", data = "<body>")]
async fn login(
tenant: &str,
body: Json<data::session::RecvSession>,
) -> RestResult<SessionResponse> {
let endpoint = get_endpoint();
let requestor = "unknown".to_string();
let body = body.as_new(tenant);
let tenant = tenant.to_string();
info!(
"{}",
data::log::format(
utils::get_ip(),
&requestor,
&tenant,
&format!("POST /login: request SESSION.generate ({})", endpoint),
)
);
let mut client = rpc::session::make_client(endpoint, tenant.clone(), requestor)
.await
.map_err(|status| {
error!("Error while connecting to SESSION: {:?}", status);
ErrorResponse::from(status)
})?;
client
.generate(Request::new(body.clone().into()))
.await
.map(|msg| {
let token = msg.into_inner().token;
Json(SessionResponse { token, tenant })
})
.map_err(|status| {
error!("Error while creating session: {:?}", status);
ErrorResponse::from(status)
})
}
#[allow(unused_variables)]
#[openapi(tag = "Authentication")]
#[post("/<tenant>/logout")]
async fn logout(tenant: String, session: SessionInfo) -> RestResult<crate::generic::Message> {
let endpoint = get_endpoint();
let requestor = "unknown".to_string();
let tenant = session.info.tenant;
info!(
"{}",
data::log::format(
utils::get_ip(),
&requestor,
&tenant,
&format!("POST /logout: request SESSION.remove ({})", endpoint),
)
);
let mut client = rpc::session::make_client(endpoint, tenant.clone(), requestor)
.await
.map_err(ErrorResponse::from)?;
let token = session.token.clone();
client
.remove(Request::new(rpc::messages::SessionToken { token }))
.await
.map(|_| Json(crate::generic::Message::from("User logout successful")))
.map_err(ErrorResponse::from)
}