aboutsummaryrefslogtreecommitdiff
path: root/crates/secd/src/util/mod.rs
blob: c26986d00b76aeb6ff0e383967aa2482107f5280 (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
pub(crate) mod from;

use rand::{thread_rng, Rng};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use url::Url;

use crate::{AddressType, IdentityId, SecdError, Session, SESSION_DURATION, SESSION_SIZE_BYTES};

pub(crate) fn remove_trailing_slash(url: &mut Url) -> String {
    let mut u = url.to_string();

    if u.ends_with('/') {
        u.pop();
    }

    u
}

pub(crate) fn hash(i: &[u8]) -> Vec<u8> {
    let mut hasher = Sha256::new();
    hasher.update(i);
    hasher.finalize().to_vec()
}

impl AddressType {
    pub fn get_value(&self) -> Option<String> {
        match &self {
            AddressType::Email { email_address } => {
                email_address.as_ref().map(|a| a.to_string().clone())
            }
            AddressType::Sms { phone_number } => phone_number.as_ref().cloned(),
        }
    }
}

impl Session {
    pub(crate) fn new(identity_id: IdentityId) -> Result<Self, SecdError> {
        let token = (0..SESSION_SIZE_BYTES)
            .map(|_| rand::random::<u8>())
            .collect::<Vec<u8>>();
        let now = OffsetDateTime::now_utc();
        Ok(Session {
            identity_id,
            token,
            created_at: now,
            expired_at: now
                .checked_add(time::Duration::new(SESSION_DURATION, 0))
                .ok_or(SecdError::Todo)?,
            revoked_at: None,
        })
    }
}