mirror of
https://github.com/sergeyyarkov/educt-server.git
synced 2026-10-11 18:29:15 +03:00
refactored users controller
This commit is contained in:
parent
2c4e86de1e
commit
fe6d4a3593
@ -1,3 +1,4 @@
|
||||
import { AuthenticationException } from '@adonisjs/auth/build/standalone';
|
||||
import { Exception } from '@adonisjs/core/build/standalone';
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Contact from 'App/Models/Contact';
|
||||
@ -25,15 +26,24 @@ export default class UsersController {
|
||||
* Shows user info of the access token resource owner.
|
||||
* GET /users/me
|
||||
*/
|
||||
public async me({ auth: { user } }: HttpContextContract): Promise<User> {
|
||||
if (!user) {
|
||||
throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS');
|
||||
public async showMe({ response, auth }: HttpContextContract) {
|
||||
const userId = auth.use('api').token?.userId;
|
||||
|
||||
if (userId) {
|
||||
const user = await this.user.findOrFail(userId);
|
||||
await user.load('contacts');
|
||||
await user.load('roles');
|
||||
|
||||
return response.ok({
|
||||
message: 'Fetched data about me.',
|
||||
data: user,
|
||||
});
|
||||
}
|
||||
|
||||
await user.load('contacts');
|
||||
await user.load('roles');
|
||||
|
||||
return user;
|
||||
/**
|
||||
* Unauthorized user
|
||||
*/
|
||||
throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS', 'api');
|
||||
}
|
||||
|
||||
/**
|
||||
@ -41,7 +51,7 @@ export default class UsersController {
|
||||
* GET /users
|
||||
*/
|
||||
|
||||
public async index({ response }: HttpContextContract) {
|
||||
public async showAll({ response }: HttpContextContract) {
|
||||
const users = await this.user.query().preload('contacts').preload('roles');
|
||||
|
||||
return response.ok({
|
||||
@ -72,7 +82,7 @@ export default class UsersController {
|
||||
* POST /users
|
||||
*/
|
||||
|
||||
public async store({ response, request }: HttpContextContract) {
|
||||
public async create({ response, request }: HttpContextContract) {
|
||||
await request.validate(CreateUserValidator);
|
||||
|
||||
const user = await this.user.create({
|
||||
@ -129,12 +139,7 @@ export default class UsersController {
|
||||
*/
|
||||
|
||||
public async destroy({ response, params }: HttpContextContract) {
|
||||
const user = await this.user
|
||||
.query()
|
||||
.preload('contacts')
|
||||
.preload('roles')
|
||||
.where('id', params.id)
|
||||
.firstOrFail();
|
||||
const user = await this.user.query().preload('contacts').preload('roles').where('id', params.id).firstOrFail();
|
||||
|
||||
await user.delete();
|
||||
|
||||
@ -190,22 +195,14 @@ export default class UsersController {
|
||||
*/
|
||||
private async findRolesBySlug(input: string[] | undefined): Promise<Role[]> {
|
||||
if (!input) {
|
||||
throw new Exception(
|
||||
'Unable to find "roles" field in input.',
|
||||
400,
|
||||
'E_ROLES_FIELD_NOT_PROVIDED'
|
||||
);
|
||||
throw new Exception('Unable to find "roles" field in input.', 400, 'E_ROLES_FIELD_NOT_PROVIDED');
|
||||
}
|
||||
|
||||
const roles = await this.role.query().whereIn('slug', input);
|
||||
|
||||
input.forEach(val => {
|
||||
if (!roles.map(r => r.slug).includes(val)) {
|
||||
throw new Exception(
|
||||
`Unable to find role: "${val}" using input value "roles"`,
|
||||
404,
|
||||
'E_ROLE_NOT_FOUND'
|
||||
);
|
||||
throw new Exception(`Unable to find role: "${val}" using input value "roles"`, 404, 'E_ROLE_NOT_FOUND');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@ -52,11 +52,7 @@ export default class AuthMiddleware {
|
||||
);
|
||||
}
|
||||
|
||||
public async handle(
|
||||
{ auth }: HttpContextContract,
|
||||
next: () => Promise<void>,
|
||||
customGuards: (keyof GuardsList)[]
|
||||
) {
|
||||
public async handle({ auth }: HttpContextContract, next: () => Promise<void>, customGuards: (keyof GuardsList)[]) {
|
||||
/**
|
||||
* Uses the user defined guards or the default guard mentioned in
|
||||
* the config file
|
||||
|
||||
@ -14,8 +14,8 @@ import {
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
import Hash from '@ioc:Adonis/Core/Hash';
|
||||
import { nanoid } from 'nanoid';
|
||||
import Role from './Role';
|
||||
import Contact from './Contact';
|
||||
import Role from 'App/Models/Role';
|
||||
import Contact from 'App/Models/Contact';
|
||||
|
||||
export default class User extends BaseModel {
|
||||
@column({ isPrimary: true })
|
||||
@ -80,11 +80,7 @@ export default class User extends BaseModel {
|
||||
public static async detachRoles(user: User, inputRoles: Role[]): Promise<void> {
|
||||
inputRoles.forEach(role => {
|
||||
if (!user.roles.map(r => r.id).includes(role.id)) {
|
||||
throw new Exception(
|
||||
`Role "${role.slug}" not attached to that user.`,
|
||||
400,
|
||||
'E_ROLE_NOT_ATTACHED'
|
||||
);
|
||||
throw new Exception(`Role "${role.slug}" not attached to that user.`, 400, 'E_ROLE_NOT_ATTACHED');
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@ -32,14 +32,14 @@ Route.group(() => {
|
||||
/**
|
||||
* Users controller
|
||||
*/
|
||||
Route.get('users', 'UsersController.index').middleware('role:admin,teacher,student').as('showAllUsers');
|
||||
Route.get('users/me', 'UsersController.me').middleware('role:admin,teacher,student').as('showMe');
|
||||
Route.get('users', 'UsersController.showAll').middleware('role:admin,teacher,student').as('showAllUsers');
|
||||
Route.get('users/:id', 'UsersController.show').middleware('role:admin,teacher,student').as('showUserById');
|
||||
Route.post('users', 'UsersController.store').middleware('role:admin').as('createUser');
|
||||
Route.post('users', 'UsersController.create').middleware('role:admin').as('createUser');
|
||||
Route.patch('users/:id', 'UsersController.update').middleware('role:admin').as('updateUser');
|
||||
Route.delete('users/:id', 'UsersController.destroy').middleware('role:admin').as('deleteUser');
|
||||
Route.post('users/:id/attach-roles', 'UsersController.attachRoles').middleware('role:admin').as('attachUserRole');
|
||||
Route.delete('users/:id/detach-roles', 'UsersController.detachRoles').middleware('role:admin').as('detachUserRole');
|
||||
Route.get('users/me', 'UsersController.showMe').middleware('role:admin,teacher,student').as('showMe');
|
||||
}).middleware('auth');
|
||||
})
|
||||
.prefix('/api/v1')
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user