use super::{
common::send_authd_request,
constants::{SAFE_AUTHD_ENDPOINT_HOST, SAFE_AUTHD_ENDPOINT_PORT},
helpers::decode_ipc_msg,
Safe, SafeApp,
};
use crate::{Error, Result};
use log::{debug, info};
use safe_core::ipc::{encode_msg, gen_req_id, AppExchangeInfo, AuthReq, IpcMsg, IpcReq};
use safe_nd::AppPermissions;
use serde_json::json;
use std::collections::HashMap;
const SAFE_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<String> {
info!("Sending authorisation request to SAFE Authenticator...");
let request = IpcReq::Auth(AuthReq {
app: AppExchangeInfo {
id: app_id.to_string(),
scope: None,
name: app_name.to_string(),
vendor: app_vendor.to_string(),
},
app_container: false,
app_permissions: AppPermissions {
get_balance: true,
perform_mutations: true,
transfer_coins: true,
},
containers: HashMap::new(),
});
let req_id: u32 = gen_req_id();
let auth_req_str = encode_msg(&IpcMsg::Req { req_id, request }).map_err(|err| {
Error::AuthError(format!(
"Failed encoding the authorisation request: {:?}",
err
))
})?;
debug!(
"Authorisation request generated successfully: {}",
auth_req_str
);
let auth_res = send_app_auth_req(&auth_req_str, endpoint).await?;
match decode_ipc_msg(&auth_res) {
Ok(_) => {
info!("Application was authorised");
Ok(auth_res)
}
Err(e) => {
info!("Application was not authorised");
Err(Error::AuthError(format!(
"Application was not authorised: {:?}",
e
)))
}
}
}
pub async fn connect(&mut self, app_id: &str, auth_credentials: Option<&str>) -> Result<()> {
self.safe_app.connect(app_id, auth_credentials).await
}
}
async fn send_app_auth_req(auth_req_str: &str, endpoint: Option<&str>) -> Result<String> {
let authd_service_url = match endpoint {
None => format!("{}:{}", SAFE_AUTHD_ENDPOINT_HOST, SAFE_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,
SAFE_AUTHD_METHOD_AUTHORISE,
json!(auth_req_str),
)
.await?;
info!("SAFE authorisation response received!");
Ok(authd_response)
}