ctrader_rs/client/
auth.rs1use super::endpoint::Endpoints;
2use crate::{
3 error::CTraderResult,
4 types::{Auth, TokenResponse},
5};
6
7impl Auth {
8 pub fn new(
9 app_client_id: String,
10 app_access_token: String,
11 app_client_secret: String,
12 app_redirect_url: String,
13 refresh_token: String,
14 ) -> Self {
15 Self {
16 ctrader_access_token: app_access_token,
17 ctrader_refresh_token: refresh_token,
18 ctrader_client_id: app_client_id,
19 ctrader_client_secret: app_client_secret,
20 ctrader_redirect_url: app_redirect_url,
21 }
22 }
23
24 pub fn get_auth_uri(self) -> CTraderResult<String> {
25 let auth_uri = format!(
26 "{}?client_id={}&redirect_uri={}&scope=trading",
27 Endpoints::AUTH_URI,
28 self.ctrader_client_id,
29 self.ctrader_redirect_url
30 );
31 Ok(auth_uri)
32 }
33
34 pub async fn get_token(self, auth_code: &str) -> CTraderResult<TokenResponse> {
35 let url = format!(
36 "{}?grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&client_secret={}",
37 Endpoints::TOKEN_URI,
38 auth_code,
39 self.ctrader_redirect_url,
40 self.ctrader_client_id,
41 self.ctrader_client_secret
42 );
43 let response = reqwest::Client::new()
44 .get(url)
45 .send()
46 .await
47 .expect("unable to get access token");
48
49 let res = response
50 .json::<TokenResponse>()
51 .await
52 .expect("error decoding json response!");
53
54 Ok(res)
55 }
56
57 pub async fn refresh_token(self, refresh_token: &str) -> CTraderResult<TokenResponse> {
58 let url = format!(
59 "{}?grant_type=refresh_token&refresh_token={}&client_id={}&client_secret={}",
60 Endpoints::TOKEN_URI,
61 refresh_token,
62 self.ctrader_client_id,
63 self.ctrader_client_secret
64 );
65 let response = reqwest::Client::new()
66 .get(url)
67 .send()
68 .await
69 .expect("unable to refresh access token");
70
71 let res = response
72 .json::<TokenResponse>()
73 .await
74 .expect("error decoding json response!");
75
76 Ok(res)
77 }
78}