97 lines
2.6 KiB
TypeScript
97 lines
2.6 KiB
TypeScript
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
|
import User from 'App/Models/User'
|
|
import Database from '@ioc:Adonis/Lucid/Database'
|
|
import { schema, rules } from '@ioc:Adonis/Core/Validator'
|
|
|
|
export default class UsersController {
|
|
public async index({ inertia, bouncer }: HttpContextContract) {
|
|
|
|
await bouncer.with('UserPolicy').authorize('index')
|
|
|
|
const users = await Database
|
|
.from('users')
|
|
.select('id', 'username', 'is_admin')
|
|
|
|
return inertia.render('Users/Index', { users })
|
|
}
|
|
|
|
public async create({ inertia, bouncer }: HttpContextContract) {
|
|
await bouncer
|
|
.with('UserPolicy')
|
|
.authorize('create')
|
|
|
|
return inertia.render('Users/Create')
|
|
}
|
|
|
|
public async store({ bouncer, inertia, request }: HttpContextContract) {
|
|
await bouncer
|
|
.with('UserPolicy')
|
|
.authorize('store')
|
|
|
|
const newUserSchema = schema.create({
|
|
username: schema.string(
|
|
{ trim: true },
|
|
[
|
|
rules.unique({ table: 'users', column: 'username' })
|
|
]
|
|
),
|
|
is_admin: schema.boolean(),
|
|
password: schema.string([
|
|
rules.confirmed("passwordRepeat")
|
|
]),
|
|
password_repeat: schema.string(),
|
|
})
|
|
console.log(request.body())
|
|
|
|
const payload = await request.validate({ schema: newUserSchema })
|
|
console.log(payload)
|
|
|
|
if(request.qs().validate) {
|
|
console.log("darf ich jetzt einen user erstellen?")
|
|
await User.create({
|
|
username: payload.username,
|
|
isAdmin: payload.is_admin,
|
|
password: payload.password,
|
|
})
|
|
|
|
return inertia.render('Users')
|
|
}
|
|
}
|
|
|
|
public async show({ bouncer, params, inertia }: HttpContextContract) {
|
|
const queriedUser: User = await User.findByOrFail('id', params.id)
|
|
|
|
await bouncer
|
|
.with('UserPolicy')
|
|
.authorize('show', queriedUser)
|
|
|
|
return inertia.render('Users/Show', { user: queriedUser })
|
|
}
|
|
|
|
public async edit({ bouncer, params, inertia }: HttpContextContract) {
|
|
const queriedUser: User = await User.findByOrFail('id', params.id)
|
|
|
|
await bouncer
|
|
.with("UserPolicy")
|
|
.authorize('edit', queriedUser)
|
|
|
|
return inertia.render("Users/Edit", { user: queriedUser })
|
|
}
|
|
|
|
public async update({}: HttpContextContract) {}
|
|
|
|
public async destroy({ auth, response, params }: HttpContextContract) {
|
|
if (auth.user?.isAdmin){
|
|
const user = await User.findOrFail(params.id)
|
|
await user.delete()
|
|
.then(
|
|
() => {
|
|
response.redirect('users.index')
|
|
},
|
|
)
|
|
// TODO implement reasonable error handling.
|
|
.catch(error => console.log(error))
|
|
}
|
|
}
|
|
}
|