zino_model/user/
jwt_auth.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
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use std::{fmt::Display, str::FromStr};
use zino_auth::JwtClaims;
use zino_core::{
    bail,
    datetime::DateTime,
    error::Error,
    extension::{JsonObjectExt, JsonValueExt},
    model::Query,
    warn, Map, Uuid,
};
use zino_orm::{ModelAccessor, ModelHelper};

/// JWT authentication service.
pub trait JwtAuthService<K = Uuid>
where
    Self: ModelAccessor<K> + ModelHelper<K>,
    K: Default + Display + FromStr + PartialEq + serde::de::DeserializeOwned,
    <K as FromStr>::Err: std::error::Error + Send + 'static,
{
    /// Account field name.
    const ACCOUNT_FIELD: &'static str = "account";
    /// Password field name.
    const PASSWORD_FIELD: &'static str = "password";
    /// Role field name.
    const ROLE_FIELD: Option<&'static str> = Some("roles");
    /// Tenant-ID field name.
    const TENANT_ID_FIELD: Option<&'static str> = None;
    /// Login-at field name.
    const LOGIN_AT_FIELD: Option<&'static str> = None;
    /// Login-IP field name.
    const LOGIN_IP_FIELD: Option<&'static str> = None;

    /// Consumes the user into standard claims without a `sub` field,
    /// which can be used to create a [`JwtClaims`] and generate an ID token.
    /// See [the spec](https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use zino_auth::JwtClaims;
    /// use zino_core::model::Model;
    /// use zino_model::user::{JwtAuthService, User};
    /// use zino_orm::ModelAccessor;
    ///
    /// let user = User::new();
    /// let subject = user.id().to_string();
    /// let custom_data = user.into_standard_claims();
    /// let claims = JwtClaims::with_data(subject, custom_data);
    /// let id_token = claims.sign_with(JwtClaims::shared_key());
    /// ```
    fn into_standard_claims(self) -> Map {
        let standard_fields = [
            "name",
            "given_name",
            "family_name",
            "middle_name",
            "nickname",
            "preferred_username",
            "profile",
            "picture",
            "website",
            "email",
            "email_verified",
            "gender",
            "birthdate",
            "zoneinfo",
            "locale",
            "phone_number",
            "phone_number_verified",
            "address",
        ];
        let address_fields = [
            "formatted",
            "street_address",
            "locality",
            "region",
            "postal_code",
            "country",
        ];

        let mut claims = Map::new();
        claims.upsert("updated_at", self.updated_at().timestamp());
        if let Some(map) = self.extra() {
            for (key, value) in map {
                if key == "address" {
                    if let Some(map) = value.as_object() {
                        let mut address = Map::new();
                        for (key, value) in map {
                            if address_fields.contains(&key.as_str()) {
                                address.upsert(key, value.clone());
                            }
                        }
                        claims.upsert(key, address);
                    }
                } else if standard_fields.contains(&key.as_str()) {
                    claims.upsert(key, value.clone());
                }
            }
        }
        for (key, value) in self.into_map() {
            if key == "address" {
                if let Some(map) = value.into_map_opt() {
                    let mut address = Map::new();
                    for (key, value) in map {
                        if address_fields.contains(&key.as_str()) {
                            address.upsert(key, value);
                        }
                    }
                    claims.upsert(key, address);
                }
            } else if standard_fields.contains(&key.as_str()) {
                claims.upsert(key, value);
            }
        }
        claims
    }

    /// Generates the access token and refresh token.
    async fn generate_token(body: Map) -> Result<(K, Map), Error> {
        let account = body
            .get_str("account")
            .ok_or_else(|| warn!("401 Unauthorized: user `account` should be specified"))?;
        let passowrd = body
            .get_str("password")
            .ok_or_else(|| warn!("401 Unauthorized: user `password` should be specified"))?;
        let mut query = Query::default();
        let mut fields = vec![Self::PRIMARY_KEY_NAME, Self::PASSWORD_FIELD];
        if let Some(role_field) = Self::ROLE_FIELD {
            fields.push(role_field);
        }
        if let Some(tenant_id_field) = Self::TENANT_ID_FIELD {
            fields.push(tenant_id_field);
        }
        if let Some(login_at_field) = Self::LOGIN_AT_FIELD {
            fields.push(login_at_field);
        }
        if let Some(login_ip_field) = Self::LOGIN_IP_FIELD {
            fields.push(login_ip_field);
        }
        query.allow_fields(&fields);
        query.add_filter("status", Map::from_entry("$nin", vec!["Locked", "Deleted"]));
        query.add_filter(Self::ACCOUNT_FIELD, account);

        let mut user: Map = Self::find_one(&query)
            .await?
            .ok_or_else(|| warn!("404 Not Found: invalid user account or password"))?;
        let encrypted_password = user
            .get_str(Self::PASSWORD_FIELD)
            .ok_or_else(|| warn!("404 Not Found: user password is absent"))?;
        if Self::verify_password(passowrd, encrypted_password)
            .map_err(|_| warn!("401 Unauthorized: invalid user account or password"))?
        {
            // Cann't use `get_str` because the primary key may be an integer
            let user_id = user
                .parse_string(Self::PRIMARY_KEY_NAME)
                .ok_or_else(|| warn!("404 Not Found: user id is absent"))?;
            let mut claims = JwtClaims::new(user_id.as_ref());

            let user_id = user_id.parse()?;
            if let Some(role_field) = Self::ROLE_FIELD.filter(|&field| user.contains_key(field)) {
                claims.add_data_entry("roles", user.parse_str_array(role_field));
            }
            if let Some(tenant_id_field) = Self::TENANT_ID_FIELD {
                if let Some(tenant_id) = user.remove(tenant_id_field) {
                    claims.add_data_entry("tenant_id", tenant_id);
                }
            }

            let refresh_token = claims.refresh_token()?;
            let mut data = claims.bearer_auth()?;
            data.upsert("refresh_token", refresh_token);
            if let Some(login_at_field) = Self::LOGIN_AT_FIELD {
                data.upsert(login_at_field, user.remove(login_at_field));
            }
            if let Some(login_ip_field) = Self::LOGIN_IP_FIELD {
                data.upsert(login_ip_field, user.remove(login_ip_field));
            }
            Ok((user_id, data))
        } else {
            Err(warn!("fail to generate access token"))
        }
    }

    /// Refreshes the access token.
    async fn refresh_token(claims: &JwtClaims) -> Result<Map, Error> {
        if !claims.data().is_empty() {
            bail!("401 Unauthorized: JWT token is not a refresh token");
        }

        let Some(user_id) = claims.subject() else {
            bail!("401 Unauthorized: JWT token does not have a subject");
        };

        let mut query = Query::default();
        let mut fields = vec![Self::PRIMARY_KEY_NAME];
        if let Some(role_field) = Self::ROLE_FIELD {
            fields.push(role_field);
        }
        if let Some(tenant_id_field) = Self::TENANT_ID_FIELD {
            fields.push(tenant_id_field);
        }
        query.allow_fields(&fields);
        query.add_filter(Self::PRIMARY_KEY_NAME, user_id);
        query.add_filter(
            "status",
            Map::from_entry("$nin", vec!["SignedOut", "Locked", "Deleted"]),
        );

        let mut user: Map = Self::find_one(&query)
            .await?
            .ok_or_else(|| warn!("404 Not Found: cannot get the user `{}`", user_id))?;
        let mut claims = JwtClaims::new(user_id);
        if let Some(role_field) = Self::ROLE_FIELD.filter(|&field| user.contains_key(field)) {
            claims.add_data_entry("roles", user.parse_str_array(role_field));
        }
        if let Some(tenant_id_field) = Self::TENANT_ID_FIELD {
            if let Some(tenant_id) = user.remove(tenant_id_field) {
                claims.add_data_entry("tenant_id", tenant_id);
            }
        }
        claims.bearer_auth()
    }

    /// Verfifies the JWT claims.
    async fn verify_jwt_claims(claims: &JwtClaims) -> Result<bool, Error> {
        let Some(user_id) = claims.subject() else {
            bail!("401 Unauthorized: JWT token does not have a subject");
        };

        let mut query = Query::default();
        let mut fields = vec![Self::PRIMARY_KEY_NAME];
        if let Some(role_field) = Self::ROLE_FIELD {
            fields.push(role_field);
        }
        if let Some(tenant_id_field) = Self::TENANT_ID_FIELD {
            fields.push(tenant_id_field);
        }
        if let Some(login_at_field) = Self::LOGIN_AT_FIELD {
            fields.push(login_at_field);
        }
        query.allow_fields(&fields);
        query.add_filter(Self::PRIMARY_KEY_NAME, user_id);
        query.add_filter(
            "status",
            Map::from_entry("$nin", vec!["SignedOut", "Locked", "Deleted"]),
        );

        let user: Map = Self::find_one(&query)
            .await?
            .ok_or_else(|| warn!("404 Not Found: cannot get the user `{}`", user_id))?;
        let data = claims.data();
        if let Some(role_field) = Self::ROLE_FIELD {
            if let Some(roles) = data.get("roles") {
                if user.get(role_field) != Some(roles) {
                    bail!("401 Unauthorized: invalid for the `{}` field", role_field);
                }
            }
        }
        if let Some(tenant_id_field) = Self::TENANT_ID_FIELD {
            if let Some(tenant_id) = data.get("tenant_id") {
                if user.get(tenant_id_field) != Some(tenant_id) {
                    bail!(
                        "401 Unauthorized: invalid for the `{}` field",
                        tenant_id_field
                    );
                }
            }
        }
        if let Some(login_at_field) = Self::LOGIN_AT_FIELD {
            if let Some(login_at_str) = user.get_str(login_at_field) {
                if let Ok(login_at) = login_at_str.parse::<DateTime>() {
                    if claims.issued_at().timestamp() < login_at.timestamp() {
                        bail!(
                            "401 Unauthorized: invalid before the `{}` time",
                            login_at_field
                        );
                    }
                }
            }
        }
        Ok(true)
    }

    /// Verifies the user identity.
    async fn verify_identity(user_id: K, body: &Map) -> Result<Map, Error> {
        let mut query = Query::default();
        let mut fields = vec![Self::PRIMARY_KEY_NAME];
        let account = if let Some(account) = body.get_str("account") {
            fields.push(Self::ACCOUNT_FIELD);
            account
        } else {
            ""
        };
        let password = if let Some(passowrd) = body.get_str("password") {
            fields.push(Self::PASSWORD_FIELD);
            passowrd
        } else {
            ""
        };
        query.allow_fields(&fields);
        query.add_filter(Self::PRIMARY_KEY_NAME, user_id.to_string());
        query.add_filter("status", Map::from_entry("$nin", vec!["Locked", "Deleted"]));

        let user: Map = Self::find_one(&query)
            .await?
            .ok_or_else(|| warn!("404 Not Found: cannot get the user `{}`", user_id))?;

        let mut data = Map::new();
        if let Some(user_account) = user.get_str(Self::ACCOUNT_FIELD) {
            let account_verified = user_account == account;
            data.upsert("account_verified", account_verified);
        }
        if let Some(encrypted_password) = user.get_str(Self::PASSWORD_FIELD) {
            let password_verified = Self::verify_password(password, encrypted_password)?;
            data.upsert("password_verified", password_verified);
        }
        Ok(data)
    }
}

impl JwtAuthService<Uuid> for super::User {
    const LOGIN_AT_FIELD: Option<&'static str> = Some("current_login_at");
    const LOGIN_IP_FIELD: Option<&'static str> = Some("current_login_ip");
}