-
-
Notifications
You must be signed in to change notification settings - Fork 624
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adicionando api JWT no Mapos #2366
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -465,7 +465,8 @@ | |
"email.*+", | ||
"permissoes.*+", | ||
"auditoria.*+", | ||
"tools.*+" | ||
"tools.*+", | ||
"api.*+" | ||
]; | ||
|
||
/* | ||
|
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; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sugiro deixar esse tempo de expiração configurável via processo de instalação. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Dúvida: Não daria pra criar outro arquivo api.php e fazer o include? Acho que ficaria mais organizado. |
||
|
||
/* End of file routes.php */ | ||
/* Location: ./application/config/routes.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'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sugestão: Acho melhor tentar colocar o REST_Controller no autoload do composer, pra não ter que colocar o require em todos os arquivos. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Não pensei em colocar pq só será usado na API, e quem não for usar a api não precisa carregar o RET_Controller. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. O custo de carregar no autoload é minimo e o benefício compensa. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ok |
||
|
||
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; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sugestão: Alterar todos os result que usam stdClass pra usar array |
||
|
||
$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); | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sugestão: Ajustar a indentação. |
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); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Deixar essa chave fixa é uma grande vulnerabilidade, vai ser necessário gerar ela dinamicamente.
Sugiro gerar-la durante o processo de instalação.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pensei nisso também, vou dar uma "estudada" em como colocar pra gerar na instalação do MapOS