Skip to content

Commit

Permalink
feat: added capability to decode supabase web token (AppFlowy-IO#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
speed2exe authored Aug 11, 2023
1 parent 58f0cdd commit d50de4e
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ bytes = "1.4.0"
bincode = "1.3.3"
dashmap = "5.4"
rcgen = { version = "0.10.0", features = ["pem", "x509-parser"] }
jsonwebtoken = "8.3.0"

# tracing
tracing = { version = "0.1.37" }
Expand Down
1 change: 1 addition & 0 deletions src/component/auth/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod error;
mod password;
mod supabase_jwt;
mod user;

pub use error::*;
Expand Down
61 changes: 61 additions & 0 deletions src/component/auth/supabase_jwt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use anyhow::Error;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};

lazy_static::lazy_static! {
pub static ref VALIDATION: Validation = Validation::new(Algorithm::HS256);
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Token {
Anonymous(Anonymous),
Authenticated(Box<Authenticated>),
}

impl Token {
#[allow(dead_code)]
pub fn decode_from_str(&self, token: &str, secret: &[u8]) -> Result<Token, Error> {
let token_data = decode::<Token>(token, &DecodingKey::from_secret(secret), &VALIDATION)?;
Ok(token_data.claims)
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Authenticated {
aud: String,
exp: u64,
iat: u64,
iss: String,
sub: String,
email: String,
phone: String,
app_metadata: AppMetadata,
user_metadata: std::collections::HashMap<String, String>, // or another struct if you know the fields
role: String,
aal: String,
amr: Vec<Amr>,
session_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Anonymous {
iss: String,
#[serde(rename = "ref")]
reference: String,
role: String,
iat: u64,
exp: u64,
}

#[derive(Debug, Serialize, Deserialize)]
struct AppMetadata {
provider: String,
providers: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct Amr {
method: String,
timestamp: u64,
}

0 comments on commit d50de4e

Please sign in to comment.