verifyIdToken works one time and fails another time - php

I'm trying to implement google sign-in to on my website.
I've done the steps from here Authenticate with Google.
This function executes after i have logged in to google :
function onSignIn(googleUser) {
var googleResponse = googleUser.getAuthResponse();
google_login(googleResponse, true);
};
Google_login function:
function google_login(res) {
var httpObject = getXMLHTTPObject();
var ajax_url = siteURL + 'google_login';
var params = 'token='+encodeURIComponent(res.id_token);
httpObject.open('POST', ajax_url, true);
httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpObject.onreadystatechange = function() {
if (httpObject.readyState == 4) {
if(httpObject.responseText == 'true') {
window.location = httpObject.responseURL;
}
else {
if(httpObject.responseText == '') {
window.location = siteURL + 'login_again';
}
else {
window.location = siteURL + 'google_login_error';
}
}
}
};
httpObject.send(params);
}
And in my model I'm using this code:
private $google_client;
function Google_model() {
parent::__construct();
$this->google_client = new Google_Client(['client_id' => 'my_client_id','client_secret' =>'my_client_secret']);
}
function check_google_user($access_token) {
$payload = $this->google_client->verifyIdToken($access_token);
if ($payload) {
return $payload;
}
return false;
}
In my controller I'm calling check_google_user function.
And here appears a strange behaviour. Sometimes when I try to login I get the payload, and sometimes not (PS: I'm trying to login with the same user in the same day). Am I doing something wrong?
EDIT:
I'm getting this error: Caught exception: Cannot handle token prior to 2017-01-25T16:20:24+0200

Solved this by commenting these lines in firebase JWT.php file:
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
);

Related

Insert into members not working

I have a script running and working, however the insert into members part don't work:
function register_member($username,$name,$email,$password) {
$time = time();
$ip = get_ip();
db()->query("INSERT INTO members (full_name,username,email,password,ip_address,last_active,date_created,banned,active)VALUES(?,?,?,?,?,?,?,?,?)",
$name,$username,$email,$password, $ip, $time, $time,0,1);
//login user
login_user($username, $pass, false);
if (config('auto-follow', '')) {
$users = explode(',', config('auto-follow'));
foreach($users as $user){
$user = get_user($user);
if ($user) {
follow($user['id']);
}
}
}
return true;
}
It seems for me that it can't read the db()->query ("INSERT INTO part. When I remove that query, the signup script can complete reading the function, but if I leave it in, it returns a 500 internal error. Any ideas?
Finally got the php.ini to change, and it is in the js script the error is happening. On this line here: var json = jQuery.parseJSON(result);
$(document).on("submit", "#signup-form", function() {
$(".loader-container").fadeIn();
$(this).ajaxSubmit({
url : baseUrl + 'signup',
success : function(result) {
var json = jQuery.parseJSON(result);
if (json.status == 1) {
//we can redirect to the next destination
window.location.href = json.url;
notify(json.message, 'success');
} else {
notify(json.message, 'error');
$(".loader-container").fadeOut();
}
}
})
return false;
});

Cart doesn't update after changing quantity

