Skip to content

Commit 0d81bc6

Browse files
committed
feat: add admin status and default user
1 parent df7b7af commit 0d81bc6

File tree

5 files changed

+58
-1
lines changed

5 files changed

+58
-1
lines changed

.env.example

+3-1
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,6 @@ SMTP_USERNAME=username
1717
SMTP_PASSWORD=password
1818
SMTP_SECURE=false
1919
SMTP_FROM_EMAIL=dev@example.fr
20-
SMTP_FROM_NAME="Dev Aquatracking"
20+
SMTP_FROM_NAME="Dev Aquatracking"
21+
INITIAL_ADMIN_EMAIL=admin@example.fr
22+
INITIAL_ADMIN_PASSWORD=password

app/models/user.ts

+3
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ export default class User extends compose(BaseModel, AuthFinder) {
3232
@column()
3333
declare verified: boolean
3434

35+
@column()
36+
declare isAdmin: boolean
37+
3538
@column.dateTime({ autoCreate: true })
3639
declare createdAt: DateTime
3740

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { BaseSchema } from '@adonisjs/lucid/schema'
2+
3+
export default class extends BaseSchema {
4+
protected tableName = 'users'
5+
6+
async up() {
7+
this.schema.table(this.tableName, (table) => {
8+
table.boolean('is_admin').defaultTo(false)
9+
})
10+
}
11+
12+
async down() {
13+
this.schema.table(this.tableName, (table) => {
14+
table.dropColumn('is_admin')
15+
})
16+
}
17+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import env from '#start/env'
2+
import hash from '@adonisjs/core/services/hash'
3+
import { BaseSchema } from '@adonisjs/lucid/schema'
4+
import { randomUUID } from 'node:crypto'
5+
6+
export default class extends BaseSchema {
7+
async up() {
8+
// Create an admin user if there are no users
9+
const users = await this.db.from('users')
10+
const adminEmail = env.get('INITIAL_ADMIN_EMAIL')
11+
const adminPassword = env.get('INITIAL_ADMIN_PASSWORD')
12+
if (users.length === 0 && adminEmail && adminPassword) {
13+
await this.db.table('users').insert({
14+
id: randomUUID(),
15+
full_name: 'Admin',
16+
verified: true,
17+
email: adminEmail,
18+
password: await hash.make(adminPassword),
19+
is_admin: true,
20+
created_at: this.now(),
21+
updated_at: this.now(),
22+
})
23+
}
24+
}
25+
26+
async down() {}
27+
}

start/env.ts

+8
Original file line numberDiff line numberDiff line change
@@ -49,4 +49,12 @@ export default await Env.create(new URL('../', import.meta.url), {
4949
SMTP_SECURE: Env.schema.boolean(),
5050
SMTP_FROM_EMAIL: Env.schema.string({ format: 'email' }),
5151
SMTP_FROM_NAME: Env.schema.string(),
52+
53+
/*
54+
|----------------------------------------------------------
55+
| Variables for configuring initial user
56+
|----------------------------------------------------------
57+
*/
58+
INITIAL_ADMIN_EMAIL: Env.schema.string.optional({ format: 'email' }),
59+
INITIAL_ADMIN_PASSWORD: Env.schema.string.optional(),
5260
})

0 commit comments

Comments
 (0)