Commit a327f521 by David Villalba

Trair inutraliaWS y Login

parent 0ace5380
......@@ -24,9 +24,9 @@ class Controller_App extends Controller{
public function before(){
if (! Auth::check() ){
Response::redirect("/");
if (!$this->control_time_session()){
Session::destroy();
Response::redirect("/");
}
Config::load('app', true);
......@@ -34,6 +34,21 @@ class Controller_App extends Controller{
parent::before();
}
public function control_time_session(){
if(Session::get('expire_session') === null || Session::get('expire_session') > strtotime(date("Y-m-d H:i:s")) ){
Session::set('expire_session',strtotime(date("Y-m-d H:i:s",strtotime("+1 Hour"))));
return true;
}else{
return false;
}
}
public function post_locale(){
$id = Input::post('id','');
......
......@@ -16,16 +16,21 @@ use Fuel\Core\Log;
use Fuel\Core\Response;
use Fuel\Core\Security;
class Controller_Login_Index extends Controller{
class Controller_Login_Index extends Controller
{
use \Trait_InutraliaWS;
public function get_login()
{
// redirects if the user is logged
if (Auth::check()) {
// Si tiene el token auth esta logeado, en el before del controller APP controlamos el tiempo de exipacion de sessión.
// En el Logut tenemos que destruir la sesión.
if (\Session::get('token_auth') !== null) {
$datos = \Config::load('empresa');
Session::set('empresa',$datos);
Session::set('empresa', $datos);
return Response::redirect('/dashboard');
}
......@@ -36,8 +41,12 @@ class Controller_Login_Index extends Controller{
public function post_login()
{
$datos = \Config::load('empresa');
Session::set('empresa',$datos);
Session::set('empresa', $datos);
$username = \Input::post('username');
$password = \Input::post('password');
// performs de validation
if (!Security::check_token()) {
......@@ -50,77 +59,36 @@ class Controller_Login_Index extends Controller{
return null;
}
$val = Validation::forge();
$val->add('username', 'Correo Electronico')
->add_rule('required');
$val->add('password', 'Contraseña')
->add_rule('required');
// seteamos el old input
Session::set_flash('login:username', \Input::post('username'));
if ($val->run()) {
try {
Auth::attempt(
array(
'username' => $val->validated('username'),
'password' => $val->validated('password')
)
);
\Session::set_flash('login:username', \Input::post('username'));
$usu = array(
'username' => $val->validated('username'),
'nombre' => $val->validated('password')
);
$return = (array)$this->ws_user($username,$password);
Session::set('usuario',$usu);
if(!isset($return['status'])){
Response::redirect('/dashboard');
return null;
} catch (UserNotFoundException $e) {
Session::set_flash(
'message:error',
'No es posible entrar, email o contraseña incorrecto'
);
Response::redirect('auth/login');
return null;
}
catch (UserUnverifiedException $e) {
Session::set_flash(
'message:error',
'La cuenta a la que intenta conectarse no esta verificada aún. Inténtelo más tarde.'
);
Response::redirect('auth/login');
return null;
}
catch (UserPasswordIncorrectException $e) {
Session::set_flash(
'message:error',
'No es posible entrar, email o contraseña incorrecto'
);
Response::redirect('auth/login');
return null;
}
catch (UserDisabledException $e) {
Session::set_flash(
}elseif ($return['status'] == "0"){
\Session::set_flash(
'message:error',
'"No es posible acceder a tu cuenta porque está desactivada. Por favor, contacta con nuestro equipo de atención al cliente."'
$return['error'].' - Error al introducir el nombre de usuario o contraseña'
);
Response::redirect('auth/login');
return null;
}
} else {
Session::set_flash(
}else{
\Session::set_flash(
'message:error',
'Para entrar en tu cuenta tienes que introducir tu email y contraseña.'
);
}
Response::redirect('auth/login');
return null;
}
}
public function get_logout()
{
......@@ -128,22 +96,22 @@ class Controller_Login_Index extends Controller{
Response::redirect('/');
}
public function get_recover(){
public function get_recover()
{
$view = View::forge('recover.twig');
return Response::forge ($view);
return Response::forge($view);
}
public function post_recover()
{
$usuario = Model_Auth_User::query()
->where('user',Input::Post('username',''))
->where('user', Input::Post('username', ''))
->related('group')
->get_one();
if(isset($usuario) && $usuario->valid == 1)
{
if (isset($usuario) && $usuario->valid == 1) {
$view = \View::forge("emails/pedidos/adminResend");
$view->user = $usuario->user;
......@@ -155,54 +123,42 @@ class Controller_Login_Index extends Controller{
$error = false;
//Preparar envio
try
{
try {
$transport = Swift_SmtpTransport::newInstance($comu_session['smtp'], $comu_session['port'], 'tls')
->setUsername($comu_session['user'])->setPassword($comu_session['password']);
$mailer = Swift_Mailer::newInstance($transport);
}
catch(Exception $e)
{
Log::error('Error Enviando correo1 - >'. $e->getMessage());
} catch (Exception $e) {
Log::error('Error Enviando correo1 - >' . $e->getMessage());
$error = true;
}//endCatch
//Enviar Correo
if (!$error)
{
try
{
if (!$error) {
try {
$message = Swift_Message::newInstance("Recuperación de contraseña")
->setFrom(array ($comu_session['emailfrom'] => $comu_session['emailfrom']))
->setFrom(array($comu_session['emailfrom'] => $comu_session['emailfrom']))
->setBody($body, 'text/html');
$message->setTo(array ($comu_session['email'] => $comu_session['email']));
$message->setTo(array($comu_session['email'] => $comu_session['email']));
$mailer->send($message);
}
catch(Exception $e)
{
Log::error('Error Enviando corre2 - >'. $e->getMessage());
} catch (Exception $e) {
Log::error('Error Enviando corre2 - >' . $e->getMessage());
$error = true;
}//endCatch
}//endIf
if ($error)
{
Session::set_flash('msges.error',array('Error enviando correo.')); //Enviar Notifys!!!
}
else
{
Session::set_flash('msges.ok',array('Correos enviados correctamente.'));
if ($error) {
Session::set_flash('msges.error', array('Error enviando correo.')); //Enviar Notifys!!!
} else {
Session::set_flash('msges.ok', array('Correos enviados correctamente.'));
}//endIf
Response::redirect('/');
}
else
{
} else {
//notificar Usuario no valido
Response::redirect('recover');
......
<?php
/**
* Created by PhpStorm.
* User: Villa
* Date: 03/12/2018
* Time: 16:21
*/
trait Trait_InutraliaWS {
public function save_token_credentials ($token_auth){
\Session::set('token_auth',$token_auth);
}
public function get_header(){
return array(
'Content-Type: application/json',
'Accept: application/json',
'Authorization: Basic '. \Session::get('token_auth')
);
}
/**
* Method to make requests to inutralia.
*
* MORE INFO CURL --> http://php.net/manual/es/function.curl-setopt.php
*
* @param $parameter_url
* @param bool $header
* @param int $timeout
* @param bool $httpget
* @param int $return_transfer
* @return mixed
*/
public function request_generic($parameter_url, $header = false, $timeout = 30, $httpget = true, $return_transfer = 1){
$constant = \Config::load('constants');
// La url la obtiene de config dependiendo del entorno.
$process = curl_init($constant[$parameter_url]);
curl_setopt($process, CURLOPT_HTTPHEADER,$this->get_header());
curl_setopt($process, CURLOPT_HEADER, $header);
curl_setopt($process, CURLOPT_TIMEOUT, $timeout);
curl_setopt($process, CURLOPT_HTTPGET , $httpget);
curl_setopt($process, CURLOPT_RETURNTRANSFER, $return_transfer);
$return = curl_exec($process);
curl_close($process);
return $return;
}
/**
*
* User auth basic request for login, save the user token in session for all requests.
*
* @param $user
* @param $password
*/
public function ws_user($user,$password){
$this->save_token_credentials(base64_encode("$user:$password"));
return json_decode($this->request_generic('user'));
}
/**
* Request get profile
*/
public function ws_profile(){
return json_decode($this->request_generic('profile'));
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 23/07/2015
* Time: 14:03
*/
class Controller_Uploadfile
{
/**
* @desc: Sube a carpeta temporal correspondiente el archivo para que quede pendiente de subir
* @param $id
* @param $path
* @return string
*/
public function upload_pagos_file($id, $path)
{
// Configuracion del fichero
$config = array(
'path' => DOCROOT . "files/$path/" . $id,
'randomize' => false,
);
$config['path']= str_replace('\\','/',$config['path']);
// Procesa el archivo subido
Upload::process($config);
Log::error("PATH UPLOAD". $config['path']);
// si no hay ficheros erroneos, guarda el fichero de acuerdo con la configuracion
if (Upload::is_valid()) {
Upload::save();
$file = Upload::get_files();
// ubicación del fichero con el nombre asignado.
$uploaded_file = $file[0]['saved_to'] . $file[0]['saved_as'];
} else
$uploaded_file = 'error';
return $uploaded_file;
}
/**@desc: Guarda en el modelo de datos la direccion y el ID del archivo
* @param $path
* @return mixed
* @throws Exception
*/
public function saveFile($path, $id)
{
if($path=="compraventa"){
$file = Model_CompraventaDocumento::forge();
}else{
$file = Model_ContratoDocumento::forge();
}
$filePath = $this->upload_pagos_file($id, $path);
$filePath= str_replace('\\','/',$filePath);
Log::error("despuesd de guardar $filePath");
$filePath= explode("/",$filePath);
if(sizeof($filePath)<=0){
Log::error("Ocurrio un error relacionado con el path al guardar");
return false;
}
$filePath= $filePath[sizeof($filePath)-1];
Log::error("PATH=>$filePath ");
$file->ds = $filePath;
if($path=="compraventa"){
$file->compraventa_id = $id;
}else{
$file->contrato_id = $id;
}
$this->path = $filePath;
$file->save();
$ret['id'] = $file->id;
$ret['path'] = $file->ds;
return $ret;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: Villa
* Date: 04/12/2018
* Time: 10:45
*/
/* Structure -- > http://i20.inutralia.com/api/v1/{0}?api-key=7745289b-f09c-4e0b-89d1-bb59c599c85e"
Donde {0} puede ser :
- user -> Method get
- generic( id = null) -> Method get
- article(id = null) -> Method get
- profile -> Method get/put
- menu -> Method get
- options -> Method get
- recipe(id = null) -> Method get
- recipes -> Method get
- trivial -> Method get
- video -> Method get
*/
// Url redirect a DEL SUPER --> "https://delsuper.es/inutralia?ids=";
const DOMAIN = "http://inutralia20back";
const V1 = '/api/v1/';
const APIKEY = "?api-key=7745289b-f09c-4e0b-89d1-bb59c599c85e";
// PARAMETERS
const USER = 'user';
return array(
'user' => DOMAIN.V1.USER.APIKEY,
);
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: Villa
* Date: 04/12/2018
* Time: 10:45
*/
/* Structure -- > http://i20.inutralia.com/api/v1/{0}?api-key=7745289b-f09c-4e0b-89d1-bb59c599c85e"
Donde {0} puede ser :
- user -> Method get
- generic( id = null) -> Method get
- article(id = null) -> Method get
- profile -> Method get/put
- menu -> Method get
- options -> Method get
- recipe(id = null) -> Method get
- recipes -> Method get
- trivial -> Method get
- video -> Method get
*/
// Url redirect a DEL SUPER --> "https://delsuper.es/inutralia?ids=";
const DOMAIN = " http://i20.inutralia.com";
const V1 = '/api/v1/';
const APIKEY = "?api-key=7745289b-f09c-4e0b-89d1-bb59c599c85e";
// PARAMETERS
const USER = 'user';
return array(
'user' => DOMAIN.V1.USER.APIKEY,
);
\ No newline at end of file
......@@ -675,3 +675,9 @@ INFO - 2018-11-27 17:11:07 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2018-11-27 17:11:10 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "dashboard"
INFO - 2018-11-27 17:11:10 --> Fuel\Core\Request::execute - Called
INFO - 2018-11-27 17:11:10 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2018-11-27 17:36:02 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = ""
INFO - 2018-11-27 17:36:02 --> Fuel\Core\Request::execute - Called
INFO - 2018-11-27 17:36:02 --> Fuel\Core\Request::execute - Setting main Request
INFO - 2018-11-27 17:36:03 --> Fuel\Core\Request::__construct - Creating a new main Request with URI = "assets/img/logos/logo_seti_50x50_black_orange"
INFO - 2018-11-27 17:36:03 --> Fuel\Core\Request::execute - Called
INFO - 2018-11-27 17:36:03 --> Fuel\Core\Request::execute - Setting main Request
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment