Skip to content

Commit

Permalink
Adicionando api JWT no Mapos
Browse files Browse the repository at this point in the history
  • Loading branch information
juliolobo committed Mar 30, 2024
1 parent a6ae21e commit 3c8e6fc
Show file tree
Hide file tree
Showing 21 changed files with 5,724 additions and 2 deletions.
3 changes: 2 additions & 1 deletion application/config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,8 @@
"email.*+",
"permissoes.*+",
"auditoria.*+",
"tools.*+"
"tools.*+",
"api.*+"
];

/*
Expand Down
37 changes: 37 additions & 0 deletions application/config/jwt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php defined('BASEPATH') OR exit('No direct script access allowed');

/*
|--------------------
| JWT Secure Key
|--------------------------------------------------------------------------
*/
$config['jwt_key'] = 'cf51557196367f204f2a824c3db7c3cabdc5611a766feadfeeb23f208de65746';


/*
|-----------------------
| JWT Algorithm Type
|--------------------------------------------------------------------------
*/
$config['jwt_algorithm'] = 'HS256';


/*
|-----------------------
| Token Request Header Name
|--------------------------------------------------------------------------
*/
$config['token_header'] = 'x-api-key';


/*
|-----------------------
| Token Expire Time
| https://www.tools4noobs.com/online_tools/hh_mm_ss_to_seconds/
|--------------------------------------------------------------------------
| ( 1 Day ) : 60 * 60 * 24 = 86400
| ( 1 Hour ) : 60 * 60 = 3600
| ( 1 Minute ) : 60 = 60
*/
$config['token_expire_time'] = 86400;
27 changes: 26 additions & 1 deletion application/config/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,32 @@
$route['default_controller'] = "mapos";
$route['404_override'] = '';


// Rotas API
$route['api'] = 'api/ApiController/index';
$route['api/audit'] = 'api/ApiController/audit';
$route['api/login'] = 'api/UsuariosController/login';
$route['api/reGenToken'] = 'api/UsuariosController/reGenToken';
$route['api/conta'] = 'api/UsuariosController/conta';
$route['api/emitente'] = 'api/ApiController/emitente';
$route['api/clientes'] = 'api/ClientesController/index';
$route['api/clientes/(:num)'] = 'api/ClientesController/index/$1';
$route['api/produtos'] = 'api/ProdutosController/index';
$route['api/produtos/(:num)'] = 'api/ProdutosController/index/$1';
$route['api/servicos'] = 'api/ServicosController/index';
$route['api/servicos/(:num)'] = 'api/ServicosController/index/$1';
$route['api/usuarios'] = 'api/UsuariosController/index';
$route['api/usuarios/(:num)'] = 'api/UsuariosController/index/$1';
$route['api/os'] = 'api/OsController/index';
$route['api/os/(:num)'] = 'api/OsController/index/$1';
$route['api/os/(:num)/produtos'] = 'api/OsController/produtos/$1';
$route['api/os/(:num)/produtos/(:num)'] = 'api/OsController/produtos/$1/$2';
$route['api/os/(:num)/servicos'] = 'api/OsController/servicos/$1';
$route['api/os/(:num)/servicos/(:num)'] = 'api/OsController/servicos/$1/$2';
$route['api/os/(:num)/anotacoes'] = 'api/OsController/anotacoes/$1';
$route['api/os/(:num)/anotacoes/(:num)'] = 'api/OsController/anotacoes/$1/$2';
$route['api/os/(:num)/anexos'] = 'api/OsController/anexos/$1';
$route['api/os/(:num)/anexos/(:num)'] = 'api/OsController/anexos/$1/$2';
$route['api/os/(:num)/desconto'] = 'api/OsController/desconto/$1';

/* End of file routes.php */
/* Location: ./application/config/routes.php */
83 changes: 83 additions & 0 deletions application/controllers/api/ApiController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
* Classe ApiController.
*
* @extends REST_Controller
*/
require(APPPATH.'/libraries/REST_Controller.php');

