acton-service 0.23.0

Production-ready Rust backend framework with type-enforced API versioning
Documentation
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! PostgreSQL account storage backend

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sqlx::PgPool;

use super::AccountStorage;
use crate::accounts::types::{Account, AccountId, AccountStatus};
use crate::error::Error;

/// PostgreSQL-backed account storage
pub struct PgAccountStorage {
    pool: PgPool,
}

impl PgAccountStorage {
    /// Create a new PostgreSQL account storage and initialize the schema
    pub async fn new(pool: PgPool) -> Result<Self, Error> {
        let storage = Self { pool };
        storage.initialize().await?;
        Ok(storage)
    }

    async fn initialize(&self) -> Result<(), Error> {
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS accounts (
                id VARCHAR(36) PRIMARY KEY,
                email VARCHAR(255) NOT NULL UNIQUE,
                username VARCHAR(255),
                password_hash TEXT,
                status VARCHAR(32) NOT NULL DEFAULT 'pending_verification',
                roles JSONB NOT NULL DEFAULT '[]',
                email_verified BOOLEAN NOT NULL DEFAULT FALSE,
                email_verified_at TIMESTAMPTZ,
                last_login_at TIMESTAMPTZ,
                locked_at TIMESTAMPTZ,
                locked_reason TEXT,
                disabled_at TIMESTAMPTZ,
                disabled_reason TEXT,
                expires_at TIMESTAMPTZ,
                password_changed_at TIMESTAMPTZ,
                failed_login_count INTEGER NOT NULL DEFAULT 0,
                metadata JSONB,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
            )
            "#,
        )
        .execute(&self.pool)
        .await
        .map_err(|e| Error::Internal(format!("Failed to create accounts table: {}", e)))?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_accounts_email ON accounts(email)")
            .execute(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to create email index: {}", e)))?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_accounts_status ON accounts(status)")
            .execute(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to create status index: {}", e)))?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_accounts_username ON accounts(username) WHERE username IS NOT NULL")
            .execute(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to create username index: {}", e)))?;

        sqlx::query("CREATE INDEX IF NOT EXISTS idx_accounts_expires_at ON accounts(expires_at) WHERE expires_at IS NOT NULL")
            .execute(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to create expires_at index: {}", e)))?;

        Ok(())
    }
}

/// Internal row type for sqlx mapping
#[derive(sqlx::FromRow)]
struct AccountRow {
    id: String,
    email: String,
    username: Option<String>,
    password_hash: Option<String>,
    status: String,
    roles: serde_json::Value,
    email_verified: bool,
    email_verified_at: Option<DateTime<Utc>>,
    last_login_at: Option<DateTime<Utc>>,
    locked_at: Option<DateTime<Utc>>,
    locked_reason: Option<String>,
    disabled_at: Option<DateTime<Utc>>,
    disabled_reason: Option<String>,
    expires_at: Option<DateTime<Utc>>,
    password_changed_at: Option<DateTime<Utc>>,
    failed_login_count: i32,
    metadata: Option<serde_json::Value>,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

impl From<AccountRow> for Account {
    fn from(row: AccountRow) -> Self {
        let id = row.id.parse().unwrap_or_else(|_| AccountId::new());

        let status = row
            .status
            .parse()
            .unwrap_or(AccountStatus::PendingVerification);

        let roles: Vec<String> = serde_json::from_value(row.roles).unwrap_or_default();

        Account {
            id,
            email: row.email,
            username: row.username,
            password_hash: row.password_hash,
            status,
            roles,
            email_verified: row.email_verified,
            email_verified_at: row.email_verified_at,
            last_login_at: row.last_login_at,
            locked_at: row.locked_at,
            locked_reason: row.locked_reason,
            disabled_at: row.disabled_at,
            disabled_reason: row.disabled_reason,
            expires_at: row.expires_at,
            password_changed_at: row.password_changed_at,
            failed_login_count: row.failed_login_count as u32,
            metadata: row.metadata,
            created_at: row.created_at,
            updated_at: row.updated_at,
        }
    }
}

#[async_trait]
impl AccountStorage for PgAccountStorage {
    async fn create(&self, account: &Account) -> Result<(), Error> {
        let roles_json = serde_json::to_value(&account.roles).unwrap_or_default();

        sqlx::query(
            r#"
            INSERT INTO accounts (
                id, email, username, password_hash, status, roles,
                email_verified, email_verified_at, last_login_at,
                locked_at, locked_reason, disabled_at, disabled_reason,
                expires_at, password_changed_at, failed_login_count,
                metadata, created_at, updated_at
            ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19)
            "#,
        )
        .bind(account.id.as_str())
        .bind(&account.email)
        .bind(&account.username)
        .bind(&account.password_hash)
        .bind(account.status.to_string())
        .bind(&roles_json)
        .bind(account.email_verified)
        .bind(account.email_verified_at)
        .bind(account.last_login_at)
        .bind(account.locked_at)
        .bind(&account.locked_reason)
        .bind(account.disabled_at)
        .bind(&account.disabled_reason)
        .bind(account.expires_at)
        .bind(account.password_changed_at)
        .bind(account.failed_login_count as i32)
        .bind(&account.metadata)
        .bind(account.created_at)
        .bind(account.updated_at)
        .execute(&self.pool)
        .await
        .map_err(|e| Error::Internal(format!("Failed to create account: {}", e)))?;

        Ok(())
    }

