Authenticacion

This commit is contained in:
2020-04-07 15:37:21 -04:00
parent 2ae6826ff4
commit bca4665721
27 changed files with 378 additions and 34 deletions

View File

@ -8,8 +8,8 @@ $container_builder = new DI\ContainerBuilder();
$folders = [ $folders = [
'common' 'common'
]; ];
if (isset($_ENV)) { if (isset($__environment)) {
$folders []= $_ENV; $folders []= $__environment;
} }
$file = 'config.php'; $file = 'config.php';
@ -42,4 +42,7 @@ foreach ($folders as $folder) {
} }
} }
$dotenv = Dotenv\Dotenv::createImmutable($container->get('folders.base'));
$dotenv->load();
include_once implode(DIRECTORY_SEPARATOR, [$app->getContainer()->get('folders.routes'), 'router.php']); include_once implode(DIRECTORY_SEPARATOR, [$app->getContainer()->get('folders.routes'), 'router.php']);

View File

@ -1,3 +1,3 @@
<?php <?php
$_ENV = 'web'; $__environment = 'web';
include_once 'app.php'; include_once 'app.php';

View File

@ -47,12 +47,13 @@ return [
'uploads' 'uploads'
])), ])),
'urls.metro.logo' => 'https://img.freepik.com/free-icon/santiago-metro-logo_318-66588.jpg?size=338&ext=jpg', 'urls.metro.logo' => 'https://img.freepik.com/free-icon/santiago-metro-logo_318-66588.jpg?size=338&ext=jpg',
'urls.notaria.turno' => 'http://www.notariasdeturno.cl', 'urls.notaria.turno' => 'https://www.notariosyconservadores.cl/notarias-de-turno/',
'urls.fojas' => 'http://fojas.cl/?motv=vista_descarga_web&cons_sel=not_patricrabybenavent', 'urls.fojas' => 'http://fojas.cl/?motv=vista_descarga_web&cons_sel=not_patricrabybenavent',
'urls.atencion' => 'https://zeroq.cl/#/local/notaria-patricio-raby/48', 'urls.atencion' => 'https://zeroq.cl/#/local/notaria-patricio-raby/48',
'urls.atencion.logo' => 'https://zeroq.cl/img/logo-small.png', 'urls.atencion.logo' => 'https://zeroq.cl/img/logo-small.png',
'urls.map' => 'https://maps.google.com/maps?hl=es&amp;q=Notaria%20Patricio%20Raby+(Notaria%20Patricio%20Raby)&amp;ie=UTF8&amp;z=16&amp;iwloc=B&amp;output=embed', 'urls.map' => 'https://maps.google.com/maps?hl=es&amp;q=Notaria%20Patricio%20Raby+(Notaria%20Patricio%20Raby)&amp;ie=UTF8&amp;z=16&amp;iwloc=B&amp;output=embed',
'urls.map2' => 'https://www.google.com/maps/embed/v1/place?q=notaria+patricio+raby&key=AIzaSyBFw0Qbyq9zTFTd-tUY6dZWTgaQzuU17R8', 'urls.map2' => 'https://www.google.com/maps/embed/v1/place?q=notaria+patricio+raby&key=AIzaSyBFw0Qbyq9zTFTd-tUY6dZWTgaQzuU17R8',
'urls.direccion' => 'https://goo.gl/maps/xcxs1SQ9BPAbUDi69',
'styles' => [ 'styles' => [
'https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.8.4/semantic.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.8.4/semantic.min.css',
DI\string(implode('/', ['{urls.styles}', 'iconmoon.css'])), DI\string(implode('/', ['{urls.styles}', 'iconmoon.css'])),
@ -85,5 +86,13 @@ return [
'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.8.4/semantic.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.8.4/semantic.min.js',
'https://friconix.com/cdn/friconix.js' 'https://friconix.com/cdn/friconix.js'
] ],
'app.cookie.name' => 'login',
'app.cookie.time' => 20 * 60 * 60, // 20 min
'files.login' => 'login.yml',
'urls.login' => DI\string(implode('/', [
'{urls.base}',
'admin',
'login'
]))
]; ];

View File