class ApiController extends REST_Controller
{
public function __construct()
{
parent::__construct();

$this->load->library('Authorization_Token');
$this->load->model('mapos_model');
}

public function index_get()
{
$user = $this->logged_user();

$result = new stdClass;
$result->countOs = $this->mapos_model->count('os');
$result->clientes = $this->mapos_model->count('clientes');
$result->produtos = $this->mapos_model->count('produtos');
$result->servicos = $this->mapos_model->count('servicos');
$result->garantias = $this->mapos_model->count('garantias');
$result->vendas = $this->mapos_model->count('vendas');

$result->osAbertas = $this->mapos_model->getOsAbertas();
$result->osAndamento = $this->mapos_model->getOsAndamento();
$result->estoqueBaixo = $this->mapos_model->getProdutosMinimo();

$this->response([
'status' => true,
'message' => 'Dashboard',
'result' => $result
], REST_Controller::HTTP_OK);
}

public function emitente_get()
{
$this->logged_user();

$result = new stdClass;
$result->appName = $this->getConfig('app_name');
$result->emitente = $this->mapos_model->getEmitente() ?: false;

$this->response([
'status' => true,
'message' => 'Dados do Map-OS',
'result' => $result
], REST_Controller::HTTP_OK);
}

public function audit_get()
{
$this->logged_user();

if (!$this->permission->checkPermission($this->logged_user()->level, 'cAuditoria')) {
$this->response([
'status' => false,
'message' => 'Você não está autorizado a Visualizar Auditoria'
], REST_Controller::HTTP_UNAUTHORIZED);
}

$perPage = $this->input->get('perPage') ?: 20;
$page = $this->input->get('page') ?: 0;
$start = $page ? ($perPage * $page) : 0;

$this->load->model('Audit_model');
$logs = $this->Audit_model->get('logs', '*', '', $perPage, $start);

$this->response([
'status' => true,
'message' => 'Listando Logs',
'result' => $logs
], REST_Controller::HTTP_OK);
}
}
224 changes: 224 additions & 0 deletions application/controllers/api/ClientesController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require(APPPATH.'/libraries/REST_Controller.php');

