Cookie is not being deleted - session

I've seen other questions of this problem, but nothing solved my problem:
I'm using cakephp, the code for setting/unsetting cookies is on AppController -> beforeFilter() to make sure it works correctly (is going to be the first portion of code to be executed before the actual page)
Let's see... for the login:
if($data['check'] == 'on')
$_SESSION['cookieActivation'] = 0;
$this->redirect(array('controller' => 'info', 'action' => 'index'));
For beforeFilter()
session_start();
//Esto es para eliminar la cookie, si la hay, y también sacar la sesión (deslogear)
if (isset($_SESSION['cookieRemoval']))
{
if (isset($_COOKIE['user'])) //está la cookie, en primer lugar?
{
unset($_COOKIE['user']);
setcookie('user','',1);
}
unset($_SESSION['cookieRemoval']);
}
//esto se setea si el tipo puso recordar contraseña en el login de dreyfus, se hace acá porque
//es el lugar correcto para setear la cookie, si se intenta hacer después, no funciona
if(isset($_SESSION['cookieActivation']))
if($_SESSION['cookieActivation'] == 0) //cero significa que quiere setear cookie porque todavía no lo hizo...
{
//si quiere que recuerden su login, hacemos una cookie
//va a expirar en 30 días... 3600 es una hora....
$_SESSION['cookieActivation'] = 1;
setcookie('user','pass',time()+(3600*30*24));
}
for logout
$_SESSION['cookieRemoval'] = 1; //avisa a appcontroller que quiere borrar la cookie de sesión...
$this->redirect(array('controller' => 'info', 'action' => 'login'));
Ok, that's a lot of code, let me explain it a bit:
If you do login, it sets a session variable to state that you want to set a cookie.
Then in it goes to beforefilter, it checks that you actually want to set a cookie, and it sets it for 30 days.
when you do logout, a session variable is created to specify that you want to remove the cookie, then it goes to beforefilter and then it detects that session variable and removes the cookie.
It works well, it redirects to a login page and with a printr the results are that I no longer have the cookie set... BUT, if I do F5 or close the browser and open the page again... the cookie is still there.
Any... tips here?

I solved this problem by being extra specific when setting the cookie, like this:
Create cookie:
setcookie('user','pass',time()+(3600*30*24), '/', $_SERVER['SERVER_NAME']);
Delete cookie:
setcookie('user','',1, '/', $_SERVER['SERVER_NAME']);
I basically added those last two fields...

Related

JWT - Verify Token given a public key

I need to create a Rest API that receives a JWT token and I need to validate it with a given public key.
"They must validate the "Bearer Token" sent in the header of
requests using a public key provided according to the environment, as well as verifying the
scope user availability. Consult "
The public key:
http://desenv.authenticador.sp.gov.br/.well-known/jwks
I tried using DoVerify() but I don't know where to enter the public key.
&token = &HttpRequest.GetHeader('Authorization')
if not &token.IsEmpty()
&token = &token.Replace("Bearer ", "")
&result = &JWTCreator.DoVerify(&token, JWTAlgorithm.RS256, &privateClaims, &JWTOptions)
if &result
&mensagem = 'token is valid'
else
&mensagem = "token is NOT valid"
If &JWTCreator.HasError()
&codigo = &JWTCreator.GetErrorCode().ToNumeric()
&mensagem = &JWTCreator.GetErrorDescription()
EndIf
endif
else
&codigo = 401
&mensagem = "Token not found!"
endif
Any suggestions?
Thanks
If you already have a token, use that in jet.io to encode the first part of the key. Is the jwt token created by your application? - if so then you probably might have included a public key in the first part of the jwt token.
Load the certificate using the Certificate type. The function will depend on the format of the cert.
Then, add it to the JWTOptions
Also, it looks like the DoVerifyJustSignature is the function you want to use in that case.
I solved this problem as follows:
A procedure that expects a token and returns a code and a message.
parm(in:&jwt_token, out:&codigo, out:&mensagem);
Source:
&codigo = 0
&mensagem = ''
if not &jwt_token.IsEmpty() and &jwt_token.Contains('Bearer')
&token = &jwt_token.Replace("Bearer ", "")
// capturar o payload do token e o header para comparar com o que temos na chave publica.
&payload = &JWTCreator.GetPayload(&token)
&header = &JWTCreator.GetHeader(&token)
// carregar o payload e header no SDT.
&SDTJWTOptions.header.FromJson(&header)
&SDTJWTOptions.payload.FromJson(&payload)
// Validar se o token é compátivel com a chave publica disponibilizada.
&ChavePub_SDTJWTOptions.header.FromJson('{"typ": "JWT","alg": "RS256","x5t": "vST_OxZ0TJ5w3miLGWJ7xlH8sZo","kid": "vST_OxZ0TJ5w3miLGWJ7xlH8sZo"}')
If (&SDTJWTOptions.header.alg <> &ChavePub_SDTJWTOptions.header.alg) or
(&SDTJWTOptions.header.typ <> &ChavePub_SDTJWTOptions.header.typ) or
(&SDTJWTOptions.header.x5t <> &ChavePub_SDTJWTOptions.header.x5t) or
(&SDTJWTOptions.header.kid <> &ChavePub_SDTJWTOptions.header.kid)
&codigo = 401
&mensagem = "Token Inválido!" // existe um Bearer Token inválido;
Return
EndIf
// Validar se o token está com a data de expiração válida.
// A data do token é em formato UNIX que faz necessário a conversão.
// - Data UNIX inicia em 1/1/1970 as 00:00:00
// - Com a data UNIX formatada, adicionar a expiração em UNIX como segundos.
&Datetime = YMDHMStoT(1970, 1, 1, 00, 00, 00)
&NowDatetime = ServerNow()
&TokenDatetime = &Datetime.AddSeconds(&SDTJWTOptions.payload.exp)
// Valida se o retorno da diferença das datas (atual vs token) é menor que 0,
// indicando que a data de expiração já passou e é inválida.
&Diff = &TokenDatetime.Difference(&NowDatetime)
If &Diff <= 0
&codigo = 401
&mensagem = "Token Expirado!" // existe um Bearer Token válido, porém está expirado;
EndIf
Else
&codigo = 401
&mensagem = "Requisição sem token de autorização" // não encontrado o Bearer Token no header;
EndIf
Return

