mirror of
https://github.com/sergeyyarkov/educt-server.git
synced 2026-10-11 10:19:20 +03:00
added: AuthService
This commit is contained in:
parent
7ef12795d9
commit
a852e82451
@ -1,20 +1,24 @@
|
|||||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||||
import Logger from '@ioc:Adonis/Core/Logger';
|
import { Exception, inject, Ioc } from '@adonisjs/core/build/standalone';
|
||||||
import Hash from '@ioc:Adonis/Core/Hash';
|
import AuthService from 'App/Services/AuthService';
|
||||||
import { Exception } from '@adonisjs/core/build/standalone';
|
|
||||||
|
/**
|
||||||
|
* Validators
|
||||||
|
*/
|
||||||
|
import AuthValidator from 'App/Validators/Auth/AuthValidator';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Models
|
* Models
|
||||||
*/
|
*/
|
||||||
import User from 'App/Models/User';
|
import BaseController from '../../BaseController';
|
||||||
|
|
||||||
export default class AuthController {
|
@inject()
|
||||||
private User: typeof User;
|
export default class AuthController extends BaseController {
|
||||||
|
private authService: AuthService;
|
||||||
|
|
||||||
private guard: 'api';
|
constructor(authService: AuthService) {
|
||||||
|
super();
|
||||||
constructor() {
|
this.authService = authService;
|
||||||
this.User = User;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -22,23 +26,15 @@ export default class AuthController {
|
|||||||
* POST /login
|
* POST /login
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public async login({ auth, request }: HttpContextContract) {
|
public async login(ctx: HttpContextContract) {
|
||||||
const login = request.input('login');
|
const payload = await ctx.request.validate(AuthValidator);
|
||||||
const password = request.input('password');
|
const result = await this.authService.login(payload.login, payload.password, ctx.auth);
|
||||||
const user = await this.User.query().preload('roles').where('login', login).firstOrFail();
|
|
||||||
|
|
||||||
if (!(await Hash.verify(user.password, password))) {
|
if (!result.success && result.error) {
|
||||||
throw new Exception('Invalid credentials.', 403, 'E_INVALID_CREDENTIALS');
|
throw new Exception(result.message, result.status, result.error.code);
|
||||||
}
|
}
|
||||||
|
|
||||||
const token = await auth.use(this.guard).generate(user, {
|
return this.sendResponse(ctx, result.data, result.message, result.status);
|
||||||
expiresIn: '1d',
|
|
||||||
userRoles: user.roles.map(role => role.slug),
|
|
||||||
});
|
|
||||||
|
|
||||||
Logger.info(`A token for user with id: "${token.user.id}" was successfully generated.`);
|
|
||||||
|
|
||||||
return token.toJSON();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -46,8 +42,15 @@ export default class AuthController {
|
|||||||
* POST /logout
|
* POST /logout
|
||||||
*/
|
*/
|
||||||
|
|
||||||
public async logout({ response, auth }: HttpContextContract) {
|
public async logout(ctx: HttpContextContract) {
|
||||||
await auth.use(this.guard).revoke();
|
const result = await this.authService.logout(ctx.auth);
|
||||||
return response.noContent();
|
|
||||||
|
if (!result.success && result.error) {
|
||||||
|
throw new Exception(result.message, result.status, result.error.code);
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.sendResponse(ctx, result.data, result.message, result.status);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
new Ioc().make(AuthController);
|
||||||
|
|||||||
@ -21,6 +21,18 @@ export default class UserRepository {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user by column
|
||||||
|
*
|
||||||
|
* @param column Column name
|
||||||
|
* @param value Comparsion column
|
||||||
|
* @returns User or null
|
||||||
|
*/
|
||||||
|
public async getByColumn(column: string, value: string | number) {
|
||||||
|
const data = await this.User.query().preload('contacts').preload('roles').where(column, value).first();
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get users by role
|
* Get users by role
|
||||||
*
|
*
|
||||||
|
|||||||
100
app/Services/AuthService.ts
Normal file
100
app/Services/AuthService.ts
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
import { inject, Ioc } from '@adonisjs/core/build/standalone';
|
||||||
|
import Hash from '@ioc:Adonis/Core/Hash';
|
||||||
|
import Logger from '@ioc:Adonis/Core/Logger';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interfaces
|
||||||
|
*/
|
||||||
|
import { AuthContract } from '@ioc:Adonis/Addons/Auth';
|
||||||
|
import IResponse from 'App/Datatypes/Interfaces/IResponse';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reposirories
|
||||||
|
*/
|
||||||
|
import UserRepository from 'App/Repositories/UserRepository';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class AuthService {
|
||||||
|
private userRepository: UserRepository;
|
||||||
|
|
||||||
|
private guard: 'api';
|
||||||
|
|
||||||
|
constructor(userRepository: UserRepository) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Login user
|
||||||
|
*
|
||||||
|
* @param login Login
|
||||||
|
* @param password Password
|
||||||
|
* @param auth AuthContact
|
||||||
|
* @returns Token data
|
||||||
|
*/
|
||||||
|
public async login(login: string, password: string, auth: AuthContract): Promise<IResponse> {
|
||||||
|
const user = await this.userRepository.getByColumn('login', login);
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 404,
|
||||||
|
message: 'User not found.',
|
||||||
|
data: {},
|
||||||
|
error: {
|
||||||
|
code: 'E_USER_NOT_FOUND',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invalid credentials while login
|
||||||
|
*/
|
||||||
|
if (!(await Hash.verify(user.password, password))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
status: 403,
|
||||||
|
message: 'Invalid credentials.',
|
||||||
|
data: {},
|
||||||
|
error: {
|
||||||
|
code: 'E_INVALID_CREDENTIALS',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create new token
|
||||||
|
*/
|
||||||
|
const token = await auth.use(this.guard).generate(user, {
|
||||||
|
expiresIn: '1d',
|
||||||
|
userRoles: user.roles.map(role => role.slug),
|
||||||
|
});
|
||||||
|
|
||||||
|
Logger.info(`A token for user with id: "${token.user.id}" was successfully generated.`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
status: 200,
|
||||||
|
message: 'Login success.',
|
||||||
|
data: token.toJSON(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logout user
|
||||||
|
*
|
||||||
|
* @param auth AuthContract
|
||||||
|
* @returns Logout message
|
||||||
|
*/
|
||||||
|
public async logout(auth: AuthContract): Promise<IResponse> {
|
||||||
|
await auth.use(this.guard).revoke();
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
status: 200,
|
||||||
|
message: 'Logout success.',
|
||||||
|
data: {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
new Ioc().make(AuthService);
|
||||||
@ -1,9 +1,25 @@
|
|||||||
import { inject, Ioc } from '@adonisjs/core/build/standalone';
|
import { inject, Ioc } from '@adonisjs/core/build/standalone';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interfaces
|
||||||
|
*/
|
||||||
import IResponse from 'App/Datatypes/Interfaces/IResponse';
|
import IResponse from 'App/Datatypes/Interfaces/IResponse';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Models
|
||||||
|
*/
|
||||||
import Role from 'App/Models/Role';
|
import Role from 'App/Models/Role';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Repositories
|
||||||
|
*/
|
||||||
import ContactRepository from 'App/Repositories/ContactRepository';
|
import ContactRepository from 'App/Repositories/ContactRepository';
|
||||||
import RoleRepository from 'App/Repositories/RoleRepository';
|
import RoleRepository from 'App/Repositories/RoleRepository';
|
||||||
import UserRepository from 'App/Repositories/UserRepository';
|
import UserRepository from 'App/Repositories/UserRepository';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validators
|
||||||
|
*/
|
||||||
import CreateUserValidator from 'App/Validators/User/CreateUserValidator';
|
import CreateUserValidator from 'App/Validators/User/CreateUserValidator';
|
||||||
import UpdateUserValidator from 'App/Validators/User/UpdateUserValidator';
|
import UpdateUserValidator from 'App/Validators/User/UpdateUserValidator';
|
||||||
|
|
||||||
@ -37,7 +53,7 @@ export default class UserService {
|
|||||||
message: 'User not found.',
|
message: 'User not found.',
|
||||||
data: {},
|
data: {},
|
||||||
error: {
|
error: {
|
||||||
code: 'USER_NOT_FOUND',
|
code: 'E_USER_NOT_FOUND',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
13
app/Validators/Auth/AuthValidator.ts
Normal file
13
app/Validators/Auth/AuthValidator.ts
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import { schema } from '@ioc:Adonis/Core/Validator';
|
||||||
|
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||||
|
|
||||||
|
export default class AuthValidator {
|
||||||
|
constructor(protected ctx: HttpContextContract) {}
|
||||||
|
|
||||||
|
public schema = schema.create({
|
||||||
|
login: schema.string(),
|
||||||
|
password: schema.string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
public messages = {};
|
||||||
|
}
|
||||||
@ -4,12 +4,12 @@ Route.group(() => {
|
|||||||
Route.get('/', 'Api/v1/UsersController.list').middleware('role:admin,teacher,student').as('users.list');
|
Route.get('/', 'Api/v1/UsersController.list').middleware('role:admin,teacher,student').as('users.list');
|
||||||
Route.post('/', 'Api/v1/UsersController.create').middleware('role:admin,student').as('users.create');
|
Route.post('/', 'Api/v1/UsersController.create').middleware('role:admin,student').as('users.create');
|
||||||
Route.get('/:id', 'Api/v1/UsersController.show').middleware('role:admin,teacher,student').as('users.show');
|
Route.get('/:id', 'Api/v1/UsersController.show').middleware('role:admin,teacher,student').as('users.show');
|
||||||
Route.put('/:id', 'Api/v1/UsersController.update').middleware('role:admin,student,teacher').as('users.update');
|
Route.put('/:id', 'Api/v1/UsersController.update').middleware('role:admin').as('users.update');
|
||||||
Route.delete('/:id', 'Api/v1/UsersController.delete').middleware('role:admin,student,teacher').as('users.delete');
|
Route.delete('/:id', 'Api/v1/UsersController.delete').middleware('role:admin').as('users.delete');
|
||||||
Route.post('/:id/attach-roles', 'Api/v1/UsersController.attachRoles')
|
Route.post('/:id/attach-roles', 'Api/v1/UsersController.attachRoles')
|
||||||
.middleware('role:admin,student,teacher')
|
.middleware('role:admin')
|
||||||
.as('users.attach-role');
|
.as('users.attach-role');
|
||||||
Route.delete('/:id/detach-roles', 'Api/v1/UsersController.detachRoles')
|
Route.delete('/:id/detach-roles', 'Api/v1/UsersController.detachRoles')
|
||||||
.middleware('role:admin,student,teacher')
|
.middleware('role:admin')
|
||||||
.as('users.detach-role');
|
.as('users.detach-role');
|
||||||
}).prefix('users');
|
}).prefix('users');
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user