use oauth2::{CsrfToken, Scope};
use crate::error::{Error, OAuthError};
use crate::model::oauth2::AuthenticationData;
use crate::oauth2::OAuth2Endpoints;
impl<'a> OAuth2Endpoints<'a> {
pub fn login_url(&self, scopes: Vec<String>) -> Result<AuthenticationData, Error> {
let client = match &self.client.inner.oauth2_client {
Some(client) => client,
None => {
error!(
"Error building a login URL: {:#?}",
OAuthError::OAuth2NotConfigured
);
return Err(Error::OAuthError(OAuthError::OAuth2NotConfigured));
}
};
let scopes: Vec<Scope> = scopes.into_iter().map(Scope::new).collect();
let (eve_oauth_url, csrf_token) = client
.authorize_url(CsrfToken::new_random)
.add_scopes(scopes)
.url();
Ok(AuthenticationData {
login_url: eve_oauth_url.to_string(),
state: csrf_token.secret().to_string(),
})
}
}
#[cfg(test)]
mod tests {
use crate::error::{Error, OAuthError};
use crate::ScopeBuilder;
#[test]
fn test_successful_login_url() {
let esi_client = crate::Client::builder()
.user_agent("MyApp/1.0 (contact@example.com)")
.client_id("client_id")
.client_secret("client_secret")
.callback_url("http://localhost:8080/callback")
.build()
.expect("Failed to build Client");
let scopes = ScopeBuilder::new().public_data().build();
let result = esi_client.oauth2().login_url(scopes);
assert!(result.is_ok());
}
#[test]
fn test_oauth_client_not_configured() {
let esi_client = crate::Client::builder()
.user_agent("MyApp/1.0 (contact@example.com)")
.build()
.expect("Failed to build Client");
let scopes = ScopeBuilder::new().public_data().build();
let result = esi_client.oauth2().login_url(scopes);
assert!(result.is_err());
assert!(matches!(
result,
Err(Error::OAuthError(OAuthError::OAuth2NotConfigured))
));
}
}