How to send new direct message through Twitter API https://api.twitter.com/1.1/direct_messages/events/new.json?

I am implementing Twitter new Direct message API,
https://api.twitter.com/1.1/direct_messages/events/new.json
I am facing error,
415 Unsupported Media Type
I am able to call it via TWURL tool and currently I am sending simple text message through it.
From error code, I understand that either there is content-type issue or payload is in incorrect format.
I am passing payload as,
options = {
"event": {
"type": "message_create",
"message_create": {
"target": {
"recipient_id": "1234"
},
"message_data": {
"text": "test"
}
}
}
}
Payload is converted to usual Ruby hash, i.e. :key => "value"
{:event=>
{:type=>"message_create",
:message_create=>
{:target=>{:recipient_id=>"1234"},
:message_data=>{:text=>"test"}}}}
How to preserve third party API request format?
Any suggestion will be great help.
Thanks
Have you tried setting Content-Type ('application/json')? in your content header before sending?
It is one of the most common issues.
You can do so by doing something similar to:
before_filter :set_content_type
def set_content_type
#headers["Content-Type"] = "application/json; charset=utf-8"
end
It will force your application to append the Content-Type on each request.
https://github.com/J7mbo/twitter-api-php/blob/master/TwitterAPIExchange.php
usa la clase TwitterAPIExchange y aplica estos cambios.
Yo lo solucione modificando la clase así:
a la clase TwitterAPIExchange , añade la propiedad
public $appjson;
en public function __construct(array $settings) añade la inicialización.
$this->appjson=false;
en public function performRequest($return = true, $curlOptions = array())
remplaza
$header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:');
por
if ($this->appjson) {
$header = array('Content-Type: application/json',$this->buildAuthorizationHeader($this->oauth), 'Expect:');
} else {
$header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:');
}
para finalizar usa:
.....
$twitter = new TwitterAPIExchange($settings);
......
......
$twitter->appjson=true;
$twitter->buildOauth($url, $requestMethod)
->performRequest(true,
array( CURLOPT_POSTFIELDS => $params)
);
I got similar error and it turned out the data format I was sending the request in was a bit wrong. I was using python requests with the following headers:
HEADERS = {
'Content-type': 'application/json',
'Accept': 'application/json'
}
But still using json.dumps() on the actual data, the request was subsequently inconsistent with bad data, it all worked when I just sent the data without dumps'ing it.
This might not really help but just check your data integrity.

Another Laravel Token Mismatch Exception issue

