-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
56 lines (48 loc) · 1.46 KB
/
mod.rs
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
use anyhow::Context;
use redis::{AsyncCommands, Client};
use rocket::async_trait;
use super::*;
#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait TokenRepoApi {
async fn save_token(&self, token: &Token, username: &str) -> Result<()>;
async fn get_username(&self, token: &Token) -> Result<String>;
}
pub struct RedisTokenRepo {
client: Client,
}
impl RedisTokenRepo {
pub fn new(client: &Client) -> Self {
Self { client: client.clone() }
}
}
#[async_trait]
impl TokenRepoApi for RedisTokenRepo {
async fn save_token(&self, token: &Token, username: &str) -> Result<()> {
// redis-rs currently doesn't have connection pooling
let mut conn = self
.client
.get_async_connection()
.await
.context("Unable to connect to Redis")?;
let key = get_key(token);
let value = username;
conn.set(key, value).await.context("Unable to store the token")?;
Ok(())
}
async fn get_username(&self, token: &Token) -> Result<String> {
let mut conn = self
.client
.get_async_connection()
.await
.context("Unable to connect to Redis")?;
let key = get_key(token);
let value: Option<String> = conn.get(key).await.context("Unable to fetch the username")?;
value.ok_or(Error::BadToken)
}
}
fn get_key(token: &Token) -> String {
format!("token:{}", token)
}
#[cfg(test)]
mod tests;