This commit is contained in:
kleper 2018-12-16 09:14:19 -05:00
commit 800f45060d
48 changed files with 7101 additions and 1168 deletions

44
api.php
View File

@ -1,23 +1,49 @@
<?php
session_start();
//ini_set('display_errors', 'On');
ini_set('display_errors', 'On');
require ('xajax/xajax.inc.php');
$xajax = new xajax();
include ('librerias/parsedown/Parsedown.php');
require ('funciones/funciones.php');
require ('funciones/convert.php');
require ("includes/markdown.php");
//require ("includes/markdown.php");
require ("funciones/conex.php");
$datos['id']=$_REQUEST['id'];
$datos['identificador']=$_REQUEST['identificador'];
$datos['dato']=$_REQUEST['dato'];
$datos['inicio']=$_REQUEST['inicio'];
$datos['fin']=$_REQUEST['fin'];
$datos['tipo']=$_REQUEST['tipo'];
@$datos['id']=$_REQUEST['id'];
@$datos['identificador']=$_REQUEST['identificador'];
@$datos['dato']=$_REQUEST['dato'];
@$datos['inicio']=$_REQUEST['inicio'];
@$datos['fin']=$_REQUEST['fin'];
@$datos['tipo']=$_REQUEST['tipo'];
@$datos['registros']=$_REQUEST['registros'];
@$datos['pagina']=$_REQUEST['pagina'];
@$datos['proyecto']=$_REQUEST['proyecto'];
if($datos['proyecto']==""){
$proyecto= remplacetas('form_id','id',$datos['id'],'id_empresa',"") ;
$datos['proyecto']= $proyecto[0] ;
}
@$datos['formato']=$_REQUEST['formato'];
if(isset($_REQUEST['debug'])) {ini_set('display_errors', 'On');
}
if(isset($_REQUEST['formato'])){
// if($_REQUEST['formato']=='li'){
//$array = aplicaciones_listado($datos['id'],'','array','');
//print_r($array);//echo "hola li";
$json= json($datos);
$array = json_decode($json);
echo array_linea($array,$_REQUEST['formato'],$_REQUEST['id'])." ";
//echo "".build_list($array,$_REQUEST['formato'],$_REQUEST['id']);
//echo $json;
//echo planilla($datos['id'],$datos['registros'],"dinamico");
// }
}else{
header('Content-Type: application/json');
//echo "hola /// $_REQUEST[id] // " ;
echo json($datos);
}
?>

View File

@ -2,8 +2,16 @@
el otro archivo css style.css que está en la carpeta milfs
no está referenciado en index.php de milfs*/
#barra_milfs{
position: absolute;
}
#contenedor_principal{
padding-top: 100px;
padding-top: 10em;
}
#empresa_pie{
display: block;
}
@media (max-width: 768px) {

View File

@ -15,9 +15,12 @@ h1, h2, h3, h4, h5, h6 {
line-height: 1.1;
}
/* #principal_general{
position: absolute;
} */
#toc {
font-size: 1em;
padding-top: 50px;
max-height: 95% !important;
overflow: auto !important;
}
@ -26,6 +29,30 @@ h1, h2, h3, h4, h5, h6 {
opacity: 1;
}
#navbar-principal{
border-color: transparent;
}
#asistento{
padding-top: 5em;
}
#lo_ultimo{
padding-bottom: 3em;
}
.lo_ultimo>img{
max-height: 300px;'
}
.titulo_seccion{
padding-top: 3em;
padding-bottom: 1em;
font-family: "Helvetica", times, sans-serif !important;
font-weight: 500 !important;
line-height: 1.1 !important;
font-size: 36px;
}
.navbar-inverse {
background-color: #222;
border-color: #090909;
@ -43,8 +70,13 @@ h1, h2, h3, h4, h5, h6 {
border-color: transparent;
}
#cabecera{
padding-top: 20em;
}
#contenedor_cabecera {
padding-top: 0em;
padding-right: 3em;
}
#logo_cabecera {
@ -69,8 +101,16 @@ h1, h2, h3, h4, h5, h6 {
overflow: auto;
}
#div_panel_aplicaciones {
padding-top: 21em;
#menu_administrador{
background-color: white;
}
.dropdown-menu>li>a:hover{
background-color: #e95420!important;
color: white;
}
.intro-social-buttons {
padding-top: 10px !important;
}
/*NAVBAR BRAND*/
@ -84,7 +124,7 @@ h1, h2, h3, h4, h5, h6 {
#menu_hamburguesa{
color: white;
background-color: none !important;
background-color: transparent !important;
}
.navbar-brand {
transform: translateX(-50%);
@ -144,33 +184,6 @@ h1, h2, h3, h4, h5, h6 {
padding: 4px 5px;
}
.btn-botonera-admin {
margin-left: 20px;
margin-right: 20px;
}
#botonera-admin, #botonera-admin>a {
color: white !important;
}
.btn-botonera-admin {
/* margin-left: 20px; */
/* margin-right: 20px; */
float: left;
}
.btn-botonera-admin:hover {
background-color: black;
}
.btn.btn-botonera-admin:hover {
color: white !important;
}
.intro-social-buttons {
padding-top: 10px !important;
}
#botonera_landing {
display: inline-flex;
}
@ -184,8 +197,6 @@ h1, h2, h3, h4, h5, h6 {
padding-left: 80px !important;
}
#encabezado_proyecto {
padding-top: 30px;
}
@ -200,6 +211,7 @@ h1, h2, h3, h4, h5, h6 {
#proyectos {
background-color: #d4d4d4;
padding-top: 4em;
}
.div_proyecto {
@ -252,8 +264,6 @@ h1, h2, h3, h4, h5, h6 {
height: 100% !important;
overflow-y: auto;
overflow-x: hidden;
padding: 0px 0px 70px 0px;
;
border: none;
}
@ -261,7 +271,7 @@ h1, h2, h3, h4, h5, h6 {
/* box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);*/
border-radius: 0px !important;
padding: 50px;
padding: 3em;
border-bottom: 1px solid lightgrey;
}
@ -366,7 +376,7 @@ span.etiquetatam10 {
margin-top: -13px;
}
.navbar-principal>li>a, {
.navbar-principal>li>a {
padding-top: 0px !important;
padding-bottom: 0 !important;
height: 30px;
@ -411,7 +421,8 @@ box-shadow: none;
}
}
< !-- ESTILOS PRIORITARIOS -->.modal-dialog {
/*ESTILOS PRIORITARIOS*/
.modal-dialog {
width: 95% !important;
height: auto;
padding: 0;
@ -458,8 +469,7 @@ legend.legend-area {
}
.fh5co-post-entry article h2 {
font-size: 28px;
!important;
font-size: 28px ;
}
#fh5co-offcanvas .fh5co-bio img {
@ -489,25 +499,41 @@ RESPONSIVE */
/*Se afectan todos hacia arriba*/
@media (min-width: 767px) {
@media (min-width: 769px) {
#cabecera {
margin-left: 20px;
margin-right: 20px;
}
}
@media only screen and (max-width: 1440px) {
.titulo_seccion{
padding-top: 1em;
}
#asistento{
padding-top: 1em;
}
}
@media only screen and (max-width: 1200px) {
#logo_cabecera {
padding-top: 3em;
#contenedor_cabecera{
padding-right: 5em;
}
#cabecera{
padding-top: 20em;
}
#div_panel_aplicaciones{
padding-top: 23em;
#logo_cabecera {
padding-top: 2em;
max-width: 70% !important;
}
.img-gris {
filter: grayscale(0);
}
.lead{
padding-left: 5em;
padding-right: 5em;
}
}
@media only screen and (max-width: 992px) {
@ -517,61 +543,160 @@ RESPONSIVE */
}
@media only screen and (max-width: 767px) {
@media only screen and (max-width: 769px) {
.navbar-inverse .navbar-nav>li>a:hover {
background: transparent;
}
.navbar-header {
margin: 0px !important;
float: left;
}
a.dropdown-toggle.img-rounded.visible-xs{
background-color: #08080800 !important;
}
#slogan_cabecera{
font-size: 1.5em;
}
#logo_cabecera {
padding-top: 0em;
padding-top: 2em;
}
#div_panel_aplicaciones {
padding-top: 21em;
#caja{
padding: 0px;
}
}
@media only screen and (max-width: 586px) {
#contenedor_cabecera {
padding-top: 0em;
#cabecera{
padding-top: 21em;
}
#div_panel_aplicaciones {
padding-top: 15em;
#lo_ultimo{
padding-left: 0px;
padding-right: 0px;
}
#contenedor_landingpage {
padding-left: 0px !important;
padding-right: 0px !important;
}
#logo_cabecera {
max-width: 65% !important;
}
#principal_general {
padding-left: 2em;
}
#texto_articulo{
padding: 0px !important
}
}
@media only screen and (max-width: 495px) {
#contenedor_cabecera {
padding-top: 0em;
#cabecera{
padding-top: 15em;
}
#principal_general{
margin-left: 2em;
margin-right: 2em;
}
#principal_general {
padding-left: 3em;
}
#proyectos{
display: grid !important;
}
.lead {
padding-left: 0px;
padding-right: 0px;
}
.articulo_cuadro{
padding-left: 0px;
padding-right: 0px;
}
div#contenedor_landingpage {
padding-left: 0px !important;
padding-right: 0px !important;
}
.box-secciones{
padding: 1em;
padding-bottom: 4em;
}
}
@media only screen and (max-width: 320px) {
@media only screen and (max-width: 375px) {
#cabecera{
padding-top: 15em;
}
#principal_general{
padding-left: 2em;
padding-right: 2em;
margin-left: 1em;
margin-right: 1em;
}
#caja{
padding-left: 0px;
padding-right: 0px;
margin-left: 0px;
margin-right: 0px;
}
#slogan_cabecera {
font-size: 1em;
}
#div_panel_aplicaciones {
padding-top: 10em;
.articulo_cuadro{
padding-left: 0px;
padding-right: 0px;
}
.btn-group-sm>.btn, .btn-sm {
padding: 5px 7px;
font-size: 11px;
line-height: 1.5;
border-radius: 3px;
}
}
@media only screen and (max-width: 361px) {
#principal_general{
margin-left: 0em;
margin-right: 0em;
}
}
@media only screen and (max-width: 320px) {
#principal_general{
padding-left: 1em;
padding-right: 0em;
}
}
/*-------------
Help-tip Style
---------------*/
/* CSS animation */
@-webkit-keyframes fadeIn {
0% {
opacity:0;
transform: scale(0.6);
}
100% {
opacity:100%;
transform: scale(1);
}
}
@keyframes fadeIn {
0% { opacity:0; }
100% { opacity:100%; }
}
.blink{
color: rgb (0, 137, 226);
animation: blink 1s infinite;
}