I am making a cart system using PHP and AJAX. Everything works pretty fine, except for the updating part. When the user clicks outside of the number form, the subtotal will update automatically. I used AJAX for this, but doesn't work. I tested this with the search, everything was fine.
AJAX function:
function initXML() { //Adaptation for old browsers
var _xmlhttp;
if (window.XMLHttpRequest) {
_xmlhttp = new XMLHttpRequest();
} else {
_xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return _xmlhttp;
}
function ajaxFormValidate(_config) {
/*Structure
type: 'GET' or 'POST',
url: 'request URL' Default: location.href,
method: true or false (optional). False for non-async, true for async,
sendItem: file or data to be sent,
success: a callback function when the request is complete
error: a fallback function when the request is failed
*/
if (!_config.type) {
_config.type = 'POST'; //Automatically set type to POST if no type property is declared
}
if (!_config.url) {
_config.url = location.href; //Automatically set url to self if no url property is declared
}
if (!_config.method) {
_config.method = true; //Automatically set method to true if no method property is declared
}
var _xmlHttp = initXML(); //Declare request variable
_xmlHttp.onreadystatechange = function(){
if (_xmlHttp.readyState === 4 && _xmlHttp.status === 200) {
if (_config.success) {
_config.success(_xmlHttp.responseText);
}
}
else {
if (_config.error) {
_config.error(_xmlHttp.responseText);
}
}
}; //Check readyState and status to handle the request properly
//Handle the items sent
var _Itemstring = [], _sendItem = _config.sendItem;
if (typeof _sendItem === "string") {
var _arrTmp = String.prototype.split.call(_sendItem, '&');
for (var i = 0; i < _arrTmp.length; i ++) {
var _tmpData = _arrTmp[i].split('=');
_Itemstring.push(encodeURIComponent(_tmpData[0]) + "=" + encodeURIComponent(_tmpData[1]));
}
}
else if (typeof _sendItem === "object" && !(_sendItem instanceof String || (FormData && _sendItem instanceof FormData))) {
for (var k in _sendItem) {
var _tmpData = _sendItem[k];
if (Object.prototype.toString.call(_tmpData) === "[object Array]") {
for (var j = 0; j < _tmpData.length; j ++) {
_Itemstring.push(encodeURIComponent(k) + '[]=' + encodeURIComponent(_tmpData[j]));
}
}
else {
_Itemstring.push(encodeURIComponent(k) + '=' + encodeURIComponent(_tmpData));
}
}
}
_Itemstring = _Itemstring.join('&');
if (_config.type === 'GET') {
_xmlHttp.open('GET', _config.url + "?" + _Itemstring, _config.method);
_xmlHttp.send();
}
else if (_config.type === 'POST') {
_xmlHttp.open('POST', _config.url, _config.method);
_xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
_xmlHttp.send(_Itemstring);
}
}
AJAX called inside a JS file handling the changes in the inputs
// JavaScript Document
window.addEventListener('load', function(){
var _ranum = document.getElementsByClassName('ranum');
for (var i = 0; i < _ranum.length; i ++) {
_ranum[i].addEventListener('blur', function(){ //Check click outside
var _this = this;
ajaxFormValidate({
type:'POST',
sendItem: {
u: _this.value, //Send the value after the change
id: _this.id, //Send the product id
},
success: function(response){
console.log('SUCCESS');
}
});
}, false);
}
}, false);
Handling the changes in PHP file
var_dump($_POST['u']);
if (isset($_POST['id'], $_POST['u'])) {
if (!empty($_POST['id']) && !empty($_POST['u'])) {
$id = mysqli_real_escape_string($conn, $_POST['id']);
$u = mysqli_real_escape_string($conn, $_POST['u']);
if (isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id] = $u;
}
}
}
I see the it logged out 'SUCCESS' in the console, however, when I use var_dump($_POST['u']) it doesn't work. Also, it updates the subtotal only if I reload the page.
What did I do wrong? I pretty sure my AJAX function is correct, and JS logged out 'SUCCESS', so what's the problem? Thanks very much

ajax call failed to give response in wordpress

hai im working in wordpress the simple concept is if the changing password if the user enters the existing password wrong need to alert the user im trying it with json message, response is receiving as undefined unable to parse the data from response.
function choice_update_password(){
global $wpdb;
$old_password=$_REQUEST['old_password'];
$N_password=$_REQUEST['new_password'];
$user = wp_get_current_user();
$encrypt_pass= $user->data->user_pass;
if ($user && wp_check_password( $old_password, $user->data->user_pass, $user->ID) ) {
wp_set_password($N_password, $user->ID);
$url="profile";
$view_profile=site_url($url);
echo json_encode(array("type"=>"success","data"=>"","url"=> $view_profile));
die();
}else{
echo json_encode(array("type"=>"failure","data"=>""));
die();
}
}
and the ajax part
function mail_prop_update($clsfrm) {
var $form = jQuery($clsfrm),$dataType = "json";
$form.on('click', 'input[type=submit]', function(e) {
var $elements = $form.find('input:not(input[type="submit"],input[type="button"],input[type="hidden"],input[type="file"],input[type="text"].not-required),textarea#message');
var $bool = $elements.validate();
var email = $form.find('input[type="email"]').val();
var action = $form.find('input[name="action"]').val();
if ($bool) {
ajax_submit($form, $elements, $dataType);
}
alert(e.responseText.type);
e.preventDefault();
});
}

