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
use super::{
common::send_authd_request,
constants::{SN_AUTHD_ENDPOINT_HOST, SN_AUTHD_ENDPOINT_PORT},
Safe,
};
use crate::{
api::ipc::{BootstrapConfig, IpcMsg, IpcResp},
Error, Result,
};
use log::{debug, info};
use serde_json::json;
use sn_data_types::Keypair;
use std::path::Path;
const SN_AUTHD_METHOD_AUTHORISE: &str = "authorise";
impl Safe {
pub async fn auth_app(
app_id: &str,
app_name: &str,
app_vendor: &str,
endpoint: Option<&str>,
) -> Result<Keypair> {
info!("Sending authorisation request to SAFE Authenticator...");
let request = IpcMsg::new_auth_req(app_id, app_name, app_vendor);
let auth_req_str = request.to_string()?;
debug!(
"Authorisation request generated successfully: {}",
auth_req_str
);
let auth_res = send_app_auth_req(&auth_req_str, endpoint).await?;
match IpcMsg::from_string(&auth_res) {
Ok(IpcMsg::Resp(IpcResp::Auth(Ok(auth_granted)))) => {
info!("Application '{}' was authorised!", app_id);
Ok(auth_granted.app_keypair)
}
Ok(other) => {
info!("Unexpected messages received: {:?}", other);
Err(Error::AuthError(format!(
"Application was not authorised, unexpected response was received: {:?}",
other
)))
}
Err(e) => {
info!("Application '{}' was not authorised", app_id);
Err(Error::AuthError(format!(
"Application '{}' was not authorised: {:?}",
app_id, e
)))
}
}
}
pub async fn connect(
&mut self,
app_keypair: Option<Keypair>,
config_path: Option<&Path>,
bootstrap_config: Option<BootstrapConfig>,
) -> Result<()> {
self.safe_client
.connect(app_keypair, config_path, bootstrap_config)
.await
}
}
async fn send_app_auth_req(auth_req_str: &str, endpoint: Option<&str>) -> Result<String> {
let authd_service_url = match endpoint {
None => format!("{}:{}", SN_AUTHD_ENDPOINT_HOST, SN_AUTHD_ENDPOINT_PORT,),
Some(endpoint) => endpoint.to_string(),
};
info!("Sending authorisation request to SAFE Authenticator...");
let authd_response = send_authd_request::<String>(
&authd_service_url,
SN_AUTHD_METHOD_AUTHORISE,
json!(auth_req_str),
)
.await?;
info!("SAFE authorisation response received!");
Ok(authd_response)
}