use crate::{
config::*,
job::{Job, JobResult, JobStatus, Session, SessionBody, SessionResponseBody, ValueResponseBody},
MessageError,
};
use reqwest::blocking::Client;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
#[derive(Debug, PartialEq)]
pub struct Credential {
pub key: String,
}
impl Credential {
pub fn request_value(&self, job: &Job) -> Result<String, MessageError> {
let backend_endpoint = get_backend_hostname();
let backend_username = get_backend_username();
let backend_password = get_backend_password();
let session_url = format!("{}/sessions", backend_endpoint);
let credential_url = format!("{}/credentials/{}", backend_endpoint, self.key);
let client = Client::builder().build().map_err(|e| {
let job_result = JobResult::from(job)
.with_status(JobStatus::Error)
.with_error(e);
MessageError::ProcessingError(job_result)
})?;
let session_body = SessionBody {
session: Session {
email: backend_username,
password: backend_password,
},
};
let response: SessionResponseBody = client
.post(&session_url)
.json(&session_body)
.send()
.map_err(|e| {
let job_result = JobResult::from(job)
.with_status(JobStatus::Error)
.with_error(e);
MessageError::ProcessingError(job_result)
})?
.json()
.map_err(|e| {
let job_result = JobResult::from(job)
.with_status(JobStatus::Error)
.with_error(e);
MessageError::ProcessingError(job_result)
})?;
let mut headers = HeaderMap::new();
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&response.access_token).map_err(|_e| {
let job_result = JobResult::from(job).with_status(JobStatus::Error);
MessageError::ProcessingError(job_result)
})?,
);
let client = Client::builder()
.default_headers(headers)
.build()
.map_err(|e| {
let job_result = JobResult::from(job)
.with_status(JobStatus::Error)
.with_error(e);
MessageError::ProcessingError(job_result)
})?;
let response: ValueResponseBody = client
.get(&credential_url)
.send()
.map_err(|e| {
let job_result = JobResult::from(job)
.with_status(JobStatus::Error)
.with_error(e);
MessageError::ProcessingError(job_result)
})?
.json()
.map_err(|e| {
let job_result = JobResult::from(job)
.with_status(JobStatus::Error)
.with_error(e);
MessageError::ProcessingError(job_result)
})?;
Ok(response.data.value)
}
}