I have an application which uses AJAX quite a bit on a Laravel 5.3 application. I have some pages that are behind authentication and some that are not. The ones that are inside of authentication are working fine. The one that is outside (public facing) are giving me a the infamous TokenMismatchException in VerifyCsrfToken.php line 68. In order to attach the token to the AJAX header, I am using this...
$.ajaxSetup({
cache: false,
async: true,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
And it is working because when I make a request, I can see this...
...but the tokens are not matching. When I go to the framework file Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class and do a dd() on the session token and the token that was passed, they do not match.
Things I have tried:
Clearing Cache (views, config, cache)
Changing session driver from
file to Redis
Using csrf_field() instead of AJAX headers
I cannot figure out why this is not working. Any other ideas?
If you look at this code of laravel Github Link
/**
* Determine if the session and input CSRF tokens match.
*
* #param \Illuminate\Http\Request $request
* #return bool
*/
protected function tokensMatch($request)
{
$sessionToken = $request->session()->token();
$token = $request->input('_token') ?: $request->header('X-CSRF-TOKEN');
if (! $token && $header = $request->header('X-XSRF-TOKEN')) {
$token = $this->encrypter->decrypt($header);
}
if (! is_string($sessionToken) || ! is_string($token)) {
return false;
}
return hash_equals($sessionToken, $token);
}
It checks for the X-CSRF-TOKEN and also tries to check for X-XSRF-TOKEN. You can also try to send the _token from the ajax. I hope this helps you.
And, I finally figured it out. I am using BrowserSync for livereload, which proxies all my requests to localhost:3000/*. When I was testing the public side, I was visiting it through the original domain name and not proxied through browsersync's localhost:3000 so that was causing session issues.
Basically, if you have BrowserSync running and you try in use your site not through browsersync, you can get token mismatch errors.

codeigniter - send email

I have a CRUD "clientes" and I added a button "email", when I click on it I would like to send an email with a username and a password
here is my button
$crud->add_action('Email', '', 'pendientes/pendientes_v/enviarmail', 'ui-icon-plus');
and then the function in my controller
function copyrows($id)
{
$this->load->model('cliente_model', 'client');
$clientInfo = $this->client->getInfo($client_id);
$this->email->from('myemail#gmail.com', 'Demo');
$this->email->to($clientInfo['email']);
$this->email->subject('Email Test');
$this->email->message('Hola tu usuario es ' . $clientInfo['email'] . ' y tu contraseña es ' . $clientInfo['clave']);
$this->email->send();
echo $this->email->print_debugger();
}
my model cliente_model.php
<?php
class Cliente_Model extends CI_Model{
public function getInfo($client_id){
return array('id' => $cliente_id,'email' => $email,'clave' => $clave);
}
}
here the errors
Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.
From: "Demo"
Return-Path:
Reply-To: "myemail#gmail.com"
X-Sender: myemail#gmail.com
X-Mailer: CodeIgniter
X-Priority: 3 (Normal)
Message-ID: <51478bcb599c0#gmail.com>
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 8bit
=?utf-8?Q?Email_Test?=
Hola tu usuario es y tu contraseña es#gmail.com>#gmail.com>#gmail.com>
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by (output started at /home/oscar/public_html/crud/system/core/Exceptions.php:185)
Filename: core/Common.php
Line Number: 438
I know I am receiving a null value but I can't find the solution, hope someone can help me.
thanks in advance!
i had the same problem and it's a hell, i fixed only using php native:
mail();
instead of using CI mail library
maybe it fixes your problem too

Internet Explorer 6 : Euro sign not displayed on ajax request

i'm using jquery 1.4.2 to send an ajax request to a php page then display the result.
This works fine with FF3 and IE8, but in IE6 the character € is replaced by a square, i tried to force the character encoding of the php page using header() but it didn t work...
I'm working on windows with Zend Studio for eclipse (projet encoding is utf-8)
here is the ajax call :
$.ajax({
url:'index.php?module=ajax&action=getCommande&no-header=1&id='+id ,
cache:true,
success:function(html){
$("#recap_commande").html(html);
}
});
requested page :
<?php
header('Content-type: text/html; charset=utf-8');
echo "Récapitulatif de la demande " . $_GET ['id'] . " (".$this->getTotal($nb["COD_ART"],$nb["COD_OPTION"])." €) ";
?>
Any help will be appreciate.
I would recommend you to avoid concatenating parameters as you did. Use the data hash like this so that jQuery take care of properly encoding url values:
$.ajax({
url: 'index.php',
cache: true,
data: { module: 'ajax', action: 'getCommande', no-header: '1', id: id },
success: function(html) {
$('#recap_commande').html(html);
}
});
Also make sure that your pages are utf-8 encoded.
Sorry, this was a specific computer problem, the euro sign is correctly display on another computer with same OS and IE6 ....
I dont understand where the problem came from , i tried to empty the cache still the same...
when alerting ajax response the € is correctly display, when copy the square character then paste it in notepad i can see the € ! ??
my life will be so much simplier without this stupid ie6!

Resources