    async fn get_by_id(&self, id: &str) -> Result<Option<Account>, Error> {
        let row = sqlx::query_as::<_, AccountRow>("SELECT * FROM accounts WHERE id = $1")
            .bind(id)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to get account by id: {}", e)))?;

        Ok(row.map(Into::into))
    }

    async fn get_by_email(&self, email: &str) -> Result<Option<Account>, Error> {
        let row = sqlx::query_as::<_, AccountRow>("SELECT * FROM accounts WHERE email = $1")
            .bind(email)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to get account by email: {}", e)))?;

        Ok(row.map(Into::into))
    }

    async fn get_by_username(&self, username: &str) -> Result<Option<Account>, Error> {
        let row = sqlx::query_as::<_, AccountRow>("SELECT * FROM accounts WHERE username = $1")
            .bind(username)
            .fetch_optional(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to get account by username: {}", e)))?;

        Ok(row.map(Into::into))
    }

    async fn update(&self, account: &Account) -> Result<(), Error> {
        let roles_json = serde_json::to_value(&account.roles).unwrap_or_default();

        sqlx::query(
            r#"
            UPDATE accounts SET
                email = $2, username = $3, password_hash = $4, status = $5,
                roles = $6, email_verified = $7, email_verified_at = $8,
                last_login_at = $9, locked_at = $10, locked_reason = $11,
                disabled_at = $12, disabled_reason = $13, expires_at = $14,
                password_changed_at = $15, failed_login_count = $16,
                metadata = $17, updated_at = $18
            WHERE id = $1
            "#,
        )
        .bind(account.id.as_str())
        .bind(&account.email)
        .bind(&account.username)
        .bind(&account.password_hash)
        .bind(account.status.to_string())
        .bind(&roles_json)
        .bind(account.email_verified)
        .bind(account.email_verified_at)
        .bind(account.last_login_at)
        .bind(account.locked_at)
        .bind(&account.locked_reason)
        .bind(account.disabled_at)
        .bind(&account.disabled_reason)
        .bind(account.expires_at)
        .bind(account.password_changed_at)
        .bind(account.failed_login_count as i32)
        .bind(&account.metadata)
        .bind(Utc::now())
        .execute(&self.pool)
        .await
        .map_err(|e| Error::Internal(format!("Failed to update account: {}", e)))?;

        Ok(())
    }

    async fn update_status(
        &self,
        id: &str,
        status: AccountStatus,
        reason: Option<&str>,
    ) -> Result<(), Error> {
        let now = Utc::now();
        let status_str = status.to_string();

        match status {
            AccountStatus::Disabled => {
                sqlx::query(
                    "UPDATE accounts SET status = $2, disabled_at = $3, disabled_reason = $4, updated_at = $3 WHERE id = $1",
                )
                .bind(id)
                .bind(&status_str)
                .bind(now)
                .bind(reason)
                .execute(&self.pool)
                .await
                .map_err(|e| Error::Internal(format!("Failed to update status: {}", e)))?;
            }
            AccountStatus::Locked => {
                sqlx::query(
                    "UPDATE accounts SET status = $2, locked_at = $3, locked_reason = $4, updated_at = $3 WHERE id = $1",
                )
                .bind(id)
                .bind(&status_str)
                .bind(now)
                .bind(reason)
                .execute(&self.pool)
                .await
                .map_err(|e| Error::Internal(format!("Failed to update status: {}", e)))?;
            }
            AccountStatus::Active => {
                sqlx::query(
                    "UPDATE accounts SET status = $2, locked_at = NULL, locked_reason = NULL, disabled_at = NULL, disabled_reason = NULL, updated_at = $3 WHERE id = $1",
                )
                .bind(id)
                .bind(&status_str)
                .bind(now)
                .execute(&self.pool)
                .await
                .map_err(|e| Error::Internal(format!("Failed to update status: {}", e)))?;
            }
            _ => {
                sqlx::query("UPDATE accounts SET status = $2, updated_at = $3 WHERE id = $1")
                    .bind(id)
                    .bind(&status_str)
                    .bind(now)
                    .execute(&self.pool)
                    .await
                    .map_err(|e| Error::Internal(format!("Failed to update status: {}", e)))?;
            }
        }

        Ok(())
    }

    async fn list(
        &self,
        status_filter: Option<AccountStatus>,
        limit: usize,
        offset: usize,
    ) -> Result<Vec<Account>, Error> {
        let rows = if let Some(status) = status_filter {
            sqlx::query_as::<_, AccountRow>(
                "SELECT * FROM accounts WHERE status = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3",
            )
            .bind(status.to_string())
            .bind(limit as i64)
            .bind(offset as i64)
            .fetch_all(&self.pool)
            .await
        } else {
            sqlx::query_as::<_, AccountRow>(
                "SELECT * FROM accounts ORDER BY created_at DESC LIMIT $1 OFFSET $2",
            )
            .bind(limit as i64)
            .bind(offset as i64)
            .fetch_all(&self.pool)
            .await
        }
        .map_err(|e| Error::Internal(format!("Failed to list accounts: {}", e)))?;

        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn count(&self, status_filter: Option<AccountStatus>) -> Result<u64, Error> {
        let count: (i64,) = if let Some(status) = status_filter {
            sqlx::query_as("SELECT COUNT(*) FROM accounts WHERE status = $1")
                .bind(status.to_string())
                .fetch_one(&self.pool)
                .await
        } else {
            sqlx::query_as("SELECT COUNT(*) FROM accounts")
                .fetch_one(&self.pool)
                .await
        }
        .map_err(|e| Error::Internal(format!("Failed to count accounts: {}", e)))?;

        Ok(count.0 as u64)
    }

    async fn delete(&self, id: &str) -> Result<bool, Error> {
        let result = sqlx::query("DELETE FROM accounts WHERE id = $1")
            .bind(id)
            .execute(&self.pool)
            .await
            .map_err(|e| Error::Internal(format!("Failed to delete account: {}", e)))?;

        Ok(result.rows_affected() > 0)
    }

    async fn record_login(&self, id: &str) -> Result<(), Error> {
        sqlx::query(
            "UPDATE accounts SET last_login_at = $2, failed_login_count = 0, updated_at = $2 WHERE id = $1",
        )
        .bind(id)
        .bind(Utc::now())
        .execute(&self.pool)
        .await
        .map_err(|e| Error::Internal(format!("Failed to record login: {}", e)))?;

        Ok(())
    }

    async fn find_expired(&self, limit: usize) -> Result<Vec<Account>, Error> {
        let rows = sqlx::query_as::<_, AccountRow>(
            "SELECT * FROM accounts WHERE expires_at IS NOT NULL AND expires_at < $1 AND status != 'expired' ORDER BY expires_at ASC LIMIT $2",
        )
        .bind(Utc::now())
        .bind(limit as i64)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| Error::Internal(format!("Failed to find expired accounts: {}", e)))?;

        Ok(rows.into_iter().map(Into::into).collect())
    }

    async fn find_inactive(
        &self,
        cutoff: DateTime<Utc>,
        limit: usize,
    ) -> Result<Vec<Account>, Error> {
        let rows = sqlx::query_as::<_, AccountRow>(
            "SELECT * FROM accounts WHERE status = 'active' AND (last_login_at IS NULL OR last_login_at < $1) ORDER BY last_login_at ASC NULLS FIRST LIMIT $2",
        )
        .bind(cutoff)
        .bind(limit as i64)
        .fetch_all(&self.pool)
        .await
        .map_err(|e| Error::Internal(format!("Failed to find inactive accounts: {}", e)))?;

        Ok(rows.into_iter().map(Into::into).collect())
    }
}