better-auth-api 1.0.0-alpha.2

Plugin implementations for better-auth
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use super::*;
use crate::plugins::test_helpers;
use better_auth_core::entity::{AuthAccount, AuthSession};
use better_auth_core::utils::cookie_utils::related_cookie_name;
use better_auth_core::wire::{SessionView, UserView};
use better_auth_core::{AuthPlugin, CreateSession, CreateUser, HttpMethod};
use chrono::{Duration, Utc};
use std::collections::HashMap;
use std::sync::Arc;

type TestSchema = better_auth_seaorm::store::__private_test_support::bundled_schema::BundledSchema;

async fn create_admin_context() -> (
    AuthContext<TestSchema>,
    UserView,
    SessionView,
    UserView,
    SessionView,
) {
    let ctx = test_helpers::create_test_context().await;

    let admin = test_helpers::create_user(
        &ctx,
        CreateUser::new()
            .with_email("admin@example.com")
            .with_name("Admin")
            .with_role("admin"),
    )
    .await;
    let admin_session =
        test_helpers::create_session(&ctx, admin.id.clone(), Duration::hours(24)).await;

    let user = test_helpers::create_user(
        &ctx,
        CreateUser::new()
            .with_email("user@example.com")
            .with_name("Regular User")
            .with_role("user"),
    )
    .await;
    let user_session =
        test_helpers::create_session(&ctx, user.id.clone(), Duration::hours(24)).await;

    (ctx, admin, admin_session, user, user_session)
}

fn make_request(
    method: HttpMethod,
    path: &str,
    token: &str,
    body: Option<serde_json::Value>,
) -> AuthRequest {
    test_helpers::create_auth_json_request_no_query(method, path, Some(token), body)
}

fn json_body(resp: &AuthResponse) -> serde_json::Value {
    serde_json::from_slice(&resp.body).unwrap()
}

fn set_cookie_value(resp: &AuthResponse, name: &str) -> Option<String> {
    resp.headers.get_all("Set-Cookie").find_map(|header| {
        let (cookie_name, remainder) = header.split_once('=')?;
        if cookie_name != name {
            return None;
        }
        Some(remainder.split(';').next().unwrap_or_default().to_string())
    })
}

#[tokio::test]
async fn test_custom_admin_role_can_use_permission_engine() {
    let config = Arc::new(better_auth_core::AuthConfig::new(
        "test-secret-key-at-least-32-chars-long",
    ));
    let database = test_helpers::create_test_database().await;
    let ctx = AuthContext::new(config, database.clone());

    let admin = database
        .create_user(
            CreateUser::new()
                .with_email("superadmin@example.com")
                .with_name("Super Admin")
                .with_role("superadmin"),
        )
        .await
        .unwrap();

    let admin_session = database
        .create_session(CreateSession {
            user_id: admin.id.clone(),
            expires_at: Utc::now() + Duration::hours(24),
            ip_address: None,
            user_agent: None,
            impersonated_by: None,
            active_organization_id: None,
        })
        .await
        .unwrap();

    let _user = database
        .create_user(
            CreateUser::new()
                .with_email("user@example.com")
                .with_name("User")
                .with_role("user"),
        )
        .await
        .unwrap();

    let plugin = AdminPlugin::with_config(AdminConfig {
        admin_roles: vec!["superadmin".to_string()],
        roles: HashMap::from([(
            "superadmin".to_string(),
            RolePermissions::new()
                .allow(
                    "user",
                    [
                        "create",
                        "list",
                        "set-role",
                        "ban",
                        "impersonate",
                        "delete",
                        "set-password",
                        "get",
                        "update",
                    ],
                )
                .allow("session", ["list", "revoke", "delete"]),
        )]),
        ..Default::default()
    });

    let req = make_request(
        HttpMethod::Get,
        "/admin/list-users",
        &admin_session.token,
        None,
    );

    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(json_body(&resp)["total"], 2);
}

#[tokio::test]
async fn test_ban_revokes_user_sessions() {
    let (ctx, _admin, admin_session, user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let sessions = ctx.database.get_user_sessions(&user.id).await.unwrap();
    assert!(!sessions.is_empty());

    let req = make_request(
        HttpMethod::Post,
        "/admin/ban-user",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user.id,
            "banReason": "bad behavior"
        })),
    );

    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    assert_eq!(resp.status, 200);

    let sessions = ctx.database.get_user_sessions(&user.id).await.unwrap();
    assert!(sessions.is_empty());
}

#[tokio::test]
async fn test_unban_clears_ban_reason_and_expires() {
    let (ctx, _admin, admin_session, user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/ban-user",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user.id,
            "banReason": "spam",
            "banExpiresIn": 3600
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    assert_eq!(resp.status, 200);

    let req = make_request(
        HttpMethod::Post,
        "/admin/unban-user",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user.id,
        })),
    );

    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    assert_eq!(resp.status, 200);

    let updated_user = ctx
        .database
        .get_user_by_id(&user.id)
        .await
        .unwrap()
        .unwrap();
    assert!(!updated_user.banned);
    assert!(updated_user.ban_reason.is_none());
    assert!(updated_user.ban_expires.is_none());
}

#[tokio::test]
async fn test_impersonation_session_tracks_admin_id() {
    let (ctx, admin, admin_session, user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/impersonate-user",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user.id,
        })),
    );

    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    let admin_cookie_name = related_cookie_name(&ctx.config, "admin_session");
    assert!(
        set_cookie_value(&resp, &admin_cookie_name).is_some(),
        "impersonation should emit an admin_session cookie"
    );
    let token = json_body(&resp)["session"]["token"]
        .as_str()
        .unwrap()
        .to_string();
    let session = ctx.database.get_session(&token).await.unwrap().unwrap();

    assert_eq!(session.impersonated_by().unwrap(), admin.id);
}

