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
/// Credentials sent with each request.
enum Auth {
/// Value of the HTTP Basic credentials.
Basic(String),
/// OAuth 2.0 access token.
Bearer(String),
}
pub struct WakapiClient {
api_url: String,
auth: Auth,
}
impl WakapiClient {
/// Create a client authenticating with HTTP Basic Auth.
///
/// Wakatime API keys are write-only, so this can't be used with wakatime.com's read endpoints
/// (use [`WakapiClient::with_token`] instead). It remains useful for Wakatime-compatible
/// servers that still accept API keys on these endpoints.
pub fn new(api_url: &str, api_key: &str) -> Self {
Self {
api_url: api_url.to_string(),
auth: Auth::Basic(api_key.to_string()),
}
}
/// Create a client authenticating with an OAuth 2.0 access token.
///
/// For your own account, get a token from <https://wakatime.com/oauth>.
pub fn with_token(api_url: &str, token: &str) -> Self {
Self {
api_url: api_url.to_string(),
auth: Auth::Bearer(token.to_string()),
}
}
/// Build the full URL for the given endpoint, replacing /:user/ with "/current/" (for now).
pub fn build_url(&self, endpoint: &str, url_params: Option<String>) -> String {
let mut url = self.api_url.clone() + endpoint;
url = url.replace("/:user/", "/current/");
if let Some(params) = url_params {
url = url + "?" + ¶ms;
}
url
}
/// Get Authorization header value for the client.
pub fn get_auth_header(&self) -> String {
match &self.auth {
Auth::Basic(api_key) => format!("Basic {}", api_key),
Auth::Bearer(token) => format!("Bearer {}", token),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_uses_basic_auth() {
let client = WakapiClient::new("https://wakatime.com", "MTIzNDU=");
assert_eq!(client.get_auth_header(), "Basic MTIzNDU=");
}
#[test]
fn with_token_uses_bearer_auth() {
let client = WakapiClient::with_token("https://wakatime.com", "waka_tok_12345");
assert_eq!(client.get_auth_header(), "Bearer waka_tok_12345");
}
}