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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
use crate::client::AuthorizedClient;
use crate::errors::{Error, ErrorKind, Result};
use crate::ClientCredentials;

use failure::Fail;
use reqwest::{Response, StatusCode, Url};
use serde::Deserialize;

// Export reqwest's IntoUrl, because our public API (CodeProvider) requires users to implement this.
pub use reqwest::IntoUrl;

#[derive(Debug, Clone, Deserialize)]
pub struct Token {
    pub(crate) token_type: Option<String>,
    pub(crate) access_token: String,
    pub(crate) expires_in: Option<u32>,
    pub(crate) refresh_token: String,
}

impl Token {
    pub fn new(access_token: String, refresh_token: String) -> Token {
        Token {
            token_type: None,
            access_token,
            expires_in: None,
            refresh_token,
        }
    }

    pub fn token_type(&self) -> Option<&str> {
        self.token_type.as_ref().map(String::as_ref)
    }

    pub fn access_token(&self) -> &str {
        &self.access_token
    }

    pub fn expires_in(&self) -> Option<u32> {
        self.expires_in
    }

    pub fn refresh_token(&self) -> &str {
        self.refresh_token.as_ref()
    }
}

pub trait CodeProvider {
    fn get_code<T: IntoUrl>(&self, auth_url: T) -> Result<Code>;
}

#[derive(Debug, Deserialize)]
pub struct Code {
    code: String,
}

impl Code {
    pub fn new(code: String) -> Code {
        Code { code }
    }
}

pub fn authorization_code_flow<T: CodeProvider>(
    client_credentials: &ClientCredentials,
    base_url: &str,
    redirect_uri: &Url,
    code_provider: &T,
) -> Result<Token> {
    let code = get_code(client_credentials, &base_url, redirect_uri, code_provider)?;
    let token = exchange_code_for_token(&code, client_credentials, base_url, redirect_uri)?;

    Ok(token)
}

fn get_code<T: CodeProvider>(
    client_credentials: &ClientCredentials,
    base_url: &str,
    redirect_uri: &Url,
    code_provider: &T,
) -> Result<Code> {
    let auth_endpoint = format!("https://auth.{}/authorize", base_url);
    let params = [
        ("client_id", client_credentials.client_id),
        ("redirect_uri", redirect_uri.as_str()),
        ("response_type", "code"),
    ];
    let auth_url = Url::parse_with_params(&auth_endpoint, &params)
        .map_err(|e| e.context(ErrorKind::FailedToPrepareHttpRequest(redirect_uri.to_string())))?;

    code_provider.get_code(auth_url)
}

pub fn exchange_code_for_token(
    code: &Code,
    client_credentials: &ClientCredentials,
    base_url: &str,
    redirect_uri: &Url,
) -> Result<Token> {
    let token_endpoint = format!("https://auth.{}/token", base_url);
    let params = [
        ("grant_type", "authorization_code"),
        ("redirect_uri", redirect_uri.as_str()),
        ("code", code.code.as_str()),
    ];

    let http_client = reqwest::Client::new();

    let mut response: Response = http_client
        .post(&token_endpoint)
        .basic_auth(&client_credentials.client_id, Some(&client_credentials.client_secret))
        .form(&params)
        .send()
        .map_err(|e| e.context(ErrorKind::HttpRequestFailed))?;

    if response.status() != StatusCode::OK {
        let status_code = response.status();
        let body = response.text().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("reading body".to_string())))?;
        return Err(Error::from(ErrorKind::ApiCallFailed(status_code, body)));
    }

    let result = response.json().map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing json".to_string())))?;

    Ok(result)
}

pub fn refresh_access_token(authorized_client: &AuthorizedClient) -> Result<Token> {
    let url = format!("https://auth.{}/token", authorized_client.base_url);
    let params = [
        ("grant_type", "refresh_token"),
        ("refresh_token", &authorized_client.token.refresh_token),
    ];

    let token = authorized_client
        .http_client
        .post(&url)
        .basic_auth(
            &authorized_client.client_credentials.client_id,
            Some(&authorized_client.client_credentials.client_secret),
        )
        .form(&params)
        .send()
        .map_err(|e| e.context(ErrorKind::HttpRequestFailed))?
        .json()
        .map_err(|e| e.context(ErrorKind::FailedToProcessHttpResponse("parsing json".to_string())))?;

    Ok(token)
}