I have some troubles with the crsf_token() in laravel. I create a URL to send to the user with the token and if they click this unique link the post will set the token to NULL.
Here my sample code:
//get token from database
$getDataUserToken = $subject->lists('token');
// send the token to email user (unique token)
#foreach ($token as $toke){{ URL::to('/extend/verify', array($toke)) }}#endforeach
This code will generate: www.example.com/extend/verify/1234123TOKENHERE2313213123
Now I want if user clicks on this link that the token sets to null.
I tried this:
Route::get('/extend/verify/{$toke}', 'SubjectController#confirm');
But when I do this I get an error that says: throw new NotFoundHttpException;
So the url is not found and I don't know how to get that url token and send it to my controller to do some stuff with that.
the laravel route parameters not use "$".
this is a correct use:
Route::get('/extend/verify/{toke}', 'SubjectController#confirm');
Related
I am using Django sample JWT and I already set up for the login user. let say now I have a login user token. but at the client-side, we still need to show like user name, user image, and email address. How to get this information in the client-side?
I created a new method that will return current login user at backend=>
#get token for login user
#action(detail=False, methods=['get'])
def get_current_user(self,request):
data = {}
data["username"] = request.user.username
.
.
.
return Response({format(data)})
It's the correct way? or Can I serialize request.user and return directly? Is there any serializer for Auth-User? I am stuck there. Thanks.
If you are going for a basic retrieve of the user,you should create a serializer for the user and a generic view which uses that serializer to return the data
When a user forgets their password and try to reset it, they get a reset password email link with a token:
site.com/my/password/reset/ddc3669ab1bbd78abe620ef910716ae91678bb4beb5cd8896e21efaaa0c9d5c6
On the backend though, the token in the database password_resets table looks like it's hashed:
$2y$10$O6pgU21FhsOcgpgeqR8RReFYoCGhHNBH5bHKxtE6q1tJMTUufrbr.
So when the route is visited, the only piece of identifying information passed is the token:
ddc3669ab1bbd78abe620ef910716ae91678bb4beb5cd8896e21efaaa0c9d5c6
// Controller Method
passwordResetVerifyByToken($token){
$record = DB::table('password_resets')->where('token', $token)
->first();
}
Ofcourse we won't get a record, as the plain token from the email will NOT match the hashed one in the database with the above query. So with the plain emailed token link, when the user clicks it, how can we compare it to the one in the database to verify it exists and is a matching token?
You should use the Hash::check method, which will return true or false depending of if the hash of the reset token matches the stored database value.
if (Hash::check($token, $row->token)) {
// The passwords match...
}
Laravel docs:
https://laravel.com/docs/5.6/hashing#basic-usage
Dont worry Laravel Have there own advanced function Hash you should try this
if (Hash::check($token, $row->token)) {
// write your code or other function
}
When posting a form with a csrf token, $this->input->post("csrf_token") is empty.
I could post a duplicate csrf_token using another field name. But that looks a bit unnecessary.
Is there (another) way to get it?
__
All is done using AJAX. So first of all, a token must be requested, and is provided using a json template, populating it this way:
$data["json"] = array(
"csrf_token" => $this->security->get_csrf_hash()
);
Using that token, a ajax POST request is done, sending user login, password. If ?debugis added to the request url, and the ENVIRONMENT is not production, the complete post request parameters are added to the json output. Like so:
if( !is_null($this->input->get("debug")) && ENVIRONMENT != 'production'){
$debug = TRUE;
$data["json"]["post"] = $this->input->post();
}
And I get:
"post": {
"un": "test",
"pw": "test"
}
Adding $data["json"]["old_token"] = $this->input->post("csrf_token");gives me "old_token": null
The Cross-site request forgery itself, works as expected: no token, wrong token or expired token gives an error. So Codigniter does receive the token as a supposed to. It seems to be removed from the post data.
After some poking around, I've found the answer. The security class removes the token from the POST array: unset($_POST[$this->_csrf_token_name]); (core/Security.php in csrf_verify() at line 234)
I won't change that line, to be sure the controller keeps functioning after updating Codeigniter.
I am working with this package Analytics-Laravel 4 for google analytics and I have follower all of the steps correctly. When I try to get the site id for example, I face this error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'
I have double checked all of the configurations, client id, service_account and private key but the error still occurs.
Anything else I should try to check that maybe would solve this issue?!
I didn't use this package before, I'm using google-api-php-client, but anyways, this error occurs if you don't set the refresh token.
You should know that you need to have the access token ONLY once. You also need to set the access type to be offline, which will provide you with a refresh token that you will use to automatically get a new access token without getting a new code every time your access token expires.
In google's console, I created a Client ID for web application. Make sure you set the redirect URI to your web page where you will receive the code and will extract the access token using that code.
Here is a code example using google-api-php-client, I hope it will help:
You need to run the following code only once, and retrieve and store the access token.
<?php
require_once('google-api-php-client-master/src/Google/Client.php');
session_start();
$client = new Google_Client();
$client->setApplicationName('APP_NAME');
$client->setClientId(YOUR_CLIENT_ID);
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('YOUR_REDIRECT_URI');
$client->setDeveloperKey('YOUR_DEV_KEY');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType("offline");
// Step 1: Create an auth url
if (isset($_GET['ref']) && $_GET['ref'] == "1") {
$authUrl = $client->createAuthUrl();
return Redirect::to($authUrl);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_SESSION['code']); //Authenticate the client
$token = $client->getAccessToken(); //Get the access token
var_dump($token); //Store the token in your DB or config file
die();
}
?>
After getting your access token from the code above (which should contain a refresh token), store it in your DB or a config file.
Now the following code should authenticate the client and refresh the access token when it expires via the getAccessToken function
<?php
require_once('google-api-php-client-master/src/Google/Client.php');
require_once('google-api-php-client-master/src/Google/Service/Analytics.php');
$client = new Google_Client();
$client->setApplicationName('APP_NAME');
$client->setClientId(YOUR_CLIENT_ID);
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('YOUR_REDIRECT_URI');
$client->setDeveloperKey('YOUR_DEV_KEY');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType("offline"); //Make sure the access type is offline to get a refresh token
$config = CoreConfig::find(1); //Getting the first record from the config table
$client->setAccessToken($config->google_access_token); //Retrieve the access token that you stored and set it to the client object
//Check this the token is expired
if($client->isAccessTokenExpired()) {
$token = json_decode($config->google_access_token, true); //Get the token stored, and convert JSON to array
$client->refreshToken($token['refresh_token']); //Set the refresh token
$newtoken = $client->getAccessToken(); //Call the getAccessToken() function to get a new access token for you
$config->update(array('google_access_token' => $newtoken)); //Store the new token in your DB
}
if ($client->getAccessToken()) {
$analytics = new Google_Service_Analytics($client);
//Do something with the $analytics object
}
?>
It could be the server time. If the local time on your server is out of sync with google's oAuth server even by a few seconds you'll get that error message.
You can check the time by running "date" in the console.
Running "sudo ntpdate ntp.ubuntu.com" solved it for us.
I am working with AuthSub to view portfolios of google finance api on codeigniter framework.
after successful login of google it redirects to the url we provide.
I have provided url like: www.finance.mysite.com/google/token/
google will append its token like:
www.finance.mysite.com/google/token/?token=1/gyXbtvKT4XaIuUIhEBAsuxyDgATMDk3ztAG3MocNkKI
How can I get it inside a function token() inside google controller.
I don't know that you have control over "how" it gives it to you. For a controller parameter, you'll need to redirect after the Auth callback "gives" you the token. This is probably unnecessary though, as you can simply grab it out of the query string.
<?php
$token = $this->input->get('token');
if ($token)
{
// Option 1: redirect to a controller action that
// takes the token as the parameter
redirect('/google/token/'.$token);
// Option 2: do something directly with the token
// right now (why bother redirecting?)
var_dump($token);
exit;
}
die('Access token? We didn\'t get no access token!');
?>
Storing the token in the session or database is an alternative to the redirect, but the redirect would how to "get the token as parameter to controller" like you ask.
Just extract the token, and route it to controller of your choice.
You can extract the params like this
$params = "http://www.finance.mysite.com/google/token/?token=1/gyXbtvKT4XaIuUIhEBAsuxyDgATMDk3ztAG3MocNkKI";
$parsed = parse_url($params);
$pieces = explode("=", $parsed['query']);
$searchIndex = array_search("token", $pieces);
if($searchIndex) {
$token = $pieces[$searchIndex+1];
//now use it as you need
redirect("controller/google/$token");
}
Note: The code above will only work, if there is only single parameter on the url, or else not.