Skip to main content

devops_armory/cloud/gcp/auth/
auth.rs

1use gcp_auth::{CustomServiceAccount, TokenProvider};
2
3/// Below function uses Service Account credentials to generate token
4pub async fn gcp_get_credentials_token_sa(project: Option<String>, credentials: Option<String>) -> Result<String, std::io::Error> {
5
6    let token: String = match project {
7
8        Some(p) if !p.is_empty() => {
9            let cred = credentials.unwrap_or_default();
10            let service_account = CustomServiceAccount::from_file(cred);
11            let scopes = &["https://www.googleapis.com/auth/cloud-platform"];
12            let token = service_account.expect("No token available").token(scopes).await.expect("Missing scopes for existing token");
13            let tok = token.as_str();
14
15            tok.to_owned()
16        },
17        Some(_) => {
18            let unknown_str = "Unknown project selected".to_string();
19            unknown_str
20        },
21        None => {
22            let error_msg = "No project provided".to_string();
23            error_msg
24        }
25    };
26
27    Ok(token)
28
29}
30
31
32/// Below function uses current system log in credentials obtained via gcloud auth login command
33pub async fn gcp_get_credentials_token_iam() -> Result<String, std::io::Error> {
34
35    let provider = gcp_auth::provider().await.unwrap();
36    let scopes = &["https://www.googleapis.com/auth/cloud-platform"];
37    let token = provider.token(scopes).await.unwrap();
38
39    let t = token.as_str();
40
41    Ok(t.to_string())
42
43}
44
45/// Below function uses type of authentication to GCP account you want to use - you can choose either
46pub async fn gcp_get_authentication_method(auth_method: String) -> Result<(), std::io::Error> {
47
48    match auth_method.trim() {
49
50        "Service Account" => {
51            gcp_get_credentials_token_sa(None, None).await.unwrap_or_default();
52        },
53        "IAM" => {
54            gcp_get_credentials_token_iam().await.unwrap_or_default();
55        },
56        _ => {
57            eprintln!("Unkown authentication method to GCP")
58        }
59        
60    }
61
62    Ok(())
63
64}
65