summaryrefslogtreecommitdiffstats
path: root/src/auth/claims.rs
blob: ff582a3a2008d21537b7d7be9758d434b1d1f0fd (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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use axum::{
    async_trait,
    extract::FromRequestParts,
    http::{
        header::{AUTHORIZATION, SET_COOKIE},
        request::Parts,
        HeaderValue,
    },
    response::{IntoResponse, IntoResponseParts},
    RequestPartsExt,
};
use axum_extra::{
    extract::{cookie::Cookie, CookieJar},
    headers::{authorization::Bearer, Authorization},
    TypedHeader,
};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use uuid::Uuid;

use super::{Error, JWT};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Claims<const LIFETIME: i64 = ACCESS> {
    pub sub: Uuid,
    pub iat: i64,
    pub exp: i64,
    pub jti: Uuid,
}

impl<const LIFETIME: i64> Claims<LIFETIME> {
    pub fn new(uuid: Uuid) -> Self {
        let now = OffsetDateTime::now_utc().unix_timestamp();
        Self {
            sub: uuid,
            iat: now,
            exp: now + LIFETIME,
            jti: uuid::Uuid::new_v4(),
        }
    }
}

// 1 day in seconds
const ACCESS: i64 = 86400;

pub type AccessClaims = Claims<ACCESS>;

impl From<RefreshClaims> for AccessClaims {
    fn from(value: RefreshClaims) -> Self {
        Claims::new(value.sub)
    }
}

impl TryFrom<AccessClaims> for Cookie<'_> {
    type Error = Error;

    fn try_from(value: AccessClaims) -> Result<Self, Self::Error> {
        Ok(Cookie::build(("token", JWT.encode(&value)?))
            .expires(OffsetDateTime::from_unix_timestamp(value.exp)?)
            .secure(true)
            .http_only(true)
            .build())
    }
}

impl TryFrom<AccessClaims> for HeaderValue {
    type Error = Error;

    fn try_from(value: AccessClaims) -> Result<Self, Self::Error> {
        Cookie::try_from(value)?
            .to_string()
            .parse()
            .map_err(Into::into)
    }
}

impl IntoResponse for AccessClaims {
    fn into_response(self) -> axum::response::Response {
        (self, ()).into_response()
    }
}

impl IntoResponseParts for AccessClaims {
    type Error = Error;

    fn into_response_parts(
        self,
        mut res: axum::response::ResponseParts,
    ) -> Result<axum::response::ResponseParts, Self::Error> {
        res.headers_mut()
            .append(SET_COOKIE, HeaderValue::try_from(self)?);

        Ok(res)
    }
}

#[async_trait]
impl<S> FromRequestParts<S> for AccessClaims
where
    S: Send + Sync,
{
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        let jar = parts
            .extract::<CookieJar>()
            .await
            .expect("Infallable result was in fact, fallable");

        JWT.decode(jar.get("token").ok_or(Error::JwtNotFound)?.value())
            .map(|t| t.claims)
    }
}

// 30 days in seconds
const REFRESH: i64 = 2_592_000;

pub type RefreshClaims = Claims<REFRESH>;

impl RefreshClaims {
    pub fn refresh(self) -> AccessClaims {
        self.into()
    }
}

impl IntoResponseParts for RefreshClaims {
    type Error = Error;

    fn into_response_parts(
        self,
        mut res: axum::response::ResponseParts,
    ) -> Result<axum::response::ResponseParts, Self::Error> {
        res.headers_mut().append(
            AUTHORIZATION,
            HeaderValue::try_from(format!("Bearer {}", JWT.encode(&self)?))?,
        );

        Ok(res)
    }
}

impl IntoResponse for RefreshClaims {
    fn into_response(self) -> axum::response::Response {
        JWT.encode(&self).into_response()
    }
}

#[async_trait]
impl<S> FromRequestParts<S> for RefreshClaims
where
    S: Send + Sync,
{
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> {
        let TypedHeader(Authorization(bearer)) = parts
            .extract::<TypedHeader<Authorization<Bearer>>>()
            .await
            .map_err(|_| Error::JwtNotFound)?;

        Ok(JWT.decode(bearer.token())?.claims)
    }
}