1use std::time::Duration;
10
11use async_trait::async_trait;
12use base64::Engine;
13use base64::engine::general_purpose::URL_SAFE_NO_PAD;
14use chrono::{DateTime, TimeDelta, Utc};
15use puerto_nucleo::ErrorRepositorio;
16use puerto_nucleo::auth::{
17 AlmacenCredenciales, AlmacenSesiones, Autenticador, ErrorAuth, Principal, Sesion,
18};
19use sha2::{Digest, Sha256};
20use sqlx::PgPool;
21use uuid::Uuid;
22
23use crate::mapear_error_sqlx;
24
25pub const TTL_SESION_POR_DEFECTO: Duration = Duration::from_secs(30 * 24 * 3600);
27
28pub fn generar_token() -> Result<String, getrandom::Error> {
30 let mut bytes = [0u8; 32];
31 getrandom::fill(&mut bytes)?;
32 Ok(URL_SAFE_NO_PAD.encode(bytes))
33}
34
35pub fn hash_token(token: &str) -> [u8; 32] {
37 Sha256::digest(token.as_bytes()).into()
38}
39
40pub fn ttl_sesion_from_env() -> Result<Duration, String> {
43 let _ = dotenvy::dotenv();
44 match std::env::var("AUTH_SESSION_TTL") {
45 Err(_) => Ok(TTL_SESION_POR_DEFECTO),
46 Ok(value) => parsear_ttl(&value).ok_or_else(|| {
47 format!("AUTH_SESSION_TTL={value} no es una duración: usa días, horas o minutos (30d, 12h, 90m)")
48 }),
49 }
50}
51
52pub fn parsear_ttl(value: &str) -> Option<Duration> {
54 let value = value.trim();
55 let unit = match value.chars().last()? {
56 'd' => 24 * 3600,
57 'h' => 3600,
58 'm' => 60,
59 _ => return None,
60 };
61 let n: u64 = value[..value.len() - 1].parse().ok()?;
62 if n == 0 {
63 return None;
64 }
65 n.checked_mul(unit).map(Duration::from_secs)
66}
67
68pub struct SesionesPostgres {
72 pool: PgPool,
73 ttl: TimeDelta,
74}
75
76impl SesionesPostgres {
77 pub fn new(pool: PgPool, ttl: Duration) -> Self {
78 Self {
79 pool,
80 ttl: TimeDelta::from_std(ttl).unwrap_or(TimeDelta::MAX),
81 }
82 }
83}
84
85type SessionUser = (
87 Uuid,
88 String,
89 Option<String>,
90 Option<String>,
91 Vec<String>,
92 DateTime<Utc>,
93);
94
95#[async_trait]
96impl AlmacenSesiones for SesionesPostgres {
97 async fn abrir(&self, user_id: Uuid) -> Result<Sesion, ErrorRepositorio> {
98 let token = generar_token().map_err(|err| {
99 tracing::error!(error = %err, "sesiones: no hay aleatoriedad para un token");
100 ErrorRepositorio::NoDisponible
101 })?;
102 let expires_at = Utc::now() + self.ttl;
103 sqlx::query("INSERT INTO sesiones (hash_token, id_usuario, expira_en) VALUES ($1, $2, $3)")
104 .bind(&hash_token(&token)[..])
105 .bind(user_id)
106 .bind(expires_at)
107 .execute(&self.pool)
108 .await
109 .map_err(|err| {
110 tracing::error!(error = %err, %user_id, "sesiones: no se pudo abrir");
111 mapear_error_sqlx(&err)
112 })?;
113 Ok(Sesion::new(token, expires_at))
114 }
115
116 async fn revocar(&self, token: &str) -> Result<(), ErrorRepositorio> {
117 sqlx::query("DELETE FROM sesiones WHERE hash_token = $1")
118 .bind(&hash_token(token)[..])
119 .execute(&self.pool)
120 .await
121 .map(|_| ())
122 .map_err(|err| {
123 tracing::error!(error = %err, "sesiones: no se pudo revocar");
124 mapear_error_sqlx(&err)
125 })
126 }
127}
128
129#[async_trait]
130impl Autenticador for SesionesPostgres {
131 async fn autenticar(&self, token: &str) -> Result<Principal, ErrorAuth> {
132 let row = sqlx::query_as::<_, SessionUser>(
133 "SELECT u.id, u.sujeto, u.email, u.nombre, u.roles, s.expira_en \
134 FROM sesiones s JOIN usuarios u ON u.id = s.id_usuario WHERE s.hash_token = $1",
135 )
136 .bind(&hash_token(token)[..])
137 .fetch_optional(&self.pool)
138 .await
139 .map_err(|err| {
140 tracing::error!(error = %err, "sesiones: falló la búsqueda");
141 ErrorAuth::NoDisponible
142 })?
143 .ok_or(ErrorAuth::Invalido)?;
144 let (id, subject, email, name, roles, expires_at) = row;
145 if expires_at <= Utc::now() {
146 return Err(ErrorAuth::Expirado);
147 }
148 let mut principal = Principal::new(id, subject).con_roles(roles);
149 if let Some(email) = email {
150 principal = principal.con_email(email);
151 }
152 if let Some(name) = name {
153 principal = principal.con_nombre(name);
154 }
155 Ok(principal)
156 }
157}
158
159pub struct CredencialesPostgres {
161 pool: PgPool,
162}
163
164impl CredencialesPostgres {
165 pub fn new(pool: PgPool) -> Self {
166 Self { pool }
167 }
168}
169
170#[async_trait]
171impl AlmacenCredenciales for CredencialesPostgres {
172 async fn hash_contrasena(&self, user_id: Uuid) -> Result<Option<String>, ErrorRepositorio> {
173 sqlx::query_scalar("SELECT hash_contrasena FROM credenciales WHERE id_usuario = $1")
174 .bind(user_id)
175 .fetch_optional(&self.pool)
176 .await
177 .map_err(|err| {
178 tracing::error!(error = %err, %user_id, "credenciales: falló la lectura");
179 mapear_error_sqlx(&err)
180 })
181 }
182
183 async fn guardar_hash_contrasena(
184 &self,
185 user_id: Uuid,
186 hash: &str,
187 ) -> Result<(), ErrorRepositorio> {
188 sqlx::query(
189 "INSERT INTO credenciales (id_usuario, hash_contrasena) VALUES ($1, $2) \
190 ON CONFLICT (id_usuario) DO UPDATE SET hash_contrasena = EXCLUDED.hash_contrasena, \
191 actualizado_en = now()",
192 )
193 .bind(user_id)
194 .bind(hash)
195 .execute(&self.pool)
196 .await
197 .map(|_| ())
198 .map_err(|err| {
199 tracing::error!(error = %err, %user_id, "credenciales: falló la escritura");
200 mapear_error_sqlx(&err)
201 })
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn should_make_a_new_url_safe_token_of_256_bits_each_time() {
211 let first = generar_token().unwrap();
213 let second = generar_token().unwrap();
214
215 assert_eq!(first.len(), 43);
217 assert!(
218 first
219 .chars()
220 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
221 );
222 assert_ne!(first, second);
223 }
224
225 #[test]
226 fn should_hash_a_token_the_same_way_every_time() {
227 assert_eq!(hash_token("abc"), hash_token("abc"));
228 assert_ne!(hash_token("abc"), hash_token("abd"));
229 }
230
231 #[test]
232 fn should_read_days_hours_and_minutes() {
233 assert_eq!(
234 parsear_ttl("30d"),
235 Some(Duration::from_secs(30 * 24 * 3600))
236 );
237 assert_eq!(parsear_ttl("12h"), Some(Duration::from_secs(12 * 3600)));
238 assert_eq!(parsear_ttl(" 90m "), Some(Duration::from_secs(90 * 60)));
239 }
240
241 #[test]
242 fn should_refuse_a_ttl_without_a_unit_a_zero_or_an_overflow() {
243 for value in [
244 "30",
245 "0d",
246 "-1d",
247 "d",
248 "",
249 "1w",
250 "1.5d",
251 "99999999999999999999d",
252 ] {
253 assert_eq!(parsear_ttl(value), None, "{value}");
254 }
255 }
256}