63 lines
2.0 KiB
TypeScript
63 lines
2.0 KiB
TypeScript
import type { ApiClient } from '@japa/api-client'
|
|
import db from '@adonisjs/lucid/services/db'
|
|
import Admins from '#base_modules/Admin/model/admin'
|
|
import Role from '#base_modules/Role/model/role'
|
|
|
|
let sequence = 0
|
|
|
|
/**
|
|
* Creates an active admin holding exactly the given permission slugs (via a
|
|
* dedicated role) and returns a Bearer token for the access-tokens guard.
|
|
*
|
|
* DB-backed: call from specs that run inside a migrated test database (see
|
|
* `tests/bootstrap.ts`), typically with a global-transaction group hook.
|
|
* Pass an empty array for an admin with no permissions at all.
|
|
*/
|
|
export async function createAdminWithToken(permissions: string[]) {
|
|
sequence += 1
|
|
const suffix = `${Date.now()}-${sequence}`
|
|
|
|
const admin = await Admins.create({
|
|
email: `spec-admin-${suffix}@test.local`,
|
|
password: 'secret-password',
|
|
status: 'active',
|
|
})
|
|
|
|
if (permissions.length > 0) {
|
|
const role = await Role.create({ name: `spec-role-${suffix}` })
|
|
await db.table('admin_roles').insert({ admin_id: admin.id, role_id: role.id })
|
|
await db
|
|
.table('role_permissions')
|
|
.multiInsert(permissions.map((slug) => ({ role_id: role.id, permission_slug: slug })))
|
|
}
|
|
|
|
const accessToken = await Admins.accessTokens.create(admin)
|
|
|
|
return { admin, token: accessToken.value!.release() }
|
|
}
|
|
|
|
/**
|
|
* Logs in as Admin using the test HTTP client.
|
|
* Returns a Bearer token string.
|
|
*/
|
|
export async function loginAsAdmin(client: ApiClient): Promise<string> {
|
|
const email = process.env.ADMIN_EMAIL || 'admin@admin.com'
|
|
const password = process.env.ADMIN_PASSWORD || '1234qqqq'
|
|
|
|
const res = await client.post('/auth/login').json({ email, password })
|
|
|
|
res.assertStatus(200)
|
|
|
|
const body = res.body()
|
|
|
|
// returns: { type, token, user }
|
|
const token = body?.token?.release?.() || body?.token || body?.access_token
|
|
|
|
if (!token) {
|
|
console.error('Login response body:', body)
|
|
throw new Error('Could not acquire admin token from /auth/login response')
|
|
}
|
|
|
|
return token
|
|
}
|