summaryrefslogtreecommitdiff
path: root/src/login/app.rs
blob: 6da26e9265d01c2bbd2066fd2a864cc849655023 (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
use sqlx::sqlite::SqlitePool;

use super::repo::Provider as _;

#[cfg(test)]
use super::{
    create::{self, Create},
    Login, Password,
};
#[cfg(test)]
use crate::{clock::DateTime, event::Broadcaster, name::Name};

pub struct Logins<'a> {
    db: &'a SqlitePool,
    #[cfg(test)]
    events: &'a Broadcaster,
}

impl<'a> Logins<'a> {
    #[cfg(not(test))]
    pub const fn new(db: &'a SqlitePool) -> Self {
        Self { db }
    }

    #[cfg(test)]
    pub const fn new(db: &'a SqlitePool, events: &'a Broadcaster) -> Self {
        Self { db, events }
    }

    #[cfg(test)]
    pub async fn create(
        &self,
        name: &Name,
        password: &Password,
        created_at: &DateTime,
    ) -> Result<Login, CreateError> {
        let create = Create::begin(name, password, created_at);
        let validated = create.validate()?;

        let mut tx = self.db.begin().await?;
        let stored = validated.store(&mut tx).await?;
        tx.commit().await?;

        let login = stored.publish(self.events);

        Ok(login.as_created())
    }

    pub async fn recanonicalize(&self) -> Result<(), sqlx::Error> {
        let mut tx = self.db.begin().await?;
        tx.logins().recanonicalize().await?;
        tx.commit().await?;

        Ok(())
    }
}

#[cfg(test)]
#[derive(Debug, thiserror::Error)]
pub enum CreateError {
    #[error("invalid login name: {0}")]
    InvalidName(Name),
    #[error(transparent)]
    PasswordHash(#[from] password_hash::Error),
    #[error(transparent)]
    Database(#[from] sqlx::Error),
}

#[cfg(test)]
impl From<create::Error> for CreateError {
    fn from(error: create::Error) -> Self {
        match error {
            create::Error::InvalidName(name) => Self::InvalidName(name),
            create::Error::PasswordHash(error) => Self::PasswordHash(error),
        }
    }
}