need to run long taking task in php

In a commercial project I need to periodically monitor SMTP and Accounting servers to see if its running and working properly.
if its dead update a table in mysql.
I cant install any 3rd party app on server hosting php script or use exec or modify php settings through php_ini_set
each task takes about 10 to 30 seconds
I tried to run tasks through Jquery ajax calls
and it worked , but the problem is when the jquery request is running you cant navigate to any other page and xhr.abort(); is not working , and stucks on loading until jquery task finishes.
This is what i tried in my js file
var monitor_running = false;
var xhr;
function monitor() {
if (document.readyState === "complete") {
if (monitor_running === false) {
monitor_call();
}
else {
console.log("jobs Already running ===>");
}
}
}
window.onbeforeunload = function () {
console.log(xhr);
xhr.abort();
alert(xhr.status);
};
setInterval(monitor, monitor_interval * 1000);
function monitor_call() {
monitor_running = true;
console.log("jobs running");
xhr = $.ajax({url: './ajax.php',
data: {
cmd: 'monitor'
},
type: 'post',
async: true,
success: function (output) {
monitor_running = false;
console.log(output + " job is finished");
}
});
}
and in php page :
<?php
include_once '../includes/config.php';
$tpl_obj = new template('admin');
$navigation_obj = new navigation();
$auth = $navigation_obj->admin_is_auth();
if (!$auth) {
die('Auth Failed !');
}
function monitor() {
sleep(10);
echo 'done';
// $monReport['acc'] = monitor::domon('acc');
// $monReport['smtp'] = monitor::domon('smtp');
// $monReport['payment'] = monitor::domon('payment');
// $monReport['dns'] = monitor::domon('dns');
// return json_encode($monReport);
}
$cmd_post = filter_input(INPUT_POST, 'cmd');
$cmd_get = filter_input(INPUT_GET, 'cmd');
if ($cmd_post == 'monitor') {
echo monitor();
}

login auth check keeps returning false in laravel 4

I'm creating a login system in laravel. On my local server, the code works but when I put it on a live server, the Auth::check() keeps return false and thus when I login with the right credentials it redirects me back to login page again. FYI My liver server is using php 5.4 while my local server is using php 5.5
Here is my code.
routes.php
Route::get('/', function() {
//Auth::check() KEEPS RETURNING FALSE EVEN WHEN USER LOGS IN
if (Auth::check() == true) {
$role = Auth::user()->role;
if ($role == 1) {
return View::make('administrator');
} elseif ($role == 9) {
return View::make('agent');
}
} else {
return View::make('login');
}
});
LoginController.php
public function login() {
if (Auth::attempt(array('username' => Input::json('username'), 'password' => Input::json('password')))) {
return Response::json(Auth::user());
} else {
return Response::json(array('flash' => 'Invalid email or password'), 500);
}
}
}
angularcontroller.js
$scope.login = function() {
//assign variables
var post = {};
post.username = $scope.info.username;
post.password = $scope.info.password;
//Validation
var errors = 0;
if (errors == 0) {
loginServ.login(post).then(function(data) {
if (data.status == 500) {
alert('wrong username or password');
} else {
window.location.replace("");
}
});
}
};
angular_service.js
login_module.factory('loginServ', function($http, $q) {
return {
login: function(post) {
var url = "login/login";
return $q.all([
$http.post(url, {
username: post.username,
password: post.password
})
])
.then(function(results) {
var data = [];
angular.forEach(results, function(result) {
data = data.concat(result.data);
// console.log("data: "+result);
// console.log("result.data: "+result.data);
});
return data[0];
},
function(error) {
console.log(error.status);
return error;
// Handle error here
});
}
}
});
I have login form using angularjs. It sends a POST request and if it gets a 200 response then it sends a GET request to "/". However even with right login credentials it keeps going back to the same login page.
Thanks
Try to change the value in app\config\session.php => 'cookie'.
This should fix the issue

Categories