refactored users controller

This commit is contained in:
Sergey Yarkov 2021-07-25 17:08:26 +03:00
parent 2c4e86de1e
commit fe6d4a3593
4 changed files with 29 additions and 40 deletions

View File

@ -1,3 +1,4 @@
import { AuthenticationException } from '@adonisjs/auth/build/standalone';
import { Exception } from '@adonisjs/core/build/standalone'; import { Exception } from '@adonisjs/core/build/standalone';
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import Contact from 'App/Models/Contact'; import Contact from 'App/Models/Contact';
@ -25,15 +26,24 @@ export default class UsersController {
* Shows user info of the access token resource owner. * Shows user info of the access token resource owner.
* GET /users/me * GET /users/me
*/ */
public async me({ auth: { user } }: HttpContextContract): Promise<User> { public async showMe({ response, auth }: HttpContextContract) {
if (!user) { const userId = auth.use('api').token?.userId;
throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS');
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'); * Unauthorized user
*/
return user; throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS', 'api');
} }
/** /**
@ -41,7 +51,7 @@ export default class UsersController {
* GET /users * GET /users
*/ */
public async index({ response }: HttpContextContract) { public async showAll({ response }: HttpContextContract) {
const users = await this.user.query().preload('contacts').preload('roles'); const users = await this.user.query().preload('contacts').preload('roles');
return response.ok({ return response.ok({
@ -72,7 +82,7 @@ export default class UsersController {
* POST /users * POST /users
*/ */
public async store({ response, request }: HttpContextContract) { public async create({ response, request }: HttpContextContract) {
await request.validate(CreateUserValidator); await request.validate(CreateUserValidator);
const user = await this.user.create({ const user = await this.user.create({
@ -129,12 +139,7 @@ export default class UsersController {
*/ */
public async destroy({ response, params }: HttpContextContract) { public async destroy({ response, params }: HttpContextContract) {
const user = await this.user const user = await this.user.query().preload('contacts').preload('roles').where('id', params.id).firstOrFail();
.query()
.preload('contacts')
.preload('roles')
.where('id', params.id)
.firstOrFail();
await user.delete(); await user.delete();
@ -190,22 +195,14 @@ export default class UsersController {
*/ */
private async findRolesBySlug(input: string[] | undefined): Promise<Role[]> { private async findRolesBySlug(input: string[] | undefined): Promise<Role[]> {
if (!input) { if (!input) {
throw new Exception( throw new Exception('Unable to find "roles" field in input.', 400, 'E_ROLES_FIELD_NOT_PROVIDED');
'Unable to find "roles" field in input.',
400,
'E_ROLES_FIELD_NOT_PROVIDED'
);
} }
const roles = await this.role.query().whereIn('slug', input); const roles = await this.role.query().whereIn('slug', input);
input.forEach(val => { input.forEach(val => {
if (!roles.map(r => r.slug).includes(val)) { if (!roles.map(r => r.slug).includes(val)) {
throw new Exception( throw new Exception(`Unable to find role: "${val}" using input value "roles"`, 404, 'E_ROLE_NOT_FOUND');
`Unable to find role: "${val}" using input value "roles"`,
404,
'E_ROLE_NOT_FOUND'
);
} }
}); });

View File

@ -52,11 +52,7 @@ export default class AuthMiddleware {
); );
} }
public async handle( public async handle({ auth }: HttpContextContract, next: () => Promise<void>, customGuards: (keyof GuardsList)[]) {
{ auth }: HttpContextContract,
next: () => Promise<void>,
customGuards: (keyof GuardsList)[]
) {
/** /**
* Uses the user defined guards or the default guard mentioned in * Uses the user defined guards or the default guard mentioned in
* the config file * the config file

View File

@ -14,8 +14,8 @@ import {
} from '@ioc:Adonis/Lucid/Orm'; } from '@ioc:Adonis/Lucid/Orm';
import Hash from '@ioc:Adonis/Core/Hash'; import Hash from '@ioc:Adonis/Core/Hash';
import { nanoid } from 'nanoid'; import { nanoid } from 'nanoid';
import Role from './Role'; import Role from 'App/Models/Role';
import Contact from './Contact'; import Contact from 'App/Models/Contact';
export default class User extends BaseModel { export default class User extends BaseModel {
@column({ isPrimary: true }) @column({ isPrimary: true })
@ -80,11 +80,7 @@ export default class User extends BaseModel {
public static async detachRoles(user: User, inputRoles: Role[]): Promise<void> { public static async detachRoles(user: User, inputRoles: Role[]): Promise<void> {
inputRoles.forEach(role => { inputRoles.forEach(role => {
if (!user.roles.map(r => r.id).includes(role.id)) { if (!user.roles.map(r => r.id).includes(role.id)) {
throw new Exception( throw new Exception(`Role "${role.slug}" not attached to that user.`, 400, 'E_ROLE_NOT_ATTACHED');
`Role "${role.slug}" not attached to that user.`,
400,
'E_ROLE_NOT_ATTACHED'
);
} }
}); });

View File

@ -32,14 +32,14 @@ Route.group(() => {
/** /**
* Users controller * Users controller
*/ */
Route.get('users', 'UsersController.index').middleware('role:admin,teacher,student').as('showAllUsers'); Route.get('users', 'UsersController.showAll').middleware('role:admin,teacher,student').as('showAllUsers');
Route.get('users/me', 'UsersController.me').middleware('role:admin,teacher,student').as('showMe');
Route.get('users/:id', 'UsersController.show').middleware('role:admin,teacher,student').as('showUserById'); 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.patch('users/:id', 'UsersController.update').middleware('role:admin').as('updateUser');
Route.delete('users/:id', 'UsersController.destroy').middleware('role:admin').as('deleteUser'); 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.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.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'); }).middleware('auth');
}) })
.prefix('/api/v1') .prefix('/api/v1')