rocket_auth_token/
lib.rs

1//Auth token and credentials helper for your rocket web api. This is a basic token generator crate for Rust Rocket Web. Let credentials = AuthCredentials{email: "email", password: "password"}, use hasher(credentials) function to generate and send AuthToken to user on login. User then need to supply the generated token as auth header when making request to server. Using rocket request guard, grab the auth token and decode with decode_hasher function.
2///
3///
4///
5use base64::{decode, encode};
6use serde::Serialize;
7/// This crate made use of external crate, base64 for encoding and decoding auth credentials
8use std::error::Error;
9
10/// AuthCredentials to be encoded into AuthToken and vice-versa
11#[derive(Debug, Serialize, PartialEq, Clone)]
12pub struct AuthCredentials {
13    pub email: String,
14    pub password: String,
15}
16
17/// AuthToken is to be passed into Authorization header after encoding user credentials
18#[derive(Debug, Serialize, Clone)]
19pub struct AuthToken {
20    pub token: String,
21}
22
23/// Encode AuthCredentials into base64 encoded string and return AuthToken
24pub fn encode_credentials(auth: &AuthCredentials) -> AuthToken {
25    let info = format!("{}:{}", auth.email, auth.password);
26    let hashed = encode(info);
27    AuthToken { token: hashed }
28}
29
30/// Decode passed AuthToken and return AuthCredentials
31pub fn decode_token(hashed: &AuthToken) -> Result<AuthCredentials, Box<dyn Error>> {
32    let decode = decode(&&hashed.token);
33
34    //check if decode result is valid
35    match decode {
36        //if valid proceed with okay
37        Ok(r) => {
38            //Get [u8] from the valid result of AuthToken decoding
39            //Extract String from r using String::from_utf8()
40            let extract = String::from_utf8(r);
41
42            // check extraction outcome
43            match extract {
44                Ok(info) => {
45                    // if extraction is successful continue with Ok
46
47                    //split info from token extraction and collect into a vec, usuaully, the result is always in this form "email.com:password"
48                    let info_vec: Vec<_> = info.split(":").collect();
49
50                    //Pass credentials to AuthCredentials
51                    Ok(AuthCredentials {
52                        email: info_vec[0].to_string(),
53                        password: info_vec[1].to_string(),
54                    })
55                }
56
57                // if extraction is unsuccessful return error
58                Err(_) => return Err("Can't decode, try again".to_string().into()),
59            }
60        }
61        // if decoding is unsuccessful return error
62        Err(_) => return Err("Invalid token!".to_string().into()),
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use crate::{decode_token, encode_credentials, AuthCredentials};
69
70    #[test]
71    fn it_works() {
72        let credentials = AuthCredentials {
73            email: "my@mail.com".to_string(),
74            password: "SamopE160!".to_string(),
75        };
76        let hash = encode_credentials(&credentials);
77        let decode = decode_token(&hash).unwrap();
78
79        assert_eq!(credentials, decode); //true
80    }
81}