Skip to main content

reifydb_auth/
token.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use std::collections::HashMap;
5
6use rand::{Rng, rng};
7use reifydb_core::interface::auth::AuthenticationProvider;
8use reifydb_type::{Result, error::Error};
9
10use crate::{crypto::constant_time_eq, error::AuthError};
11
12pub struct TokenProvider;
13
14impl AuthenticationProvider for TokenProvider {
15	fn method(&self) -> &str {
16		"token"
17	}
18
19	fn create(&self, _config: &HashMap<String, String>) -> Result<HashMap<String, String>> {
20		let mut bytes = [0u8; 32];
21		rng().fill_bytes(&mut bytes);
22
23		// Encode as hex for readability
24		let token: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
25
26		Ok(HashMap::from([("token".into(), token)]))
27	}
28
29	fn validate(&self, stored: &HashMap<String, String>, credential: &str) -> Result<bool> {
30		let token = stored.get("token").ok_or_else(|| Error::from(AuthError::MissingToken))?;
31
32		// Constant-time comparison
33		Ok(constant_time_eq(token.as_bytes(), credential.as_bytes()))
34	}
35}