From fe6d4a3593a35ef08f6618a55a528fb2e0119c81 Mon Sep 17 00:00:00 2001 From: Sergey Yarkov Date: Sun, 25 Jul 2021 17:08:26 +0300 Subject: [PATCH] refactored users controller --- app/Controllers/Http/UsersController.ts | 47 ++++++++++++------------- app/Middleware/Auth.ts | 6 +--- app/Models/User.ts | 10 ++---- start/routes.ts | 6 ++-- 4 files changed, 29 insertions(+), 40 deletions(-) diff --git a/app/Controllers/Http/UsersController.ts b/app/Controllers/Http/UsersController.ts index 08e62e6..a14cd6b 100644 --- a/app/Controllers/Http/UsersController.ts +++ b/app/Controllers/Http/UsersController.ts @@ -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 { - 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 { 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'); } }); diff --git a/app/Middleware/Auth.ts b/app/Middleware/Auth.ts index 4ddbf60..76f00a8 100644 --- a/app/Middleware/Auth.ts +++ b/app/Middleware/Auth.ts @@ -52,11 +52,7 @@ export default class AuthMiddleware { ); } - public async handle( - { auth }: HttpContextContract, - next: () => Promise, - customGuards: (keyof GuardsList)[] - ) { + public async handle({ auth }: HttpContextContract, next: () => Promise, customGuards: (keyof GuardsList)[]) { /** * Uses the user defined guards or the default guard mentioned in * the config file diff --git a/app/Models/User.ts b/app/Models/User.ts index 6087e7f..c903fbb 100644 --- a/app/Models/User.ts +++ b/app/Models/User.ts @@ -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 { 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'); } }); diff --git a/start/routes.ts b/start/routes.ts index a3e91fc..be5755a 100644 --- a/start/routes.ts +++ b/start/routes.ts @@ -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')