File diff suppressed because it is too large Load Diff

View File

@ -4,12 +4,13 @@ require ('xajax/xajax.inc.php');
$xajax = new xajax();
require ('funciones/funciones.php');
require ('funciones/convert.php');
include ('librerias/parsedown/Parsedown.php');
require ("funciones/conex.php");
$geojson = imprime_geojson("$_REQUEST[id]","","mapa","$_REQUEST[buscar]");
$geojson = imprime_geojson("$_REQUEST[id]","","mapa","$_REQUEST[buscar]","$_REQUEST[item]");
//header('Content-Type: application/json');
echo "var geojsonSample = ";
echo $geojson;

View File

@ -1,5 +1,7 @@
<?php
session_start();
<?php session_start();
$timestamp=time();
setcookie("timestamp",$timestamp,($timestamp + 5000));
$_SESSION['timestamp']= $timestamp;
if($_SESSION['grupo'] != "administrador") {
// header("Location: ../");
}
@ -7,6 +9,7 @@ session_start();
require ('xajax/xajax.inc.php');
$xajax = new xajax();
//$xajax = new xajax("https://tupale.co/milfs/index.php");
include ('librerias/parsedown/Parsedown.php');
require ('funciones/funciones.php');
//require ('funciones/convert.php');
require ('funciones/login.php');
@ -184,7 +187,7 @@ legend.legend-area {
</style>
</head>
<body >
<body onload="revisarSession()"; >
<?php if($embebido ==1) {
if($form!=''){ echo formulario_embebido($form,$opciones);}
elseif($identificador !='') { echo mostrar_identificador($identificador,$id);}
@ -197,19 +200,23 @@ else{}
<?php echo @$onload; ?>
<?php
if ( isset ( $_SESSION['id'] ) ) { ?>
<div class="navbar navbar-inverse navbar-fixed-top " role="navigation">
<div class="navbar navbar-inverse navbar-fixed-top " id="barra_milfs" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">MILFS</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><img src="favicon-152.png" style="width:60px" alt="MILFS" title="Multi Interactive Light Form System"></a>
</div>
<?php echo milfs() ?>
</div><!-- /.container-fluid -->
</div>
@ -220,12 +227,18 @@ else{}
<div id='debug'></div>
<div class='container' id='contenedor_principal'>
<div id='contenido'>
<div class='row'>
<div id='' class='col-sm-6'>
<?php if(isset($_SESSION['id'])){ echo "
<form id='manejo_sesion' name='form_session' class='navbar-form navbar-left'>
<div class='input-group'>
<input type='text' name='tiempo_session' size='18' class='form-control input-sm' readonly>
<span class='input-group-addon'><a href='#' onclick=\"location.reload();\" title='Renovar'><span class='glyphicon glyphicon-refresh' aria-hidden='true'></span></a></span>
</div>
</form> "; } ?>
<?php
///echo adjuntar_basico('33');
@ -236,7 +249,7 @@ else{}
echo "$encabezado";
//if(isset($_SESSION['id_empresa'])) {$id_empresa_portada='1'; echo panel_aplicaciones('1',"");}
echo " </div>
<div id='div_login' class='col-sm-6'>";
<div id='div_login' class='col-xs-12 col-sm-6'>";
if(isset($_REQUEST['change'])){
echo cambiar_password_formato("$_REQUEST[change]");
}
@ -305,5 +318,6 @@ $(document).ready(function() {
});
</script>
</body>
</html>

View File

@ -1,3 +1,15 @@
function delayTimer() {
var timer;
return function (fun, time) {
clearTimeout(timer);
timer = setTimeout(fun, time);
};
}
var delayFunction = delayTimer();
function revisarSession(){
tiempo = "30";
gavela="19";
@ -5,14 +17,14 @@
inicio = leerCookie("timestamp");
transcurrido = (timestamp - inicio);
transcurrido_minutos = Math.round(transcurrido/60);
restante = (tiempo - transcurrido_minutos)
prefin = (tiempo*60)-transcurrido
restante = (tiempo - transcurrido_minutos);
prefin = (tiempo*60)-transcurrido;
document.form_session.tiempo_session.value = "Cerrar en: "+restante+" minutos ";
document.form_session.tiempo_session.value = "Cierra en: "+restante+" minutos ";
if(restante == 1 ){
//alert(transcurrido);
location.href="./includes/salir.php";
location.href="./salir.php";
}else{
setTimeout("revisarSession()",2000) ;
}
@ -31,20 +43,35 @@ function leerCookie(nombre) {
}
function loadArticle(pageNumber,id,plantilla,registros,scroll) {
function loadArticle(pageNumber,id,plantilla,registros,scroll,formato) {
var newDiv = document.createElement('div');
var newDiv = document.createElement('tr');
document.getElementById(scroll).appendChild(newDiv);
$.ajax({
url: './milfs/api.php?id='+id+'&tipo=simple&formato=li&plantilla='+plantilla+'&registros='+registros+'&pagina=' + pageNumber,
url: './milfs/api.php?id='+id+'&tipo=simple&formato='+formato+'&plantilla='+plantilla+'&registros='+registros+'&pagina=' + pageNumber,
type: 'POST',
dataType: 'html',
success: function(html) {
// $('#scroll-contentx').append(html);
var contenido = html;
newDiv.innerHTML = contenido;
$('.lazy').lazy({
// your configuration goes here
//combined: true,
// delay: 1000,
// scrollDirection: 'vertical',
//effect: 'fadeIn',
//visibleOnly: true,
onError: function(element) {
console.log('error loading ' + element.data('src'));
}
});
}
});
@ -102,7 +129,7 @@ function loadArticle(pageNumber,id,plantilla,registros,scroll) {
function comprueba_imagen(campo,item, archivo,campo_mapa,ubicacion) {
var ubicacion;
extensiones_permitidas = new Array('.gif', '.jpg', '.png', '.mp4', '.3gp', '.mov');
extensiones_permitidas = new Array('.gif', '.jpg', '.png', '.mp4', '.3gp', '.mov', '.jpeg');
mierror = '';
if (!archivo) {
//Si no tengo archivo, es que no se ha seleccionado un archivo en el formulario
@ -595,6 +622,6 @@ else if (document.all) document.all[''+id+''].style.visibility = "hidden"
else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"
}
}
$(function () {
$('[data-toggle="tooltip"]').tooltip()
}) ;

File diff suppressed because it is too large Load Diff

View File

@ -39,6 +39,7 @@
var map = L.map('map')
.setView([<?php echo $lon ?>, <?php echo $lat ?>], <?php echo $zoom ?>);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
<?php
if(!isset($_REQUEST['exif'])) { ?>
@ -46,12 +47,20 @@ function onLocationFound(e) {
//var radius = e.accuracy / 2;
var marker = L.marker(e.latlng,{draggable: true}).addTo(map);
var mapa = window.parent.document.getElementById("<?php echo $_REQUEST[id] ?>");
mapa.value= '<?php echo "$lon $lat $zoom"; ?>';
marker.on('dragend', ondragend);
ondragend();
map.setZoom(<?php echo $zoom; ?>);
var m = marker.getLatLng();
mapa.value= m.lng+' '+m.lat+' <?php echo $zoom; ?>';
function ondragend() {
var m = marker.getLatLng();
var z = map.getZoom();
map.setZoom(z);
mapa.value= m.lng+' '+m.lat+' '+z;
}
@ -70,7 +79,7 @@ function ondragend() {
}
map.on('locationerror', onLocationError);
map.on('locationfound', onLocationFound);
map.locate({setView: true, maxZoom: 16});
map.locate({setView: true, maxZoom: 20});
<?php }else{ ?>
var marker = L.marker([<?php echo $lon ?>,<?php echo $lat ?>],{draggable: true}).addTo(map);

View File

@ -1,5 +1,7 @@
{
"require": {
"slim/slim": "^3.0"
"slim/slim": "^3.0",
"tuupola/slim-jwt-auth": "^2.4",
"firebase/php-jwt": "^5.0"
}
}

152
rest/composer.lock generated
View File

@ -4,8 +4,8 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "6f5d3d05d70b58db9144bb1ca70c8698",
"content-hash": "3b0766dbcef4dfb1a4a2012fef8611d8",
"hash": "db06d159aa973eb83cbd8c8a94dff140",
"content-hash": "9aebed89c362ee9703dec74f7f636758",
"packages": [
{
"name": "container-interop/container-interop",
@ -38,6 +38,52 @@
"homepage": "https://github.com/container-interop/container-interop",
"time": "2017-02-14 19:40:03"
},
{
"name": "firebase/php-jwt",
"version": "v5.0.0",
"source": {
"type": "git",
"url": "https://github.com/firebase/php-jwt.git",
"reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/firebase/php-jwt/zipball/9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
"reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": " 4.8.35"
},
"type": "library",
"autoload": {
"psr-4": {
"Firebase\\JWT\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Neuman Vong",
"email": "neuman+pear@twilio.com",
"role": "Developer"
},
{
"name": "Anant Narayanan",
"email": "anant@php.net",
"role": "Developer"
}
],
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/firebase/php-jwt",
"time": "2017-06-27 22:17:23"
},
{
"name": "nikic/fast-route",
"version": "v1.3.0",
@ -233,6 +279,53 @@
],
"time": "2016-08-06 14:39:51"
},
{
"name": "psr/log",
"version": "1.0.2",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
"reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
"reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Log\\": "Psr/Log/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"homepage": "https://github.com/php-fig/log",
"keywords": [
"log",
"psr",
"psr-3"
],
"time": "2016-10-10 12:19:37"
},
{
"name": "slim/slim",
"version": "3.11.0",
@ -303,6 +396,61 @@
"router"
],
"time": "2018-09-16 10:54:21"
},
{
"name": "tuupola/slim-jwt-auth",
"version": "2.4.0",
"source": {
"type": "git",
"url": "https://github.com/tuupola/slim-jwt-auth.git",
"reference": "bca54de41a8207d4d67faf3601a06a96cb7ed48f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tuupola/slim-jwt-auth/zipball/bca54de41a8207d4d67faf3601a06a96cb7ed48f",
"reference": "bca54de41a8207d4d67faf3601a06a96cb7ed48f",
"shasum": ""
},
"require": {
"firebase/php-jwt": "^3.0 || ^4.0 || ^5.0",
"php": "^5.5 || ^7.0",
"psr/http-message": "^1.0",
"psr/log": "^1.0"
},
"require-dev": {
"overtrue/phplint": "^0.2.4",
"phpunit/phpunit": "^4.6",
"squizlabs/php_codesniffer": "^2.3",
"zendframework/zend-diactoros": "^1.3"
},
"type": "library",
"autoload": {
"psr-4": {
"Slim\\Middleware\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mika Tuupola",
"email": "tuupola@appelsiini.net",
"homepage": "http://www.appelsiini.net/",
"role": "Developer"
}
],
"description": "PSR-7 JWT Authentication Middleware",
"homepage": "https://github.com/tuupola/slim-jwt-auth",
"keywords": [
"auth",
"json",
"jwt",
"middleware",
"psr-7"
],
"time": "2018-04-03 06:12:18"
}
],
"packages-dev": [],

1
rest/index.php Normal file
View File

@ -0,0 +1 @@

View File

@ -1,3 +1,5 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

1
rest/src/index.php Normal file
View File

@ -0,0 +1 @@

View File

@ -6,34 +6,48 @@ $app =new \Slim\app;
/// listado de todos los proyectos
$app ->get('/api/proyectos/', function(Request $request, Response $response){
$app ->get('/api/proyectos', function(Request $request, Response $response){
$array = aplicaciones_listado("",'','array','');
echo json_encode($array);
echo json_encode($array,JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT);
});
/// aplicaciones por proyecto
$app ->get('/api/proyectos/{id}', function(Request $request, Response $response){
$id= $request->getAttribute('id');
$array = aplicaciones_listado("$id",'','array','');
echo json_encode($array);
$array = empresa_datos("$id",'array');
echo json_encode($array,JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT);
});
// entradas a aplicacion por id
$app ->get('/api/proyectos/aplicaciones/{id}', function(Request $request, Response $response){
$datos= array();
$datos['id']= $request->getAttribute('id');
$datos['tipo']='simple';
$app ->get('/api/proyectos/{id}/aplicaciones', function(Request $request, Response $response){
$id= $request->getAttribute('id');
$array = aplicaciones_listado("$id",'','array','');
echo json_encode($array,JSON_NUMERIC_CHECK|JSON_PRETTY_PRINT);
});
// entradas a aplicacion por id
$app ->get('/api/proyectos/{id}/aplicaciones/{aplicacion}', function(Request $request, Response $response){
$datos= array();
$datos['id']= $request->getAttribute('aplicacion');
$datos['proyecto']= $request->getAttribute('id');
$datos['tipo']='simple';
//print_r($datos);
echo json($datos);
});
// entradas a aplicacion por identificador
$app ->get('/api/proyectos/aplicaciones/{id}/{identificador}', function(Request $request, Response $response){
$app ->get('/api/proyectos/{id}/aplicaciones/{aplicacion}/{identificador}', function(Request $request, Response $response){
$datos= array();
//$datos['id']= $request->getAttribute('id');
$datos['id']= $request->getAttribute('aplicacion');
$datos['proyecto']= $request->getAttribute('id');
$datos['identificador']= $request->getAttribute('identificador');
$datos['tipo']='simple';

View File

@ -6,9 +6,12 @@ $vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Slim\\Middleware\\' => array($vendorDir . '/tuupola/slim-jwt-auth/src'),
'Slim\\' => array($vendorDir . '/slim/slim/Slim'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'Interop\\Container\\' => array($vendorDir . '/container-interop/container-interop/src/Interop/Container'),
'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'),
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
);

View File

@ -13,10 +13,12 @@ class ComposerStaticInitf276a0def1050763d961e731ed5733c4
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Slim\\Middleware\\' => 16,
'Slim\\' => 5,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
'Psr\\Container\\' => 14,
),
@ -26,15 +28,24 @@ class ComposerStaticInitf276a0def1050763d961e731ed5733c4
),
'F' =>
array (
'Firebase\\JWT\\' => 13,
'FastRoute\\' => 10,
),
);
public static $prefixDirsPsr4 = array (
'Slim\\Middleware\\' =>
array (
0 => __DIR__ . '/..' . '/tuupola/slim-jwt-auth/src',
),
'Slim\\' =>
array (
0 => __DIR__ . '/..' . '/slim/slim/Slim',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-message/src',
@ -47,6 +58,10 @@ class ComposerStaticInitf276a0def1050763d961e731ed5733c4
array (
0 => __DIR__ . '/..' . '/container-interop/container-interop/src/Interop/Container',
),
'Firebase\\JWT\\' =>
array (
0 => __DIR__ . '/..' . '/firebase/php-jwt/src',
),
'FastRoute\\' =>
array (
0 => __DIR__ . '/..' . '/nikic/fast-route/src',

View File

@ -307,5 +307,159 @@
"micro",
"router"
]
},
{
"name": "firebase/php-jwt",
"version": "v5.0.0",
"version_normalized": "5.0.0.0",
"source": {
"type": "git",
"url": "https://github.com/firebase/php-jwt.git",
"reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/firebase/php-jwt/zipball/9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
"reference": "9984a4d3a32ae7673d6971ea00bae9d0a1abba0e",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"require-dev": {
"phpunit/phpunit": " 4.8.35"
},
"time": "2017-06-27 22:17:23",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Firebase\\JWT\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Neuman Vong",
"email": "neuman+pear@twilio.com",
"role": "Developer"
},
{
"name": "Anant Narayanan",
"email": "anant@php.net",
"role": "Developer"
}
],
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/firebase/php-jwt"
},
{
"name": "psr/log",
"version": "1.0.2",
"version_normalized": "1.0.2.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
"reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
"reference": "4ebe3a8bf773a19edfe0a84b6585ba3d401b724d",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2016-10-10 12:19:37",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Log\\": "Psr/Log/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"homepage": "https://github.com/php-fig/log",
"keywords": [
"log",
"psr",
"psr-3"
]
},
{
"name": "tuupola/slim-jwt-auth",
"version": "2.4.0",
"version_normalized": "2.4.0.0",
"source": {
"type": "git",
"url": "https://github.com/tuupola/slim-jwt-auth.git",
"reference": "bca54de41a8207d4d67faf3601a06a96cb7ed48f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/tuupola/slim-jwt-auth/zipball/bca54de41a8207d4d67faf3601a06a96cb7ed48f",
"reference": "bca54de41a8207d4d67faf3601a06a96cb7ed48f",
"shasum": ""
},
"require": {
"firebase/php-jwt": "^3.0 || ^4.0 || ^5.0",
"php": "^5.5 || ^7.0",
"psr/http-message": "^1.0",
"psr/log": "^1.0"
},
"require-dev": {
"overtrue/phplint": "^0.2.4",
"phpunit/phpunit": "^4.6",
"squizlabs/php_codesniffer": "^2.3",
"zendframework/zend-diactoros": "^1.3"
},
"time": "2018-04-03 06:12:18",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Slim\\Middleware\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mika Tuupola",
"email": "tuupola@appelsiini.net",
"homepage": "http://www.appelsiini.net/",
"role": "Developer"
}
],
"description": "PSR-7 JWT Authentication Middleware",
"homepage": "https://github.com/tuupola/slim-jwt-auth",
"keywords": [
"auth",
"json",
"jwt",
"middleware",
"psr-7"
]
}
]

30
rest/vendor/firebase/php-jwt/LICENSE vendored Normal file
View File

@ -0,0 +1,30 @@
Copyright (c) 2011, Neuman Vong
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Neuman Vong nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

200
rest/vendor/firebase/php-jwt/README.md vendored Normal file
View File

@ -0,0 +1,200 @@
[![Build Status](https://travis-ci.org/firebase/php-jwt.png?branch=master)](https://travis-ci.org/firebase/php-jwt)
[![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt)
[![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt)
[![License](https://poser.pugx.org/firebase/php-jwt/license)](https://packagist.org/packages/firebase/php-jwt)
PHP-JWT
=======
A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://tools.ietf.org/html/rfc7519).
Installation
------------
Use composer to manage your dependencies and download PHP-JWT:
```bash
composer require firebase/php-jwt
```
Example
-------
```php
<?php
use \Firebase\JWT\JWT;
$key = "example_key";
$token = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1356999524,
"nbf" => 1357000000
);
/**
* IMPORTANT:
* You must specify supported algorithms for your application. See
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*/
$jwt = JWT::encode($token, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));
print_r($decoded);
/*
NOTE: This will now be an object instead of an associative array. To get
an associative array, you will need to cast it as such:
*/
$decoded_array = (array) $decoded;
/**
* You can add a leeway to account for when there is a clock skew times between
* the signing and verifying servers. It is recommended that this leeway should
* not be bigger than a few minutes.
*
* Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
*/
JWT::$leeway = 60; // $leeway in seconds
$decoded = JWT::decode($jwt, $key, array('HS256'));
?>
```
Example with RS256 (openssl)
----------------------------
```php
<?php
use \Firebase\JWT\JWT;
$privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC8kGa1pSjbSYZVebtTRBLxBz5H4i2p/llLCrEeQhta5kaQu/Rn
vuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t0tyazyZ8JXw+KgXTxldMPEL9
5+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4ehde/zUxo6UvS7UrBQIDAQAB
AoGAb/MXV46XxCFRxNuB8LyAtmLDgi/xRnTAlMHjSACddwkyKem8//8eZtw9fzxz
bWZ/1/doQOuHBGYZU8aDzzj59FZ78dyzNFoF91hbvZKkg+6wGyd/LrGVEB+Xre0J
Nil0GReM2AHDNZUYRv+HYJPIOrB0CRczLQsgFJ8K6aAD6F0CQQDzbpjYdx10qgK1
cP59UHiHjPZYC0loEsk7s+hUmT3QHerAQJMZWC11Qrn2N+ybwwNblDKv+s5qgMQ5
5tNoQ9IfAkEAxkyffU6ythpg/H0Ixe1I2rd0GbF05biIzO/i77Det3n4YsJVlDck
ZkcvY3SK2iRIL4c9yY6hlIhs+K9wXTtGWwJBAO9Dskl48mO7woPR9uD22jDpNSwe
k90OMepTjzSvlhjbfuPN1IdhqvSJTDychRwn1kIJ7LQZgQ8fVz9OCFZ/6qMCQGOb
qaGwHmUK6xzpUbbacnYrIM6nLSkXgOAwv7XXCojvY614ILTK3iXiLBOxPu5Eu13k
eUz9sHyD6vkgZzjtxXECQAkp4Xerf5TGfQXGXhxIX52yH+N2LtujCdkQZjXAsGdm
B2zNzvrlgRmgBrklMTrMYgm1NPcW+bRLGcwgW2PTvNM=
-----END RSA PRIVATE KEY-----
EOD;
$publicKey = <<<EOD
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8kGa1pSjbSYZVebtTRBLxBz5H
4i2p/llLCrEeQhta5kaQu/RnvuER4W8oDH3+3iuIYW4VQAzyqFpwuzjkDI+17t5t
0tyazyZ8JXw+KgXTxldMPEL95+qVhgXvwtihXC1c5oGbRlEDvDF6Sa53rcFVsYJ4
ehde/zUxo6UvS7UrBQIDAQAB
-----END PUBLIC KEY-----
EOD;
$token = array(
"iss" => "example.org",
"aud" => "example.com",
"iat" => 1356999524,
"nbf" => 1357000000
);
$jwt = JWT::encode($token, $privateKey, 'RS256');
echo "Encode:\n" . print_r($jwt, true) . "\n";
$decoded = JWT::decode($jwt, $publicKey, array('RS256'));
/*
NOTE: This will now be an object instead of an associative array. To get
an associative array, you will need to cast it as such:
*/
$decoded_array = (array) $decoded;
echo "Decode:\n" . print_r($decoded_array, true) . "\n";
?>
```
Changelog
---------
#### 5.0.0 / 2017-06-26
- Support RS384 and RS512.
See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)!
- Add an example for RS256 openssl.
See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)!
- Detect invalid Base64 encoding in signature.
See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)!
- Update `JWT::verify` to handle OpenSSL errors.
See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)!
- Add `array` type hinting to `decode` method
See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)!
- Add all JSON error types.
See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)!
- Bugfix 'kid' not in given key list.
See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)!
- Miscellaneous cleanup, documentation and test fixes.
See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115),
[#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and
[#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman),
[@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)!
#### 4.0.0 / 2016-07-17
- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)!
- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)!
- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)!
- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)!
#### 3.0.0 / 2015-07-22
- Minimum PHP version updated from `5.2.0` to `5.3.0`.
- Add `\Firebase\JWT` namespace. See
[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to
[@Dashron](https://github.com/Dashron)!
- Require a non-empty key to decode and verify a JWT. See
[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to
[@sjones608](https://github.com/sjones608)!
- Cleaner documentation blocks in the code. See
[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to
[@johanderuijter](https://github.com/johanderuijter)!
#### 2.2.0 / 2015-06-22
- Add support for adding custom, optional JWT headers to `JWT::encode()`. See
[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to
[@mcocaro](https://github.com/mcocaro)!
#### 2.1.0 / 2015-05-20
- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew
between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)!
- Add support for passing an object implementing the `ArrayAccess` interface for
`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)!
#### 2.0.0 / 2015-04-01
- **Note**: It is strongly recommended that you update to > v2.0.0 to address
known security vulnerabilities in prior versions when both symmetric and
asymmetric keys are used together.
- Update signature for `JWT::decode(...)` to require an array of supported
algorithms to use when verifying token signatures.
Tests
-----
Run the tests using phpunit:
```bash
$ pear install PHPUnit
$ phpunit --configuration phpunit.xml.dist
PHPUnit 3.7.10 by Sebastian Bergmann.
.....
Time: 0 seconds, Memory: 2.50Mb
OK (5 tests, 5 assertions)
```
New Lines in private keys
-----
If your private key contains `\n` characters, be sure to wrap it in double quotes `""`
and not single quotes `''` in order to properly interpret the escaped characters.
License
-------
[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause).

View File

@ -0,0 +1,29 @@
{
"name": "firebase/php-jwt",
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/firebase/php-jwt",
"authors": [
{
"name": "Neuman Vong",
"email": "neuman+pear@twilio.com",
"role": "Developer"
},
{
"name": "Anant Narayanan",
"email": "anant@php.net",
"role": "Developer"
}
],
"license": "BSD-3-Clause",
"require": {
"php": ">=5.3.0"
},
"autoload": {
"psr-4": {
"Firebase\\JWT\\": "src"
}
},
"require-dev": {
"phpunit/phpunit": " 4.8.35"
}
}

View File

@ -0,0 +1,7 @@
<?php
namespace Firebase\JWT;
class BeforeValidException extends \UnexpectedValueException
{
}

View File

@ -0,0 +1,7 @@
<?php
namespace Firebase\JWT;
class ExpiredException extends \UnexpectedValueException
{
}

379
rest/vendor/firebase/php-jwt/src/JWT.php vendored Normal file
View File

@ -0,0 +1,379 @@
<?php
namespace Firebase\JWT;
use \DomainException;
use \InvalidArgumentException;
use \UnexpectedValueException;
use \DateTime;
/**
* JSON Web Token implementation, based on this spec:
* https://tools.ietf.org/html/rfc7519
*
* PHP version 5
*
* @category Authentication
* @package Authentication_JWT
* @author Neuman Vong <neuman@twilio.com>
* @author Anant Narayanan <anant@php.net>
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
* @link https://github.com/firebase/php-jwt
*/
class JWT
{
/**
* When checking nbf, iat or expiration times,
* we want to provide some extra leeway time to
* account for clock skew.
*/
public static $leeway = 0;
/**
* Allow the current timestamp to be specified.
* Useful for fixing a value within unit testing.
*
* Will default to PHP time() value if null.
*/
public static $timestamp = null;
public static $supported_algs = array(
'HS256' => array('hash_hmac', 'SHA256'),
'HS512' => array('hash_hmac', 'SHA512'),
'HS384' => array('hash_hmac', 'SHA384'),
'RS256' => array('openssl', 'SHA256'),
'RS384' => array('openssl', 'SHA384'),
'RS512' => array('openssl', 'SHA512'),
);
/**
* Decodes a JWT string into a PHP object.
*
* @param string $jwt The JWT
* @param string|array $key The key, or map of keys.
* If the algorithm used is asymmetric, this is the public key
* @param array $allowed_algs List of supported verification algorithms
* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
*
* @return object The JWT's payload as a PHP object
*
* @throws UnexpectedValueException Provided JWT was invalid
* @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
* @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
* @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
* @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
*
* @uses jsonDecode
* @uses urlsafeB64Decode
*/
public static function decode($jwt, $key, array $allowed_algs = array())
{
$timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
if (empty($key)) {
throw new InvalidArgumentException('Key may not be empty');
}
$tks = explode('.', $jwt);
if (count($tks) != 3) {
throw new UnexpectedValueException('Wrong number of segments');
}
list($headb64, $bodyb64, $cryptob64) = $tks;
if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
throw new UnexpectedValueException('Invalid header encoding');
}
if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
throw new UnexpectedValueException('Invalid claims encoding');
}
if (false === ($sig = static::urlsafeB64Decode($cryptob64))) {
throw new UnexpectedValueException('Invalid signature encoding');
}
if (empty($header->alg)) {
throw new UnexpectedValueException('Empty algorithm');
}
if (empty(static::$supported_algs[$header->alg])) {
throw new UnexpectedValueException('Algorithm not supported');
}
if (!in_array($header->alg, $allowed_algs)) {
throw new UnexpectedValueException('Algorithm not allowed');
}
if (is_array($key) || $key instanceof \ArrayAccess) {
if (isset($header->kid)) {
if (!isset($key[$header->kid])) {
throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
}
$key = $key[$header->kid];
} else {
throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
}
}
// Check the signature
if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
throw new SignatureInvalidException('Signature verification failed');
}
// Check if the nbf if it is defined. This is the time that the
// token can actually be used. If it's not yet that time, abort.
if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
);
}
// Check that this token has been created before 'now'. This prevents
// using tokens that have been created for later use (and haven't
// correctly used the nbf claim).
if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
);
}
// Check if this token has expired.
if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
throw new ExpiredException('Expired token');
}
return $payload;
}
/**
* Converts and signs a PHP object or array into a JWT string.
*
* @param object|array $payload PHP object or array
* @param string $key The secret key.
* If the algorithm used is asymmetric, this is the private key
* @param string $alg The signing algorithm.
* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
* @param mixed $keyId
* @param array $head An array with header elements to attach
*
* @return string A signed JWT
*
* @uses jsonEncode
* @uses urlsafeB64Encode
*/
public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
{
$header = array('typ' => 'JWT', 'alg' => $alg);
if ($keyId !== null) {
$header['kid'] = $keyId;
}
if ( isset($head) && is_array($head) ) {
$header = array_merge($head, $header);
}
$segments = array();
$segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
$segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
$signing_input = implode('.', $segments);
$signature = static::sign($signing_input, $key, $alg);
$segments[] = static::urlsafeB64Encode($signature);
return implode('.', $segments);
}
/**
* Sign a string with a given key and algorithm.
*
* @param string $msg The message to sign
* @param string|resource $key The secret key
* @param string $alg The signing algorithm.
* Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
*
* @return string An encrypted message
*
* @throws DomainException Unsupported algorithm was specified
*/
public static function sign($msg, $key, $alg = 'HS256')
{
if (empty(static::$supported_algs[$alg])) {
throw new DomainException('Algorithm not supported');
}
list($function, $algorithm) = static::$supported_algs[$alg];
switch($function) {
case 'hash_hmac':
return hash_hmac($algorithm, $msg, $key, true);
case 'openssl':
$signature = '';
$success = openssl_sign($msg, $signature, $key, $algorithm);
if (!$success) {
throw new DomainException("OpenSSL unable to sign data");
} else {
return $signature;
}
}
}
/**
* Verify a signature with the message, key and method. Not all methods
* are symmetric, so we must have a separate verify and sign method.
*
* @param string $msg The original message (header and body)
* @param string $signature The original signature
* @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key
* @param string $alg The algorithm
*
* @return bool
*
* @throws DomainException Invalid Algorithm or OpenSSL failure
*/
private static function verify($msg, $signature, $key, $alg)
{
if (empty(static::$supported_algs[$alg])) {
throw new DomainException('Algorithm not supported');
}
list($function, $algorithm) = static::$supported_algs[$alg];
switch($function) {
case 'openssl':
$success = openssl_verify($msg, $signature, $key, $algorithm);
if ($success === 1) {
return true;
} elseif ($success === 0) {
return false;
}
// returns 1 on success, 0 on failure, -1 on error.
throw new DomainException(
'OpenSSL error: ' . openssl_error_string()
);
case 'hash_hmac':
default:
$hash = hash_hmac($algorithm, $msg, $key, true);
if (function_exists('hash_equals')) {
return hash_equals($signature, $hash);
}
$len = min(static::safeStrlen($signature), static::safeStrlen($hash));
$status = 0;
for ($i = 0; $i < $len; $i++) {
$status |= (ord($signature[$i]) ^ ord($hash[$i]));
}
$status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
return ($status === 0);
}
}
/**
* Decode a JSON string into a PHP object.
*
* @param string $input JSON string
*
* @return object Object representation of JSON string
*
* @throws DomainException Provided string was invalid JSON
*/
public static function jsonDecode($input)
{
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
/** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
* to specify that large ints (like Steam Transaction IDs) should be treated as
* strings, rather than the PHP default behaviour of converting them to floats.
*/
$obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
} else {
/** Not all servers will support that, however, so for older versions we must
* manually detect large ints in the JSON string and quote them (thus converting
*them to strings) before decoding, hence the preg_replace() call.
*/
$max_int_length = strlen((string) PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
$obj = json_decode($json_without_bigints);
}
if (function_exists('json_last_error') && $errno = json_last_error()) {
static::handleJsonError($errno);
} elseif ($obj === null && $input !== 'null') {
throw new DomainException('Null result with non-null input');
}
return $obj;
}
/**
* Encode a PHP object into a JSON string.
*
* @param object|array $input A PHP object or array
*
* @return string JSON representation of the PHP object or array
*
* @throws DomainException Provided object could not be encoded to valid JSON
*/
public static function jsonEncode($input)
{
$json = json_encode($input);
if (function_exists('json_last_error') && $errno = json_last_error()) {
static::handleJsonError($errno);
} elseif ($json === 'null' && $input !== null) {
throw new DomainException('Null result with non-null input');
}
return $json;
}
/**
* Decode a string with URL-safe Base64.
*
* @param string $input A Base64 encoded string
*
* @return string A decoded string
*/
public static function urlsafeB64Decode($input)
{
$remainder = strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
$input .= str_repeat('=', $padlen);
}
return base64_decode(strtr($input, '-_', '+/'));
}
/**
* Encode a string with URL-safe Base64.
*
* @param string $input The string you want encoded
*
* @return string The base64 encode of what you passed in
*/
public static function urlsafeB64Encode($input)
{
return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
}
/**
* Helper method to create a JSON error.
*
* @param int $errno An error number from json_last_error()
*
* @return void
*/
private static function handleJsonError($errno)
{
$messages = array(
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
);
throw new DomainException(
isset($messages[$errno])
? $messages[$errno]
: 'Unknown JSON error: ' . $errno
);
}
/**
* Get the number of bytes in cryptographic strings.
*
* @param string
*
* @return int
*/
private static function safeStrlen($str)
{
if (function_exists('mb_strlen')) {
return mb_strlen($str, '8bit');
}
return strlen($str);
}
}

View File

@ -0,0 +1,7 @@
<?php
namespace Firebase\JWT;
class SignatureInvalidException extends \UnexpectedValueException
{
}

1
rest/vendor/psr/log/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
vendor

19
rest/vendor/psr/log/LICENSE vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2012 PHP Framework Interoperability Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,128 @@
<?php
namespace Psr\Log;
/**
* This is a simple Logger implementation that other Loggers can inherit from.
*
* It simply delegates all log-level-specific methods to the `log` method to
* reduce boilerplate code that a simple Logger that does the same thing with
* messages regardless of the error level has to implement.
*/
abstract class AbstractLogger implements LoggerInterface
{
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
}

View File

@ -0,0 +1,7 @@
<?php
namespace Psr\Log;
class InvalidArgumentException extends \InvalidArgumentException
{
}

View File

@ -0,0 +1,18 @@
<?php
namespace Psr\Log;
/**
* Describes log levels.
*/
class LogLevel
{
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
}

View File

@ -0,0 +1,18 @@
<?php
namespace Psr\Log;
/**
* Describes a logger-aware instance.
*/
interface LoggerAwareInterface
{
/**
* Sets a logger instance on the object.
*
* @param LoggerInterface $logger
*
* @return void
*/
public function setLogger(LoggerInterface $logger);
}

View File

@ -0,0 +1,26 @@
<?php
namespace Psr\Log;
/**
* Basic Implementation of LoggerAwareInterface.
*/
trait LoggerAwareTrait
{
/**
* The logger instance.
*
* @var LoggerInterface
*/
protected $logger;
/**
* Sets a logger.
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace Psr\Log;
/**
* Describes a logger instance.
*
* The message MUST be a string or object implementing __toString().
*
* The message MAY contain placeholders in the form: {foo} where foo
* will be replaced by the context data in key "foo".
*
* The context array can contain arbitrary data. The only assumption that
* can be made by implementors is that if an Exception instance is given
* to produce a stack trace, it MUST be in a key named "exception".
*
* See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
* for the full interface specification.
*/
interface LoggerInterface
{
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array());
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array());
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array());
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array());
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array());
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array());
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array());
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array());
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = array());
}

View File

@ -0,0 +1,140 @@
<?php
namespace Psr\Log;
/**
* This is a simple Logger trait that classes unable to extend AbstractLogger
* (because they extend another class, etc) can include.
*
* It simply delegates all log-level-specific methods to the `log` method to
* reduce boilerplate code that a simple Logger that does the same thing with
* messages regardless of the error level has to implement.
*/
trait LoggerTrait
{
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
abstract public function log($level, $message, array $context = array());
}

View File

@ -0,0 +1,28 @@
<?php
namespace Psr\Log;
/**
* This Logger can be used to avoid conditional log calls.
*
* Logging should always be optional, and if no logger is provided to your
* library creating a NullLogger instance to have something to throw logs at
* is a good way to avoid littering your code with `if ($this->logger) { }`
* blocks.
*/
class NullLogger extends AbstractLogger
{
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = array())
{
// noop
}
}

View File

@ -0,0 +1,140 @@
<?php
namespace Psr\Log\Test;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* Provides a base test class for ensuring compliance with the LoggerInterface.
*
* Implementors can extend the class and implement abstract methods to run this
* as part of their test suite.
*/
abstract class LoggerInterfaceTest extends \PHPUnit_Framework_TestCase
{
/**
* @return LoggerInterface
*/
abstract public function getLogger();
/**
* This must return the log messages in order.
*
* The simple formatting of the messages is: "<LOG LEVEL> <MESSAGE>".
*
* Example ->error('Foo') would yield "error Foo".
*
* @return string[]
*/
abstract public function getLogs();
public function testImplements()
{
$this->assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger());
}
/**
* @dataProvider provideLevelsAndMessages
*/
public function testLogsAtAllLevels($level, $message)
{
$logger = $this->getLogger();
$logger->{$level}($message, array('user' => 'Bob'));
$logger->log($level, $message, array('user' => 'Bob'));
$expected = array(
$level.' message of level '.$level.' with context: Bob',
$level.' message of level '.$level.' with context: Bob',
);
$this->assertEquals($expected, $this->getLogs());
}
public function provideLevelsAndMessages()
{
return array(
LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
);
}
/**
* @expectedException \Psr\Log\InvalidArgumentException
*/
public function testThrowsOnInvalidLevel()
{
$logger = $this->getLogger();
$logger->log('invalid level', 'Foo');
}
public function testContextReplacement()
{
$logger = $this->getLogger();
$logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
$expected = array('info {Message {nothing} Bob Bar a}');
$this->assertEquals($expected, $this->getLogs());
}
public function testObjectCastToString()
{
if (method_exists($this, 'createPartialMock')) {
$dummy = $this->createPartialMock('Psr\Log\Test\DummyTest', array('__toString'));
} else {
$dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString'));
}
$dummy->expects($this->once())
->method('__toString')
->will($this->returnValue('DUMMY'));
$this->getLogger()->warning($dummy);
$expected = array('warning DUMMY');
$this->assertEquals($expected, $this->getLogs());
}
public function testContextCanContainAnything()
{
$context = array(
'bool' => true,
'null' => null,
'string' => 'Foo',
'int' => 0,
'float' => 0.5,
'nested' => array('with object' => new DummyTest),
'object' => new \DateTime,
'resource' => fopen('php://memory', 'r'),
);
$this->getLogger()->warning('Crazy context data', $context);
$expected = array('warning Crazy context data');
$this->assertEquals($expected, $this->getLogs());
}
public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$logger = $this->getLogger();
$logger->warning('Random message', array('exception' => 'oops'));
$logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
$expected = array(
'warning Random message',
'critical Uncaught Exception!'
);
$this->assertEquals($expected, $this->getLogs());
}
}
class DummyTest
{
public function __toString()
{
}
}

45
rest/vendor/psr/log/README.md vendored Normal file
View File

@ -0,0 +1,45 @@
PSR Log
=======
This repository holds all interfaces/classes/traits related to
[PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md).
Note that this is not a logger of its own. It is merely an interface that
describes a logger. See the specification for more details.
Usage
-----
If you need a logger, you can use the interface like this:
```php
<?php
use Psr\Log\LoggerInterface;
class Foo
{
private $logger;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
public function doSomething()
{
if ($this->logger) {
$this->logger->info('Doing work');
}
// do something useful
}
}
```
You can then pick one of the implementations of the interface to get a logger.
If you want to implement the interface, you can require this package and
implement `Psr\Log\LoggerInterface` in your code. Please read the
[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
for details.

26
rest/vendor/psr/log/composer.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"name": "psr/log",
"description": "Common interface for logging libraries",
"keywords": ["psr", "psr-3", "log"],
"homepage": "https://github.com/php-fig/log",
"license": "MIT",
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"require": {
"php": ">=5.3.0"
},
"autoload": {
"psr-4": {
"Psr\\Log\\": "Psr/Log/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}

View File

@ -0,0 +1,53 @@
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 2.4.0 - 2018-04-03
### Added
- Callback now receives also the raw token in arguments ([#93](https://github.com/tuupola/slim-jwt-auth/pull/93)).
```php
$app->add(new \Slim\Middleware\JwtAuthentication([
"secret" => "supersecretkeyyoushouldnotcommittogithub",
"callback" => function ($request, $response, $arguments) {
print_r($arguments["token"]);
}
]));
```
### Changed
- Response status code set in error handler is no longer ignored ([#111](https://github.com/tuupola/slim-jwt-auth/pull/111)) ([#110](https://github.com/tuupola/slim-jwt-auth/issues/110)).
## 2.3.3 - 2017-07-12
### Added
- Support for `firebase/php-jwt:^5.0` ([#59](https://github.com/tuupola/slim-jwt-auth/issues/59)) ([#61](https://github.com/tuupola/slim-jwt-auth/pull/61)).
## 2.3.2 - 2017-02-27
This is a security release.
`RequestPathRule` now removes multiple slashes from the URI before determining whether the path should be authenticated or not. For HTTP client `/foo` and `//foo` are different URIs and technically valid according to [RFC3986](https://tools.ietf.org/html/rfc3986). However on serverside it depends on implementation and often `/foo`, `//foo` and even `/////foo` are considered a same route.
Different PSR-7 implementations were behaving in different way. Diactoros [removes multiple leading slashes](https://github.com/zendframework/zend-diactoros/blob/master/CHANGELOG.md#104---2015-06-23). By default Slim does not alter any slashes. However when installed in subfolder [Slim removes all slashes](https://github.com/slimphp/Slim/issues/1554).
This means if you are authenticating a subfolder, for example `/api` and Slim is installed in document root it was possible to bypass authentication by doing a request to `//api`. Problem did not exist if Slim was installed in subfolder. Diactoros was not affected.
```php
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/api",
"secret" => "supersecretkeyyoushouldnotcommittogithub"
]));
```
If you were using default setting of authenticating all routes you were not affected.
```php
$app->add(new \Slim\Middleware\JwtAuthentication([
"secret" => "supersecretkeyyoushouldnotcommittogithub"
]));
```
### Fixed
- Bug [#50](https://github.com/tuupola/slim-jwt-auth/issues/50) where in some cases it was possible to bypass authentication by adding multiple slashes to request URI.

View File

@ -0,0 +1,21 @@
# The MIT License (MIT)
Copyright (c) 2015-2018 Mika Tuupola <tuupola@appelsiini.net>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.

View File

@ -0,0 +1,33 @@
.DEFAULT_GOAL := help
help:
@echo ""
@echo "Available tasks:"
@echo " lint Run linter and code style checker"
@echo " unit Run unit tests and generate coverage"
@echo " test Run linter and unit tests"
@echo " watch Run linter and unit tests when any of the source files change"
@echo " deps Install dependencies"
@echo " all Install dependencies and run linter and unit tests"
@echo ""
deps:
composer install --prefer-dist
lint:
vendor/bin/phplint . --exclude=vendor/
vendor/bin/phpcs -p --standard=PSR2 --extensions=php --encoding=utf-8 --ignore=*/vendor/*,*/benchmarks/* .
unit:
vendor/bin/phpunit --coverage-text --coverage-clover=coverage.xml --coverage-html=./report/
watch:
find . -name "*.php" -not -path "./vendor/*" -o -name "*.json" -not -path "./vendor/*" | entr -c make test
test: lint unit
travis: lint unit
all: deps test
.PHONY: help deps lint test watch all

View File

@ -0,0 +1,3 @@
codecov:
branch: 2.x
comment: false

View File

@ -0,0 +1,43 @@
{
"name": "tuupola/slim-jwt-auth",
"description": "PSR-7 JWT Authentication Middleware",
"keywords": [
"psr-7",
"middleware",
"jwt",
"json",
"auth"
],
"homepage": "https://github.com/tuupola/slim-jwt-auth",
"license": "MIT",
"authors": [
{
"name": "Mika Tuupola",
"email": "tuupola@appelsiini.net",
"homepage": "http://www.appelsiini.net/",
"role": "Developer"
}
],
"require": {
"php" : "^5.5 || ^7.0",
"psr/log": "^1.0",
"firebase/php-jwt": "^3.0 || ^4.0 || ^5.0",
"psr/http-message": "^1.0"
},
"require-dev": {
"phpunit/phpunit" : "^4.6",
"squizlabs/php_codesniffer": "^2.3",
"zendframework/zend-diactoros": "^1.3",
"overtrue/phplint": "^0.2.4"
},
"autoload": {
"psr-4": {
"Slim\\Middleware\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Slim\\Middleware\\": "tests"
}
}
}

View File

@ -0,0 +1,667 @@
<?php
/*
* This file is part of PSR-7 JSON Web Token Authentication middleware
*
* Copyright (c) 2015-2018 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware;
use Slim\Middleware\JwtAuthentication\RequestMethodRule;
use Slim\Middleware\JwtAuthentication\RequestPathRule;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Firebase\JWT\JWT;
class JwtAuthentication
{
/**
* PSR-3 compliant logger
*/
protected $logger;
/**
* Last error message
*/
protected $message;
/**
* Stores all the options passed to the rule
*/
private $options = [
"secure" => true,
"relaxed" => ["localhost", "127.0.0.1"],
"environment" => ["HTTP_AUTHORIZATION", "REDIRECT_HTTP_AUTHORIZATION"],
"algorithm" => ["HS256", "HS512", "HS384"],
"header" => "Authorization",
"regexp" => "/Bearer\s+(.*)$/i",
"cookie" => "token",
"attribute" => "token",
"path" => null,
"passthrough" => null,
"callback" => null,
"error" => null
];
/**
* Create a new middleware instance
*
* @param string[] $options
*/
public function __construct(array $options = [])
{
/* Setup stack for rules */
$this->rules = new \SplStack;
/* Store passed in options overwriting any defaults. */
$this->hydrate($options);
/* If nothing was passed in options add default rules. */
if (!isset($options["rules"])) {
$this->addRule(new RequestMethodRule([
"passthrough" => ["OPTIONS"]
]));
}
/* If path was given in easy mode add rule for it. */
if (null !== ($this->options["path"])) {
$this->addRule(new RequestPathRule([
"path" => $this->options["path"],
"passthrough" => $this->options["passthrough"]
]));
}
}
/**
* Call the middleware
*
* @param \Psr\Http\Message\RequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
* @param callable $next
* @return \Psr\Http\Message\ResponseInterface
*/
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$scheme = $request->getUri()->getScheme();
$host = $request->getUri()->getHost();
/* If rules say we should not authenticate call next and return. */
if (false === $this->shouldAuthenticate($request)) {
return $next($request, $response);
}
/* HTTP allowed only if secure is false or server is in relaxed array. */
if ("https" !== $scheme && true === $this->options["secure"]) {
if (!in_array($host, $this->options["relaxed"])) {
$message = sprintf(
"Insecure use of middleware over %s denied by configuration.",
strtoupper($scheme)
);
throw new \RuntimeException($message);
}
}
/* If token cannot be found return with 401 Unauthorized. */
if (false === $token = $this->fetchToken($request)) {
return $this->error($request, $response->withStatus(401), [
"message" => $this->message
]);
}
/* If token cannot be decoded return with 401 Unauthorized. */
if (false === $decoded = $this->decodeToken($token)) {
return $this->error($request, $response->withStatus(401), [
"message" => $this->message,
"token" => $token
]);
}
/* If callback returns false return with 401 Unauthorized. */
if (is_callable($this->options["callback"])) {
$params = ["decoded" => $decoded, "token" => $token];
if (false === $this->options["callback"]($request, $response, $params)) {
return $this->error($request, $response->withStatus(401), [
"message" => $this->message ? $this->message : "Callback returned false"
]);
}
}
/* Add decoded token to request as attribute when requested. */
if ($this->options["attribute"]) {
$request = $request->withAttribute($this->options["attribute"], $decoded);
}
/* Everything ok, call next middleware and return. */
return $next($request, $response);
}
/**
* Check if middleware should authenticate
*
* @param \Psr\Http\Message\RequestInterface $request
* @return boolean True if middleware should authenticate.
*/
public function shouldAuthenticate(RequestInterface $request)
{
/* If any of the rules in stack return false will not authenticate */
foreach ($this->rules as $callable) {
if (false === $callable($request)) {
return false;
}
}
return true;
}
/**
* Call the error handler if it exists
*
* @param \Psr\Http\Message\RequestInterface $request
* @param \Psr\Http\Message\ResponseInterface $response
* @param mixed[] $arguments
* @return \Psr\Http\Message\ResponseInterface
*/
public function error(RequestInterface $request, ResponseInterface $response, $arguments)
{
if (is_callable($this->options["error"])) {
$handler_response = $this->options["error"]($request, $response, $arguments);
if (is_a($handler_response, "\Psr\Http\Message\ResponseInterface")) {
return $handler_response;
}
}
return $response;
}
/**
* Fetch the access token
*
* @param \Psr\Http\Message\RequestInterface $request
* @return string|null Base64 encoded JSON Web Token or null if not found.
*/
public function fetchToken(RequestInterface $request)
{
/* If using PHP in CGI mode and non standard environment */
$server_params = $request->getServerParams();
$header = "";
$message = "";
/* Check for each given environment */
foreach ((array) $this->options["environment"] as $environment) {
if (isset($server_params[$environment])) {
$message = "Using token from environment";
$header = $server_params[$environment];
}
}
/* Nothing in environment, try header instead */
if (empty($header)) {
$message = "Using token from request header";
$headers = $request->getHeader($this->options["header"]);
$header = isset($headers[0]) ? $headers[0] : "";
}
/* Try apache_request_headers() as last resort */
if (empty($header) && function_exists("apache_request_headers")) {
$message = "Using token from apache_request_headers()";
$headers = apache_request_headers();
$header = isset($headers[$this->options["header"]]) ? $headers[$this->options["header"]] : "";
}
if (preg_match($this->options["regexp"], $header, $matches)) {
$this->log(LogLevel::DEBUG, $message);
return $matches[1];
}
/* Bearer not found, try a cookie. */
$cookie_params = $request->getCookieParams();
if (isset($cookie_params[$this->options["cookie"]])) {
$this->log(LogLevel::DEBUG, "Using token from cookie");
$this->log(LogLevel::DEBUG, $cookie_params[$this->options["cookie"]]);
return $cookie_params[$this->options["cookie"]];
};
/* If everything fails log and return false. */
$this->message = "Token not found";
$this->log(LogLevel::WARNING, $this->message);
return false;
}
/**
* Decode the token
*
* @param string $$token
* @return object|boolean The JWT's payload as a PHP object or false in case of error
*/
public function decodeToken($token)
{
try {
return JWT::decode(
$token,
$this->options["secret"],
(array) $this->options["algorithm"]
);
} catch (\Exception $exception) {
$this->message = $exception->getMessage();
$this->log(LogLevel::WARNING, $exception->getMessage(), [$token]);
return false;
}
}
/**
* Hydate options from given array
*
* @param array $data Array of options.
* @return self
*/
private function hydrate(array $data = [])
{
foreach ($data as $key => $value) {
$method = "set" . ucfirst($key);
if (method_exists($this, $method)) {
call_user_func(array($this, $method), $value);
}
}
return $this;
}
/**
* Get path where middleware is be binded to
*
* @return string
*/
public function getPath()
{
return $this->options["path"];
}
/**
* Set path where middleware should be binded to
*
* @param string|string[] $$path
* @return self
*/
public function setPath($path)
{
$this->options["path"] = $path;
return $this;
}
/**
* Get path which middleware ignores
*
* @return string|array
*/
public function getPassthrough()
{
return $this->options["passthrough"];
}
/**
* Set path which middleware ignores
*
* @param string|string[] $passthrough
* @return self
*/
public function setPassthrough($passthrough)
{
$this->options["passthrough"] = $passthrough;
return $this;
}
/**
* Get the environment name where to search the token from
*
* @return string Name of environment variable.
*/
public function getEnvironment()
{
return $this->options["environment"];
}
/**
* Set the environment name where to search the token from
*
* @param string $environment
* @return self
*/
public function setEnvironment($environment)
{
$this->options["environment"] = $environment;
return $this;
}
/**
* Get the cookie name where to search the token from
*
* @return string
*/
public function getCookie()
{
return $this->options["cookie"];
}
/**
* Set the cookie name where to search the token from
*
* @param string $cookie
* @return self
*/
public function setCookie($cookie)
{
$this->options["cookie"] = $cookie;
return $this;
}
/**
* Get the secure flag
*
* @return boolean
*/
public function getSecure()
{
return $this->options["secure"];
}
/**
* Set the secure flag
*
* @param boolean $secure
* @return self
*/
public function setSecure($secure)
{
$this->options["secure"] = !!$secure;
return $this;
}
/**
* Get hosts where secure rule is relaxed
*
* @return array
*/
public function getRelaxed()
{
return $this->options["relaxed"];
}
/**
* Set hosts where secure rule is relaxed
*
* @param string[] $relaxed
* @return self
*/
public function setRelaxed(array $relaxed)
{
$this->options["relaxed"] = $relaxed;
return $this;
}
/**
* Get the secret key
*
* @return string
*/
public function getSecret()
{
return $this->options["secret"];
}
/**
* Set the secret key
*
* @param string $secret
* @return self
*/
public function setSecret($secret)
{
$this->options["secret"] = $secret;
return $this;
}
/**
* Get the callback
*
* @return callable
*/
public function getCallback()
{
return $this->options["callback"];
}
/**
* Set the callback
*
* @param callable $callback
* @return self
*/
public function setCallback($callback)
{
$this->options["callback"] = $callback->bindTo($this);
return $this;
}
/**
* Get the error handler
*
* @return callable
*/
public function getError()
{
return $this->options["error"];
}
/**
* Set the error handler
*
* @param callable $error
* @return self
*/
public function setError($error)
{
$this->options["error"] = $error;
return $this;
}
/**
* Get the rules stack
*
* @return \SplStack
*/
public function getRules()
{
return $this->rules;
}
/**
* Set all rules in the stack
*
* @param array $rules
* @return self
*/
public function setRules(array $rules)
{
/* Clear the stack */
unset($this->rules);
$this->rules = new \SplStack;
/* Add the rules */
foreach ($rules as $callable) {
$this->addRule($callable);
}
return $this;
}
/**
* Add rule to the stack
*
* @param callable $callable Callable which returns a boolean.
* @return self
*/
public function addRule($callable)
{
$this->rules->push($callable);
return $this;
}
/* Cannot use traits since PHP 5.3 should be supported */
/**
* Get the logger
*
* @return \Psr\Log\LoggerInterface $logger
*/
public function getLogger()
{
return $this->logger;
}
/**
* Set the logger
*
* @param \Psr\Log\LoggerInterface $logger
* @return self
*/
public function setLogger(LoggerInterface $logger = null)
{
$this->logger = $logger;
return $this;
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return null
*/
public function log($level, $message, array $context = [])
{
if ($this->logger) {
return $this->logger->log($level, $message, $context);
}
}
/**
* Get last error message
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Set the last error message
*
* @param string
* @return self
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* Get the attribute name used to attach decoded token to request
*
* @return string
*/
public function getAttribute()
{
return $this->options["attribute"];
}
/**
* Set the attribute name used to attach decoded token to request
*
* @param string
* @return self
*/
public function setAttribute($attribute)
{
$this->options["attribute"] = $attribute;
return $this;
}
/**
* Get the header where token is searched from
*
* @return string
*/
public function getHeader()
{
return $this->options["header"];
}
/**
* Set the header where token is searched from
*
* @param string
* @return self
*/
public function setHeader($header)
{
$this->options["header"] = $header;
return $this;
}
/**
* Get the regexp used to extract token from header or environment
*
* @return string
*/
public function getRegexp()
{
return $this->options["regexp"];
}
/**
* Set the regexp used to extract token from header or environment
*
* @param string
* @return self
*/
public function setRegexp($regexp)
{
$this->options["regexp"] = $regexp;
return $this;
}
/**
* Get the allowed algorithms
*
* @return string|string[]
*/
public function getAlgorithm()
{
return $this->options["algorithm"];
}
/**
* Set the allowed algorithms
*
* @param string|string[] $algorithm
* @return self
*/
public function setAlgorithm($algorithm)
{
$this->options["algorithm"] = $algorithm;
return $this;
}
}

View File

@ -0,0 +1,53 @@
<?php
/**
* This file is part of PSR-7 JSON Web Token Authentication middleware
*
* Copyright (c) 2015-2018 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware\JwtAuthentication;
use \Psr\Http\Message\RequestInterface;
/**
* Rule to decide by HTTP verb whether the request should be authenticated or not.
*/
class RequestMethodRule implements RuleInterface
{
/**
* Stores all the options passed to the rule
*/
protected $options = [
"passthrough" => ["OPTIONS"]
];
/**
* Create a new rule instance
*
* @param string[] $options
* @return void
*/
public function __construct(array $options = [])
{
$this->options = array_merge($this->options, $options);
}
/**
* @param \Psr\Http\Message\RequestInterface $request
* @return boolean
*/
public function __invoke(RequestInterface $request)
{
return !in_array($request->getMethod(), $this->options["passthrough"]);
}
}

View File

@ -0,0 +1,71 @@
<?php
/*
* This file is part of PSR-7 JSON Web Token Authentication middleware
*
* Copyright (c) 2015-2018 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware\JwtAuthentication;
use Psr\Http\Message\RequestInterface;
/**
* Rule to decide by request path whether the request should be authenticated or not.
*/
class RequestPathRule implements RuleInterface
{
/**
* Stores all the options passed to the rule
*/
protected $options = [
"path" => ["/"],
"passthrough" => []
];
/**
* Create a new rule instance
*
* @param string[] $options
* @return void
*/
public function __construct($options = [])
{
$this->options = array_merge($this->options, $options);
}
/**
* @param \Psr\Http\Message\RequestInterface $request
* @return boolean
*/
public function __invoke(RequestInterface $request)
{
$uri = "/" . $request->getUri()->getPath();
$uri = preg_replace("#/+#", "/", $uri);
/* If request path is matches passthrough should not authenticate. */
foreach ((array)$this->options["passthrough"] as $passthrough) {
$passthrough = rtrim($passthrough, "/");
if (!!preg_match("@^{$passthrough}(/.*)?$@", $uri)) {
return false;
}
}
/* Otherwise check if path matches and we should authenticate. */
foreach ((array)$this->options["path"] as $path) {
$path = rtrim($path, "/");
if (!!preg_match("@^{$path}(/.*)?$@", $uri)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,23 @@
<?php
/*
* This file is part of PSR-7 JSON Web Token Authentication middleware
*
* Copyright (c) 2015-2018 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Project home:
* https://github.com/tuupola/slim-jwt-auth
*
*/
namespace Slim\Middleware\JwtAuthentication;
use Psr\Http\Message\RequestInterface;
interface RuleInterface
{
public function __invoke(RequestInterface $request);
}

6
salir.php Normal file
View File

@ -0,0 +1,6 @@
<?php if(!isset($_SESSION)) { if(!isset($_SESSION)) { session_start(); } }
session_destroy();
$pagina=$_SERVER['HTTP_REFERER'];
header("Location:./index.php");
?>