@ -1,11 +1,2 @@
<?php <?php
$app->add(new ProVM\NotariaRaby\Common\Middleware\Blade($app->getContainer())); $app->add(new ProVM\NotariaRaby\Common\Middleware\Blade($app->getContainer()));
$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
'path' => $app->getContainer()->get('urls.base') . '/admin',
'ignore' => [
'/admin/login'
],
'users' => [
'admin' => 'admin'
]
]));

View File

@ -24,7 +24,8 @@ return [
'url' => $container->get('urls.atencion'), 'url' => $container->get('urls.atencion'),
'logo' => $container->get('urls.atencion.logo') 'logo' => $container->get('urls.atencion.logo')
], ],
'uploads' => $container->get('urls.uploads') 'uploads' => $container->get('urls.uploads'),
'direccion' => $container->get('urls.direccion')
], ],
'horario' => $horario, 'horario' => $horario,
'styles' => $container->get('styles'), 'styles' => $container->get('styles'),
@ -38,6 +39,22 @@ return [
$manager->addFolder('data', $c->get('folders.data')); $manager->addFolder('data', $c->get('folders.data'));
return $manager; return $manager;
}, },
ProVM\NotariaRaby\Common\Service\Login::class => function(Container $c) {
return new ProVM\NotariaRaby\Common\Service\Login(
$c->get('app.cookie.name'),
$c->get('app.cookie.time'),
getenv('ADMIN_PASSWORD'),
$c->get('files.login'),
$c->get(ProVM\Common\Service\Filemanager::class)
);
},
ProVM\NotariaRaby\Common\Middleware\Auth::class => function(Container $c) {
return new ProVM\NotariaRaby\Common\Middleware\Auth(
['admin'],
$c->get('urls.login'),
$c->get(ProVM\NotariaRaby\Common\Service\Login::class)
);
},
Nette\Mail\SendmailMailer::class => DI\create(), Nette\Mail\SendmailMailer::class => DI\create(),
Nette\Mail\SmtpMailer::class => function(Container $c) { Nette\Mail\SmtpMailer::class => function(Container $c) {
return new Nette\Mail\SmtpMailer($c->get('email')); return new Nette\Mail\SmtpMailer($c->get('email'));

View File

@ -0,0 +1,44 @@
<?php
namespace ProVm\NotariaRaby\Common\Controller\Web\Admin;
use Psr\Container\ContainerInterface as Container;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\Blade as View;
use ProVM\Common\Service\Filemanager;
use ProVM\NotariaRaby\Common\Service\Login;
class Clave {
public function __invoke(Request $request, Response $response, View $view): Response {
return $view->render($response, 'admin.clave');
}
public function do_edit(Request $request, Response $response, Container $container, Filemanager $filemanager, Login $service): Response {
$filename = implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__, 4),
'.env'
]);
$vars = [];
if (file_exists($filename)) {
$vars = explode(PHP_EOL, trim(file_get_contents($filename)));
}
$i = 0;
foreach ($vars as $i => $var) {
if (strpos($var, 'ADMIN_PASSWORD=') !== false) {
break;
}
}
$post = $request->getParsedBody();
$enc = password_hash($post['clave'], \PASSWORD_DEFAULT);
$vars[$i] = implode('=', [
'ADMIN_PASSWORD',
'"' . $enc . '"'
]);
file_put_contents($filename, implode(PHP_EOL, $vars));
return $response
->withHeader('Location', implode('/', [
$container->get('urls.base'),
'admin'
]))
->withStatus(301);
}
}

View File

@ -1,12 +1,23 @@
<?php <?php
namespace ProVM\NotariaRaby\Common\Controller\Web\Admin; namespace ProVM\NotariaRaby\Common\Controller\Web\Admin;
use Psr\Container\ContainerInterface as Container;
use Psr\Http\Message\ServerRequestInterface as Request; use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ResponseInterface as Response;
use Slim\Views\Blade as View; use Slim\Views\Blade as View;
use ProVM\NotariaRaby\Common\Service\Login as Service;
class Login { class Login {
public function __invoke(Request $request, Response $response, View $view): Response { public function __invoke(Request $request, Response $response, View $view): Response {
return $view->render($response, 'admin.login'); return $view->render($response, 'admin.login');
} }
public function do_login(Request $request, Response $response, Service $login, Container $container): Response {
$login->login($request);
return $response
->withHeader('Location', implode('/', [
$container->get('urls.base'),
'admin'
]))
->withStatus(301);
}
} }

View File

