Skip to content

Commit

Permalink
📝 #129 criando app 3.0
Browse files Browse the repository at this point in the history
  • Loading branch information
bjverde committed Mar 7, 2020
1 parent 6e801ee commit 003231c
Show file tree
Hide file tree
Showing 175 changed files with 12,535 additions and 0 deletions.
39 changes: 39 additions & 0 deletions appexemplo_v3.0/ajuda/ajuda_tela.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
require_once("../includes/constantes.php");
$msgSysNameVersion = SYSTEM_NAME.' - v'.SYSTEM_VERSION;
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Ajuda - <?php echo $msgSysNameVersion; ?></title>
</head>
<body>
<h2>Ajuda - <?php echo $msgSysNameVersion; ?></h2>
<h3>Tela padrão</h3>
<br>
<br>
<br><h4>Descrição da tela</h4>
<ul>
<li>Campos</li>
<li>Botões de ação</li>
<li>Lista de registro com ações por registro</li>
</ul>
<br>
<br><h4>Detalhe das ações</h4>
<ul>
<li>Buscar - informe um valor em um ou mais campos, que serão utilizados como critérios de busca. Na lista de registro aparecerá apenas os registros que respeitam a busca. Se informar mais de um campo eles serão usados com E. Logo a Pesquisa será "Quero todos os registro com o <b>campo a E o campo B</b></li>
<li>Salvar - informe todos os campos e poderá gravar um novo registro. Se clicar no botão altera da lista de registro os valores serão enviados para os campos. Depois poderá alterar esse registro</li>
<li>Limpar - limpa os valores que estão nos campos</li>
</ul>
<br>
<br><h4>Ações da listra de registro</h4>
<ul>
<li>Alterar - Carrega todos os valores do registro para os campos. Possibilitando a sua alteração</li>
<li>Excluir - Exclui o registro selecionado</li>
<li>Exportar - Exporta os registro na tela para o formato XLS</li>
<li>Ordenar - Poder ordenar por qualquer coluna, porém apenas entre os registros aparecem na tela</li>
</ul>
</body>
</html>
22 changes: 22 additions & 0 deletions appexemplo_v3.0/ajuda/changelog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php
require_once("../includes/constantes.php");
$msgSysNameVersion = SYSTEM_NAME.' - v'.SYSTEM_VERSION;
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Changelog - <?php echo $msgSysNameVersion; ?></title>
</head>
<body>
<h2><?php echo $msgSysNameVersion; ?></h2>
<ul>
<li>versão 0.0.0
<ul>
<li>Primeira versão</li>
</ul>
</li>
</ul>
</body>
</html>
2 changes: 2 additions & 0 deletions appexemplo_v3.0/ajuda/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<?php
header('Location: ../index.php');
23 changes: 23 additions & 0 deletions appexemplo_v3.0/ajuda/info_start_pt-br.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>ATENÇÃO SIGA AS INFORMAÇÕES ABAIXO</h1>
<br>
<br>Bem vindo ao <?php echo SYSTEM_NAME ?>
<br>
<br><b>Esse sistema só irá funcionar depois de criar o banco de exemplo com MySQl.</b>
<br>
<br>Execute os scripts abaixo e na ordem via MySql WorkBench ou phpMyAdmin
<ol>
<li><a href="https://github.com/bjverde/formDin/blob/master/modelo_banco_exemplos/01_script_criacao_banco.sql">modelo_banco_exemplos/01_script_criacao_banco.sql</a></li>
<li><a href="https://github.com/bjverde/formDin/blob/master/modelo_banco_exemplos/02_script_inclusao_dados.sql">modelo_banco_exemplos/02_script_inclusao_dados.sql</a></li>
<li><a href="https://github.com/bjverde/formDin/blob/master/modelo_banco_exemplos/03_script_usuario_banco.sql">modelo_banco_exemplos/03_script_usuario_banco.sql</a></li>
<li>Se o servidor MySql não for Localhost, altere o arquivo includes/config_conexao.php linha 14 para o seu servidor.</li>
</ol>
<br>
<br>
</body>
</html>
11 changes: 11 additions & 0 deletions appexemplo_v3.0/ajuda/senha.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

function gerar($user){
echo "<br><b>".$user.':</b> ';
echo password_hash($user, PASSWORD_DEFAULT);
}

gerar('root');
gerar('admin');
gerar('user');
gerar('trainee');
21 changes: 21 additions & 0 deletions appexemplo_v3.0/api/.htaccess
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<IfModule mod_rewrite.c>
RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the index.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

# If the above doesn't work you might need to set the `RewriteBase` directive manually, it should be the
# absolute physical path to the directory that contains this htaccess file.
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
20 changes: 20 additions & 0 deletions appexemplo_v3.0/api/Middlewares/JwtDateTimeMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Middlewares;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

