use std::env;
use std::fmt::Debug;
use std::marker::PhantomData;
pub trait Credentials {
fn ak(&self) -> &str;
fn sk(&self) -> &str;
fn security_token(&self) -> &str;
fn new(ak: impl Into<String>, sk: impl Into<String>, security_token: impl Into<String>) -> Self;
}
pub trait CredentialsProvider<C> where C: Credentials {
fn credentials(&self) -> &C;
fn new(c: C) -> Self;
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CommonCredentialsProvider<C> {
pub(crate) credentials: C,
}
impl<C> CredentialsProvider<C> for CommonCredentialsProvider<C> where C: Credentials {
fn credentials(&self) -> &C {
&self.credentials
}
fn new(c: C) -> Self {
CommonCredentialsProvider {
credentials: c,
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct CommonCredentials {
pub(crate) ak: String,
pub(crate) sk: String,
pub(crate) security_token: String,
}
impl Credentials for CommonCredentials {
fn ak(&self) -> &str {
&self.ak
}
fn sk(&self) -> &str {
&self.sk
}
fn security_token(&self) -> &str {
&self.security_token
}
fn new(ak: impl Into<String>, sk: impl Into<String>, security_token: impl Into<String>) -> Self {
CommonCredentials {
ak: ak.into(),
sk: sk.into(),
security_token: security_token.into(),
}
}
}
pub(crate) struct StaticCredentialsProvider<P, C> {
pub(crate) p: PhantomData<P>,
pub(crate) c: PhantomData<C>,
}
impl<P, C> StaticCredentialsProvider<P, C> where P: CredentialsProvider<C> + Debug + Default,
C: Credentials + Debug + Default {
pub(crate) fn new(ak: impl Into<String>, sk: impl Into<String>, security_token: impl Into<String>) -> P {
let mut ak = ak.into().trim().to_owned();
let mut sk = sk.into().trim().to_owned();
let mut security_token = security_token.into().trim().to_owned();
if ak == "" {
sk = "".to_owned();
security_token = "".to_owned();
} else if sk == "" {
ak = "".to_owned();
security_token = "".to_owned();
}
P::new(C::new(ak, sk, security_token))
}
}
pub(crate) struct EnvCredentialsProvider<P, C> {
pub(crate) p: PhantomData<P>,
pub(crate) c: PhantomData<C>,
}
impl<P, C> EnvCredentialsProvider<P, C> where P: CredentialsProvider<C> + Debug + Default,
C: Credentials + Debug + Default {
pub(crate) fn new() -> P {
let mut c = C::default();
if let Ok(ak) = env::var("TOS_ACCESS_KEY") {
if let Ok(sk) = env::var("TOS_SECRET_KEY") {
if let Ok(security_token) = env::var("TOS_SECURITY_TOKEN") {
c = C::new(ak, sk, security_token)
} else {
c = C::new(ak, sk, "".to_owned())
}
}
}
P::new(c)
}
}