http_auth_basic/
credentials.rs1use std::str::FromStr;
2
3use base64::{prelude::BASE64_STANDARD, Engine};
4
5use crate::error::AuthBasicError;
6
7#[derive(Debug, PartialEq)]
10pub struct Credentials {
11 pub user_id: String,
12 pub password: String,
13}
14
15impl Credentials {
16 pub fn new(user_id: &str, password: &str) -> Self {
30 Self {
31 user_id: user_id.to_string(),
32 password: password.to_string(),
33 }
34 }
35
36 pub fn decode(auth_header_value: String) -> Result<Self, AuthBasicError> {
39 let decoded = BASE64_STANDARD.decode(auth_header_value)?;
40 let as_utf8 = String::from_utf8(decoded)?;
41
42 if let Some((user_id, password)) = as_utf8.split_once(':') {
44 return Ok(Self::new(user_id, password));
45 }
46
47 Err(AuthBasicError::InvalidAuthorizationHeader)
48 }
49
50 pub fn encode(&self) -> String {
52 let credentials = format!("{}:{}", self.user_id, self.password);
53
54 BASE64_STANDARD.encode(credentials.as_bytes())
55 }
56
57 pub fn from_header(auth_header: String) -> Result<Credentials, AuthBasicError> {
60 if let Some((auth_type, encoded_credentials)) = auth_header.split_once(' ') {
62 if encoded_credentials.contains(' ') {
63 return Err(AuthBasicError::InvalidAuthorizationHeader);
65 }
66
67 if auth_type.to_lowercase() != "basic" {
70 return Err(AuthBasicError::InvalidScheme(auth_type.to_string()));
71 }
72
73 let credentials = Credentials::decode(encoded_credentials.to_string())?;
74
75 return Ok(credentials);
76 }
77
78 Err(AuthBasicError::InvalidAuthorizationHeader)
79 }
80
81 pub fn as_http_header(&self) -> String {
84 let as_base64 = self.encode();
85
86 format!("Basic {}", as_base64)
87 }
88}
89
90impl FromStr for Credentials {
91 type Err = AuthBasicError;
92
93 fn from_str(s: &str) -> Result<Self, Self::Err> {
98 if s.contains(' ') {
99 return Self::from_header(s.into());
100 }
101
102 Self::decode(s.into())
103 }
104}