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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use std::{borrow::Cow, fmt};

use actix_web::{
    http::header::{HeaderValue, InvalidHeaderValue, TryIntoHeaderValue},
    web::{BufMut, BytesMut},
};

use crate::headers::authorization::{errors::ParseError, scheme::Scheme};

/// Credentials for `Bearer` authentication scheme, defined in [RFC 6750].
///
/// Should be used in combination with [`Authorization`] header.
///
/// [RFC 6750]: https://tools.ietf.org/html/rfc6750
/// [`Authorization`]: crate::headers::authorization::Authorization
#[derive(Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct Bearer {
    token: Cow<'static, str>,
}

impl Bearer {
    /// Creates new `Bearer` credentials with the token provided.
    ///
    /// # Example
    /// ```
    /// # use actix_web_httpauth::headers::authorization::Bearer;
    /// let credentials = Bearer::new("mF_9.B5f-4.1JqM");
    /// ```
    pub fn new<T>(token: T) -> Bearer
    where
        T: Into<Cow<'static, str>>,
    {
        Bearer {
            token: token.into(),
        }
    }

    /// Gets reference to the credentials token.
    pub fn token(&self) -> &str {
        self.token.as_ref()
    }
}

impl Scheme for Bearer {
    fn parse(header: &HeaderValue) -> Result<Self, ParseError> {
        // "Bearer *" length
        if header.len() < 8 {
            return Err(ParseError::Invalid);
        }

        let mut parts = header.to_str()?.splitn(2, ' ');

        match parts.next() {
            Some("Bearer") => {}
            _ => return Err(ParseError::MissingScheme),
        }

        let token = parts.next().ok_or(ParseError::Invalid)?;

        Ok(Bearer {
            token: token.to_string().into(),
        })
    }
}

impl fmt::Debug for Bearer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("Bearer ******"))
    }
}

impl fmt::Display for Bearer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!("Bearer {}", self.token))
    }
}

impl TryIntoHeaderValue for Bearer {
    type Error = InvalidHeaderValue;

    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
        let mut buffer = BytesMut::with_capacity(7 + self.token.len());
        buffer.put(&b"Bearer "[..]);
        buffer.extend_from_slice(self.token.as_bytes());

        HeaderValue::from_maybe_shared(buffer.freeze())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_header() {
        let value = HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM");
        let scheme = Bearer::parse(&value);

        assert!(scheme.is_ok());
        let scheme = scheme.unwrap();
        assert_eq!(scheme.token, "mF_9.B5f-4.1JqM");
    }

    #[test]
    fn test_empty_header() {
        let value = HeaderValue::from_static("");
        let scheme = Bearer::parse(&value);

        assert!(scheme.is_err());
    }

    #[test]
    fn test_wrong_scheme() {
        let value = HeaderValue::from_static("OAuthToken foo");
        let scheme = Bearer::parse(&value);

        assert!(scheme.is_err());
    }

    #[test]
    fn test_missing_token() {
        let value = HeaderValue::from_static("Bearer ");
        let scheme = Bearer::parse(&value);

        assert!(scheme.is_err());
    }

    #[test]
    fn test_into_header_value() {
        let bearer = Bearer::new("mF_9.B5f-4.1JqM");

        let result = bearer.try_into_value();
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            HeaderValue::from_static("Bearer mF_9.B5f-4.1JqM")
        );
    }
}