class ClientesController extends REST_Controller
{
public function __construct()
{
parent::__construct();

$this->load->model('clientes_model');
$this->load->helper('validation_helper');
}

public function index_get($id = '')
{
$this->logged_user();
if (!$this->permission->checkPermission($this->logged_user()->level, 'vCliente')) {
$this->response([
'status' => false,
'message' => 'Você não está autorizado a Visualizar Clientes'
], REST_Controller::HTTP_UNAUTHORIZED);
}

if(!$id) {
$search = trim($this->input->get('search'));
$where = $search ? "nomeCliente LIKE '%{$search}%' OR documento LIKE '%{$search}%' OR telefone LIKE '%{$search}%' OR celular LIKE '%{$search}%' OR email LIKE '%{$search}%' OR contato LIKE '%{$search}%'" : '';

$perPage = $this->input->get('perPage') ?: 20;
$page = $this->input->get('page') ?: 0;
$start = $page ? ($perPage * $page) : 0;

$clientes = $this->clientes_model->get('clientes', '*', $where, $perPage, $start);

if($clientes) {
$this->response([
'status' => true,
'message' => 'Lista de Clientes',
'result' => $clientes
], REST_Controller::HTTP_OK);
}
}

if($id && is_numeric($id)) {
$cliente = $this->clientes_model->getById($id);

if($cliente) {
$cliente->ordensServicos = $this->clientes_model->getOsByCliente($id);
$this->response([
'status' => true,
'message' => 'Detalhes do Cliente',
'result' => $cliente
], REST_Controller::HTTP_OK);
}

$this->response([
'status' => false,
'message' => 'Nenhum cliente localizado com esse ID.',
'result' => null,
], REST_Controller::HTTP_OK);
}

$this->response([
'status' => false,
'message' => 'Nenhum cliente localizado.',
'result' => null,
], REST_Controller::HTTP_OK);
}

public function index_post()
{
$this->logged_user();
if (!$this->permission->checkPermission($this->logged_user()->level, 'aCliente')) {
$this->response([
'status' => false,
'message' => 'Você não está autorizado a Adicionar Clientes!'
], REST_Controller::HTTP_UNAUTHORIZED);
}

$_POST = (array) json_decode(file_get_contents("php://input"), true);

$this->load->library('form_validation');

if ($this->form_validation->run('clientes') == false) {
$this->response([
'status' => false,
'message' => validation_errors()
], REST_Controller::HTTP_BAD_REQUEST);
}

$senhaCliente = $this->input->post('senha') ?: preg_replace('/[^\p{L}\p{N}\s]/', '', $this->input->post('documento'));
$cpf_cnpj = preg_replace('/[^\p{L}\p{N}\s]/', '', $this->input->post('documento'));
$pessoaFisica = strlen($cpf_cnpj) == 11 ? true : false;

$data = [
'nomeCliente' => $this->input->post('nomeCliente'),
'contato' => $this->input->post('contato'),
'pessoa_fisica' => $pessoaFisica,
'documento' => $this->input->post('documento'),
'telefone' => $this->input->post('telefone'),
'celular' => $this->input->post('celular'),
'email' => $this->input->post('email'),
'senha' => password_hash($senhaCliente, PASSWORD_DEFAULT),
'rua' => $this->input->post('rua'),
'numero' => $this->input->post('numero'),
'complemento' => $this->input->post('complemento'),
'bairro' => $this->input->post('bairro'),
'cidade' => $this->input->post('cidade'),
'estado' => $this->input->post('estado'),
'cep' => $this->input->post('cep'),
'dataCadastro' => date('Y-m-d'),
'fornecedor' => $this->input->post('fornecedor') == true ? 1 : 0,
];

if ($this->clientes_model->add('clientes', $data) == true) {
$this->response([
'status' => true,
'message' => 'Cliente adicionado com sucesso!',
'result' => $this->clientes_model->get('clientes', '*', "telefone = '{$data['telefone']}'", 1, 0, true)
], REST_Controller::HTTP_CREATED);
}

$this->response([
'status' => false,
'message' => 'Não foi possível adicionar o Cliente.'
], REST_Controller::HTTP_INTERNAL_ERROR);
}

public function index_put($id)
{
$this->logged_user();
if (!$this->permission->checkPermission($this->logged_user()->level, 'eCliente')) {
$this->response([
'status' => false,
'message' => 'Você não está autorizado a Editar Clientes!'
], REST_Controller::HTTP_UNAUTHORIZED);
}

$inputData = json_decode(trim(file_get_contents('php://input')));

if(isset($inputData->documento) && !verific_cpf_cnpj($inputData->documento)) {
$this->response([
'status' => false,
'message' => 'CPF/CNPJ inválido. Verifique o número do documento e tente novamente.'
], REST_Controller::HTTP_BAD_REQUEST);
}

$data = [
'nomeCliente' => $inputData->nomeCliente,
'contato' => $inputData->contato,
'documento' => $inputData->documento,
'telefone' => $inputData->telefone,
'celular' => $inputData->celular,
'email' => $inputData->email,
'rua' => $inputData->rua,
'numero' => $inputData->numero,
'complemento' => $inputData->complemento,
'bairro' => $inputData->bairro,
'cidade' => $inputData->cidade,
'estado' => $inputData->estado,
'cep' => $inputData->cep,
'fornecedor' => $inputData->fornecedor == true ? 1 : 0
];

if($this->put('senha')) {
$data['senha'] = password_hash($this->put('senha'), PASSWORD_DEFAULT);
}

if ($this->clientes_model->edit('clientes', $data, 'idClientes', $id) == true) {
$this->response([
'status' => true,
'message' => 'Cliente editado com sucesso!',
'result' => $this->clientes_model->getById($id)
], REST_Controller::HTTP_OK);
}

$this->response([
'status' => false,
'message' => 'Não foi possível editar o Cliente.'
], REST_Controller::HTTP_INTERNAL_ERROR);
}

public function index_delete($id)
{
$this->logged_user();
if (!$this->permission->checkPermission($this->logged_user()->level, 'dCliente')) {
$this->response([
'status' => false,
'message' => 'Você não está autorizado a Apagar Clientes!'
], REST_Controller::HTTP_UNAUTHORIZED);
}

if(!$id) {
$this->response([
'status' => false,
'message' => 'Informe o ID do cliente!'
], REST_Controller::HTTP_BAD_REQUEST);
}

$os = $this->clientes_model->getAllOsByClient($id);
if ($os != null) {
$this->clientes_model->removeClientOs($os);
}

$vendas = $this->clientes_model->getAllVendasByClient($id);
if ($vendas != null) {
$this->clientes_model->removeClientVendas($vendas);
}

if ($this->clientes_model->delete('clientes', 'idClientes', $id) == true) {
$this->log_app('Removeu um cliente. ID' . $id);
$this->response([
'status' => true,
'message' => 'Cliente excluído com sucesso!'
], REST_Controller::HTTP_OK);
}

$this->response([
'status' => false,
'message' => 'Não foi possível excluir o Cliente.'
], REST_Controller::HTTP_INTERNAL_ERROR);
}
}
Loading

0 comments on commit 3c8e6fc

Please sign in to comment.