final class JwtDateTimeMiddleware
{
public function __invoke(Request $request, Response $response, callable $next): Response
{
$token = $request->getAttribute('jwt');
$expireDate = new \DateTime($token['expired_at']);
$now = new \DateTime();
if($expireDate < $now)
return $response->withStatus(401);
$response = $next($request, $response);
return $response;
}
}
12 changes: 12 additions & 0 deletions appexemplo_v3.0/api/Middlewares/basicAuth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

use Tuupola\Middleware\HttpBasicAuthentication;

function basicAuth(): HttpBasicAuthentication
{
return new HttpBasicAuthentication([
"users" => [
"root" => "teste123"
]
]);
}
11 changes: 11 additions & 0 deletions appexemplo_v3.0/api/Middlewares/jwtAuth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

use Tuupola\Middleware\JwtAuthentication;

function jwtAuth(): JwtAuthentication
{
return new JwtAuthentication([
'secret' => getenv('JWT_SECRET_KEY'),
'attribute' => 'jwt'
]);
}
136 changes: 136 additions & 0 deletions appexemplo_v3.0/api/api_controllers/AcessoAPI.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php
/**
* System generated by SysGen (System Generator with Formdin Framework)
* Download SysGen: https://github.com/bjverde/sysgen
* Download Formdin Framework: https://github.com/bjverde/formDin
*
* SysGen Version: 1.9.0-alpha
* FormDin Version: 4.7.5
*
* System appev2 created in: 2019-09-10 09:04:46
*/

namespace api_controllers;

use DateTime;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Firebase\JWT\JWT;

class AcessoAPI
{

public function __construct()
{
}


//--------------------------------------------------------------------------------
private static function getParam(string $paramName, $bodyRequest, $required = true)
{
$paramValue = null;
$paramValue = \ArrayHelper::get($bodyRequest,$paramName);
if($required && empty($paramValue) ){
throw new \InvalidArgumentException('Parametro '.$paramName.' não informado');
}
return $paramValue;
}

//--------------------------------------------------------------------------------
private static function genToken(string $login_user,$expireDate=null)
{
$controller = new \Acesso_user();
$user = $controller->selectByLogin($login_user);

//Criado só para fins didaticos, no mundo real a data que expirada deve ser gerada
if( empty($expireDate) ){
$expireDate = (new DateTime())->modify('+1 days')->format('Y-m-d H:i:s');
}

$tokenPayload = [
'sub' => $user['IDUSER'][0],
'name' => $user['LOGIN_USER'][0],
'expired_at' => $expireDate
];

$token = JWT::encode($tokenPayload, getenv('JWT_SECRET_KEY'));

$refreshTokenPayload = [
'name' => $user['LOGIN_USER'][0],
'ramdom' => uniqid()
];
$refreshToken = JWT::encode($refreshTokenPayload, getenv('JWT_SECRET_KEY'));

$vo = new \Acesso_tokensVO();
$vo->setIduser($user['IDUSER'][0]);
$vo->setToken($token);
$vo->setRefresh_token($refreshToken);
$vo->setExpired_at($expireDate);
$vo->setActive('Y');
$controller = new \Acesso_tokens;
$controller->save($vo);

$result = array();
$result['token']=$token;
$result['refreshToken']=$refreshToken;

return $result;
}
//--------------------------------------------------------------------------------
public static function test(Request $request, Response $response, array $args)
{
$response = $response->withJson('OK!');
return $response;
}
//--------------------------------------------------------------------------------
public static function login(Request $request, Response $response, array $args)
{
$bodyRequest = json_decode($request->getBody(),true);

$login_user = self::getParam('login_user',$bodyRequest);
$pwd_user = self::getParam('pwd_user',$bodyRequest);
$expired_at = self::getParam('expired_at',$bodyRequest,false);

$controller = new \Acesso;
$msg = $controller->login($login_user,$pwd_user);
$response = $response->withJson($msg);
if($msg == true){
$token = self::genToken($login_user,$expired_at);
$response = $response->withJson([
"token" => $token['token'],
"refresh_token" => $token['refreshToken']
]);
}else{
$response = $response->withJson($msg,401); //401 Unauthorized https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status/401
}
return $response;
}

//--------------------------------------------------------------------------------
public function refreshToken(Request $request, Response $response, array $args): Response
{
$data = $request->getParsedBody();
$refreshToken = self::getParam('refresh_token',$data);
$expireDate = self::getParam('expired_at',$data);

$refreshTokenDecoded = JWT::decode(
$refreshToken,
getenv('JWT_SECRET_KEY'),
['HS256']
);

$controller = new \Acesso_tokens;
$refreshTokenExists = $controller->verifyRefreshTokenAndDelete($refreshToken);
if(!$refreshTokenExists){
return $response->withStatus(401);
}

$token = self::genToken($refreshTokenDecoded->name,$expireDate);
$response = $response->withJson([
"token" => $token['token'],
"refresh_token" => $token['refreshToken']
]);

return $response;
}
}
Loading

0 comments on commit 003231c

Please sign in to comment.