#[tokio::test]
async fn test_stop_impersonating_restores_admin_session() {
    let (ctx, admin, admin_session, user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/impersonate-user",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user.id,
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    let impersonation_token = json_body(&resp)["session"]["token"]
        .as_str()
        .unwrap()
        .to_string();
    let admin_cookie_name = related_cookie_name(&ctx.config, "admin_session");
    let admin_cookie = set_cookie_value(&resp, &admin_cookie_name)
        .expect("impersonation should set the admin_session cookie");

    let mut req = make_request(
        HttpMethod::Post,
        "/admin/stop-impersonating",
        &impersonation_token,
        None,
    );
    req.headers.insert(
        "cookie".to_string(),
        format!("{admin_cookie_name}={admin_cookie}"),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    let body = json_body(&resp);

    let restored_token = body["session"]["token"].as_str().unwrap();
    assert_eq!(
        restored_token, admin_session.token,
        "stop-impersonating should restore the original admin session token"
    );
    let restored_session = ctx
        .database
        .get_session(restored_token)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(restored_session.user_id, admin.id);
    assert!(restored_session.impersonated_by.is_none());
    assert!(
        ctx.database
            .get_session(&impersonation_token)
            .await
            .unwrap()
            .is_none()
    );
    let cleared_admin_cookie = resp
        .headers
        .get_all("Set-Cookie")
        .find(|header| header.starts_with(&format!("{admin_cookie_name}=")))
        .expect("stop-impersonating should clear admin_session");
    assert!(
        cleared_admin_cookie.contains("Max-Age=0"),
        "admin_session should be cleared after stop-impersonating"
    );
}

#[tokio::test]
async fn test_list_user_sessions_missing_user_returns_empty_array() {
    let (ctx, _admin, admin_session, _user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/list-user-sessions",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": "missing-user",
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();

    assert_eq!(resp.status, 200);
    assert_eq!(json_body(&resp), serde_json::json!({ "sessions": [] }));
}

#[tokio::test]
async fn test_revoke_user_sessions_missing_user_still_succeeds() {
    let (ctx, _admin, admin_session, _user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/revoke-user-sessions",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": "missing-user",
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();

    assert_eq!(resp.status, 200);
    assert_eq!(json_body(&resp), serde_json::json!({ "success": true }));
}

#[tokio::test]
async fn test_stop_impersonating_without_impersonated_session_returns_bad_request() {
    let (ctx, _admin, admin_session, _user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/stop-impersonating",
        &admin_session.token,
        None,
    );
    let err = plugin.on_request(&req, &ctx).await.unwrap_err();
    let response = err.to_auth_response();
    assert_eq!(response.status, 400);
    assert_eq!(
        json_body(&response),
        serde_json::json!({
            "code": "YOU_ARE_NOT_IMPERSONATING_ANYONE",
            "message": "You are not impersonating anyone"
        })
    );
}

#[tokio::test]
async fn test_remove_user_cleans_up_sessions_and_accounts() {
    let (ctx, _admin, admin_session, _user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/create-user",
        &admin_session.token,
        Some(serde_json::json!({
            "email": "tobedeleted@example.com",
            "password": "securepassword123",
            "name": "To Be Deleted"
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    let user_id = json_body(&resp)["user"]["id"].as_str().unwrap().to_string();

    let accounts = ctx.database.get_user_accounts(&user_id).await.unwrap();
    assert_eq!(accounts.len(), 1);

    let req = make_request(
        HttpMethod::Post,
        "/admin/remove-user",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user_id,
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    assert_eq!(resp.status, 200);

    assert!(
        ctx.database
            .get_user_by_id(&user_id)
            .await
            .unwrap()
            .is_none()
    );
    assert!(
        ctx.database
            .get_user_accounts(&user_id)
            .await
            .unwrap()
            .is_empty()
    );
}

#[tokio::test]
async fn test_set_user_password_updates_credential_account() {
    let (ctx, _admin, admin_session, _user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/create-user",
        &admin_session.token,
        Some(serde_json::json!({
            "email": "pwuser@example.com",
            "password": "oldpassword123",
            "name": "PW User"
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    let user_id = json_body(&resp)["user"]["id"].as_str().unwrap().to_string();

    let before = ctx.database.get_user_accounts(&user_id).await.unwrap();
    let old_password = before[0].password().unwrap().to_string();

    let req = make_request(
        HttpMethod::Post,
        "/admin/set-user-password",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user_id,
            "newPassword": "newpassword456"
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    assert_eq!(resp.status, 200);

    let after = ctx.database.get_user_accounts(&user_id).await.unwrap();
    let new_password = after[0].password().unwrap().to_string();
    assert_ne!(old_password, new_password);
}

#[tokio::test]
async fn test_set_user_password_does_not_create_credential_account() {
    let (ctx, _admin, admin_session, _user, _user_session) = create_admin_context().await;
    let plugin = AdminPlugin::new();

    let req = make_request(
        HttpMethod::Post,
        "/admin/create-user",
        &admin_session.token,
        Some(serde_json::json!({
            "email": "passwordless@example.com",
            "name": "Passwordless User"
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    let user_id = json_body(&resp)["user"]["id"].as_str().unwrap().to_string();

    let req = make_request(
        HttpMethod::Post,
        "/admin/set-user-password",
        &admin_session.token,
        Some(serde_json::json!({
            "userId": user_id,
            "newPassword": "newpassword456"
        })),
    );
    let resp = plugin.on_request(&req, &ctx).await.unwrap().unwrap();
    assert_eq!(resp.status, 200);

    assert!(
        ctx.database
            .get_user_accounts(&user_id)
            .await
            .unwrap()
            .is_empty()
    );
}