@ -12,7 +12,7 @@ class Home {
public function __invoke(Request $request, Response $response, View $view, Filemanager $manager, Container $container): Response { public function __invoke(Request $request, Response $response, View $view, Filemanager $manager, Container $container): Response {
$banner = (object) [ $banner = (object) [
'titulo' => "5° NOTARÍA DE SANTIAGO", 'titulo' => "5° NOTARÍA DE SANTIAGO",
'contenido' => "Gertrudis Echenique 30, of. 32, El Golf\n<i class=\"large icon icon-metro\"></i> Metro Alcantara" 'contenido' => '<a href="' . $container->get('urls.direccion') . '">Gertrudis Echenique 30, of. 32, El Golf' . "\n" . '<i class="large icon icon-metro"></i> Metro Alcantara</a>'
]; ];
$links = $manager->folder('data')->load('documentos.yml'); $links = $manager->folder('data')->load('documentos.yml');

View File

@ -0,0 +1,28 @@
<?php
namespace ProVM\NotariaRaby\Common\Middleware;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as Handler;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Container\ContainerInterface as Container;
use ProVM\NotariaRaby\Common\Service\Login;
class Auth {
protected $users;
public function __construct(array $users, string $login_url, Login $service) {
$this->users = $users;
$this->login_url = $login_url;
$this->login = $service;
}
public function __invoke(Request $request, Handler $handler): Response {
$response = $handler->handle($request);
$is_logged_in = $this->login->checkAuth($request);
if (!$is_logged_in and $request->getRequestTarget() != $this->login_url) {
return $response
->withHeader('Location', $this->login_url)
->withStatus(301);
}
return $response;
}
}

110
common/Service/Login.php Normal file
View File

@ -0,0 +1,110 @@
<?php
namespace ProVM\NotariaRaby\Common\Service;
use Psr\Http\Message\ServerRequestInterface as Request;
use Carbon\Carbon;
use ProVM\Common\Service\Filemanager;
class Login {
protected $cookie_name;
protected $time_limit;
protected $password;
protected $filename;
protected $manager;
public function __construct(string $cookie_name, int $time_limit, string $encrypted_password, string $login_file, Filemanager $filemanager) {
$this->cookie_name = $cookie_name;
$this->time_limit = $time_limit;
$this->password = $encrypted_password;
$this->filename = $login_file;
$this->manager = $filemanager;
}
protected $selector;
protected $token;
public function loadCookie() {
if (isset($_COOKIE[$this->cookie_name])) {
list($s, $t) = \explode(':', $_COOKIE[$this->cookie_name]);
$this->selector = $s;
$this->token = $t;
}
}
public function saveCookie() {
$now = Carbon::now();
$exp = $now->addSeconds($this->time_limit);
\setcookie($this->cookie_name, implode(':', [$this->selector, $this->token]), $exp->timestamp, '/');
}
public function removeCookie() {
\setcookie($this->cookie_name, '', Carbon::now()->timestamp, '/');
}
protected function generateToken() {
$this->selector = bin2hex(\random_bytes(12));
$this->token = bin2hex(\random_bytes(20));
}
protected $data;
public function getData() {
if ($this->data === null) {
$this->data = (object) [
'ip' => 0,
'token' => '',
'time' => 0
];
if ($this->manager->folder('data')->exists($this->filename)) {
$this->data = $this->manager->folder('data')->load($this->filename);
$this->data->time = Carbon::parse($this->data->time);
}
}
}
protected $ip;
public function getIp(Request $request) {
if ($this->ip === null) {
$this->ip = $request->getHeader('host')[0];
}
return $this->ip;
}
protected $is_logged_in;
public function checkAuth(Request $request): bool {
if ($this->is_logged_in === null) {
$this->loadCookie();
if ($this->selector === null) {
$this->is_logged_in = false;
return false;
}
$this->getIp($request);
$this->getData();
if ($this->data->ip != $this->ip) {
$this->is_logged_in = false;
return false;
}
if ($this->data->token != implode(':', [$this->selector, $this->token])) {
$this->is_logged_in = false;
return false;
}
$now = Carbon::now();
if ($this->data->time->copy()->addSeconds($this->time_limit)->diffInSeconds($now->copy()) < 0) {
$this->is_logged_in = false;
}
$this->is_logged_in = true;
}
return $this->is_logged_in;
}
public function login(Request $request): bool {
$post = $request->getParsedBody();
if (!password_verify($post['clave'], $this->password)) {
return false;
}
$this->generateToken();
$this->getIp($request);
$time = Carbon::now();
$data = [
'ip' => $this->ip,
'token' => implode(':', [$this->selector, $this->token]),
'time' => $time->format('Y-m-d H:i')
];
$this->manager->folder('data')->save($this->filename, $data);
$this->saveCookie();
$this->is_logged_in = true;
return true;
}
}

View File

@ -15,7 +15,8 @@
"tuupola/slim-basic-auth": "^3.2", "tuupola/slim-basic-auth": "^3.2",
"mustangostang/spyc": "^0.6.3", "mustangostang/spyc": "^0.6.3",
"nette/mail": "^3.1", "nette/mail": "^3.1",
"nesbot/carbon": "^2.32" "nesbot/carbon": "^2.32",
"vlucas/phpdotenv": "^4.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^8.5", "phpunit/phpunit": "^8.5",

View File

@ -11,7 +11,7 @@ abstract class Controller implements ControllerInterface {
->withHeader('Content-Type', 'application/json') ->withHeader('Content-Type', 'application/json')
->withStatus(201); ->withStatus(201);
} }
public function withRedirect(string $uri): Response { public function withRedirect(Response $response, string $uri): Response {
return $response return $response
->withHeader('Location', $uri) ->withHeader('Location', $uri)
->withStatus(303); ->withStatus(303);

View File

@ -30,9 +30,12 @@ class Filemanager {
public function folder(string $name) { public function folder(string $name) {
return new Filemanager($this->filesystem, $this->folders[$name]); return new Filemanager($this->filesystem, $this->folders[$name]);
} }
public function exists(string $filename) {
return $this->filesystem->exists($this->fullPath($filename));
}
public function load(string $filename) { public function load(string $filename) {
$filename = $this->fullPath($filename); $filename = $this->fullPath($filename);
if (!$this->filesystem->exists($filename)) { if (!$this->exists($filename)) {
return false; return false;
} }
$file = new \SplFileInfo($filename); $file = new \SplFileInfo($filename);

View File

@ -20,7 +20,17 @@ html {
padding-left: 0 !important; padding-left: 0 !important;
} }
#page_container {
display: flex;
flex-direction: column;
height: 100%;
}
.content {
flex: 1 0 auto;
}
footer { footer {
flex: none;
color: white; color: white;
height: 260px; height: 260px;
font-family: Roboto; font-family: Roboto;

View File

@ -1,4 +1,6 @@
<?php <?php
session_start();
include_once implode(DIRECTORY_SEPARATOR, [ include_once implode(DIRECTORY_SEPARATOR, [
dirname(__DIR__), dirname(__DIR__),
'bootstrap', 'bootstrap',

4
resources/data/login.yml Normal file
View File

@ -0,0 +1,4 @@
ip: localhost
token: >
2c579161cd33d9b2d3dd7791:b6936fbd9f2f1403558af3e5bc5330188af9a03e
time: 2020-04-07 16:20

View File

@ -1,7 +1,7 @@
<?php <?php
$folder = implode(DIRECTORY_SEPARATOR, [ $folder = implode(DIRECTORY_SEPARATOR, [
__DIR__, __DIR__,
$_ENV $__environment
]); ]);
$filename = $_ENV . '.php'; $filename = $__environment . '.php';
include_once $filename; include_once $filename;

View File

@ -17,4 +17,4 @@ $app->group('/admin', function($app) {
} }
$app->get('[/]', Admin::class); $app->get('[/]', Admin::class);
}); })->add($app->getContainer()->get(ProVM\NotariaRaby\Common\Middleware\Auth::class));

View File

@ -0,0 +1,7 @@
<?php
use ProVM\NotariaRaby\Common\Controller\Web\Admin\Clave;
$app->group('/clave', function($app) {
$app->get('[/]', Clave::class);
$app->post('[/]', [Clave::class, 'do_edit']);
});

View File

@ -0,0 +1,7 @@
<?php
use ProVM\NotariaRaby\Common\Controller\Web\Admin\Login;
$app->group('/login', function($app) {
$app->get('[/]', Login::class);
$app->post('[/]', [Login::class, 'do_login']);
});

View File

@ -0,0 +1,88 @@
@extends('admin.layout.base')
@section('content')
<div class="ui container">
<h2>Cambiar Clave</h2>
<form class="ui form" method="post" action="{{$urls->base}}/admin/clave" id="clave_form">
<div class="field">
<label>Clave</label>
<input type="password" name="clave" />
</div>
<div class="field">
<label>Repetir Clave</label>
<input type="password" name="clave2" />
</div>
<button class="ui button">Cambiar</button>
<div class="ui warning message" id="warnings">
<ul class="ui list"></ul>
</div>
<div class="ui error message" id="errors">
<ul class="ui list"></ul>
</div>
</form>
</div>
@endsection
@push('scripts')
<script type="text/javascript">
function clearErrors() {
$('#warnings').find('ul.list').html('')
$('#warnings').hide()
$('#errors').find('ul.list').html('')
$('#errors').hide()
}
function addError(msg) {
$('#errors').find('ul.list').append(
$('<li></li>').html(msg)
)
$('#errors').show()
}
function addWarning(msg) {
$('#warnings').find('ul.list').append(
$('<li></li>').html(msg)
)
$('#warnings').show()
}
function checkClaves() {
var c1 = $("input[name='clave']").val()
if (!validateClave(c1)) {
return false
}
var c2 = $("input[name='clave2']").val()
if (c1 != c2) {
addError('Las dos claves no coinciden.')
return false
}
return true
}
function validateClave(clave) {//NotariaR4b¿?
console.debug(clave)
var strong = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})")
var medium = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})")
if (!medium.test(clave)) {
addError('La clave no cumple con el mínimo de fuerza.')
return false
}
if (!strong.test(clave)) {
addWarning('Se recomienda una clave mas fuerte.')
}
return true
}
$(document).ready(function() {
clearErrors()
$("input[name='clave']").change(function() {
clearErrors()
validateClave($(this).val())
})
$('#clave_form').submit(function(e) {
clearErrors()
if (checkClaves()) {
$(this).submit()
return true
}
e.preventDefault()
return false
})
})
</script>
@endpush

View File

@ -1,11 +1,18 @@
@extends('admin.base') @extends('admin.layout.base')
@section('content') @section('content')
<form class="ui form" method="post" action="{{$base_url}}/admin/login"> <div class="ui container">
<form class="ui form" method="post" action="{{$urls->base}}/admin/login">
<div class="ui center aligned grid">
<div class="left aligned five wide column">
<h3>Ingresar</h3>
<div class="inline field"> <div class="inline field">
<label>Clave</label> <label>Clave</label>
<input type="password" name="clave" /> <input type="password" name="clave" />
</div> </div>
<button class="ui button">Entrar</button> <button class="ui inverted dark-blue button">Entrar</button>
</div>
</div>
</form> </form>
</div>
@endsection @endsection

View File

@ -2,7 +2,7 @@
<div class="ui stackable grid"> <div class="ui stackable grid">
<div class="row"> <div class="row">
<div class="ten wide column img"></div> <div class="ten wide column img"></div>
<div class="four wide column contenido"> <div class="six wide column contenido">
<div class="titulo"> <div class="titulo">
&Iacute;NDICES EN L&Iacute;NEA &Iacute;NDICES EN L&Iacute;NEA
</div> </div>

View File

@ -4,7 +4,9 @@
<body> <body>
<div id="page_container" class="ui fluid container"> <div id="page_container" class="ui fluid container">
@include('layout.header') @include('layout.header')
<div class="content">
@yield('page_content') @yield('page_content')
</div>
@include('layout.footer') @include('layout.footer')
</div> </div>
</body> </body>

View File

@ -6,10 +6,10 @@
<a class="item" href="{{$urls->base}}/notaria"> <a class="item" href="{{$urls->base}}/notaria">
NOTAR&Iacute;A NOTAR&Iacute;A
</a> </a>
<a class="item" href="{{$urls->base}}#servicios"> <a class="item" href="#servicios">
SERVICIOS SERVICIOS
</a> </a>
<a class="item" href="{{$urls->base}}#consultas"> <a class="item" href="#consultas">
CONSULTAS CONSULTAS
</a> </a>
<a class="item" href="{{$urls->base}}/contacto"> <a class="item" href="{{$urls->base}}/contacto">

BIN
vendor.tar Normal file

Binary file not shown.

BIN
vendor.tar.gz Normal file

Binary file not shown.