summaryrefslogtreecommitdiff
path: root/src/login/app.rs
blob: 292b95fddb522fd24a137f438873cac054b7a51a (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
use chrono::TimeDelta;
use sqlx::sqlite::SqlitePool;

use super::repo::auth::Provider as _;
use crate::{
    clock::DateTime,
    password::StoredHash,
    repo::{
        error::NotFound as _,
        login::{Login, Provider as _},
        token::Provider as _,
    },
};

pub struct Logins<'a> {
    db: &'a SqlitePool,
}

impl<'a> Logins<'a> {
    pub const fn new(db: &'a SqlitePool) -> Self {
        Self { db }
    }

    pub async fn login(
        &self,
        name: &str,
        password: &str,
        login_at: &DateTime,
    ) -> Result<String, LoginError> {
        let mut tx = self.db.begin().await?;

        let login = if let Some((login, stored_hash)) = tx.auth().for_name(name).await? {
            if stored_hash.verify(password)? {
                // Password verified; use the login.
                login
            } else {
                // Password NOT verified.
                return Err(LoginError::Rejected);
            }
        } else {
            let password_hash = StoredHash::new(password)?;
            tx.logins().create(name, &password_hash).await?
        };

        let token = tx.tokens().issue(&login, login_at).await?;
        tx.commit().await?;

        Ok(token)
    }

    #[cfg(test)]
    pub async fn create(&self, name: &str, password: &str) -> Result<Login, CreateError> {
        let password_hash = StoredHash::new(password)?;

        let mut tx = self.db.begin().await?;
        let login = tx.logins().create(name, &password_hash).await?;
        tx.commit().await?;

        Ok(login)
    }

    pub async fn validate(&self, secret: &str, used_at: &DateTime) -> Result<Login, ValidateError> {
        let mut tx = self.db.begin().await?;
        let login = tx
            .tokens()
            .validate(secret, used_at)
            .await
            .not_found(|| ValidateError::InvalidToken)?;
        tx.commit().await?;

        Ok(login)
    }

    pub async fn expire(&self, relative_to: &DateTime) -> Result<(), sqlx::Error> {
        // Somewhat arbitrarily, expire after 7 days.
        let expire_at = relative_to.to_owned() - TimeDelta::days(7);

        let mut tx = self.db.begin().await?;
        tx.tokens().expire(&expire_at).await?;
        tx.commit().await?;

        Ok(())
    }

    pub async fn logout(&self, secret: &str) -> Result<(), ValidateError> {
        let mut tx = self.db.begin().await?;
        tx.tokens()
            .revoke(secret)
            .await
            .not_found(|| ValidateError::InvalidToken)?;

        tx.commit().await?;

        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum LoginError {
    #[error("invalid login")]
    Rejected,
    #[error(transparent)]
    DatabaseError(#[from] sqlx::Error),
    #[error(transparent)]
    PasswordHashError(#[from] password_hash::Error),
}

#[cfg(test)]
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub enum CreateError {
    DatabaseError(#[from] sqlx::Error),
    PasswordHashError(#[from] password_hash::Error),
}

#[derive(Debug, thiserror::Error)]
pub enum ValidateError {
    #[error("invalid token")]
    InvalidToken,
    #[error(transparent)]
    DatabaseError(#[from] sqlx::Error),
}