Tank Auth forgot password does't work - codeigniter

I use CodeIgniter + Tank Auth. Only the code http://localhost/XXXXXXXX/auth/forgot_password doesn't work.
The result always is:
"Your activation key is incorrect or expired. Please check your email again and follow the instructions."
The registration and activation are all right.

Some likely problems:
Cookies are not being set correctly. Check your cookie settings, and do a test to make sure you can set and read cookies. (this may be invalid if cookies are not used for the reset)
The reset password key is expired or wasn't set correctly. Check the database to see if hte value is correct before following the link, and check your $config['forgot_password_expire'] in Tank Auth.
You may be linking to the wrong URL in your email.
This doesn't look right:
http://localhost/XXXXXXXX/auth/forgot_password
It should be something like:
http://localhost/auth/forgot_password/XXXXXXXX
Not to discourage you from using Tank Auth, but having used it I can recommend trying Ion_Auth if you are still in the early stages. I believe it's used in PyroCMS as well if that adds any credit.

If the XXXXXXXX in your URL is indicating that you have an extra URI segment before /auth/, you should change this:
function reset_password()
{
$user_id = $this->uri->segment(3);
$new_pass_key = $this->uri->segment(4);
to this:
function reset_password()
{
$user_id = $this->uri->segment(4);
$new_pass_key = $this->uri->segment(5);
Note the different numbers in $this->uri->segment(). With an extra segment before /auth/, your user id and activation code will be passed as parameters in the 4th and 5th segment (rather than the 3rd and 4th that Tank Auth assumes).

it could be the time stamp in your database
in user model function "can_reset_password"
uses a UNIX_TIMESTAMP(new_password_requested)
you could echo $user_id and $new_pass_key if they are correct then the problem is with time comparison.
to fix the the url to always get the last two segments
$break =$this->uri->total_segments();
$new_pass_key= $this->uri->segment($break);
$user_id= $this->uri->segment($break-1);
for the time stamp try this for the function reset_password in users model
function reset_password($user_id, $new_pass, $new_pass_key, $expire_period = 900)
{
$this->load->helper('date');
$this->db->set('password', $new_pass);
$this->db->set('new_password_key', NULL);
$this->db->set('new_password_requested', NULL);
$this->db->where('id', $user_id);
$this->db->where('new_password_key', $new_pass_key);
$this->db->where('UNIX_TIMESTAMP(new_password_requested) >=',mysql_to_unix( time() - $expire_period));
$this->db->update($this->table_name);
return $this->db->affected_rows() > 0;
}

In the main index.php, you have to define a time zone. Example:
date_default_timezone_set('Europe/Paris');
this will ensure that the following check has all the dates with the same time zone
$this->db->where('UNIX_TIMESTAMP(new_password_requested) >', time() - $expire_period);

Related

Next Page Token

I have a php program that must read analytics data and save these data to a DB. Because the data is too big, I use the pagination (10000 to be more specific). As I run the code over and over again, sometimes I get the next page token, sometimes not. The problems it is a one-time-run program. I wonder what I'm doing wrong, here's the code:
do {
$body->reportRequests[0]->setPageToken($token);
$data = $analytics->reports->batchGet( $body );
$token = $data->reports[0]->getNextPageToken();
$this->printResults($data);
} while ( $token != '' );
The searching result was right, ScottMcC. I don't understand about analytics, so I forgot to filter in the sales report and check the results there are the same in the api return.

Laravel: Global query variable?

I have a query which I use all over my routes.php under almost every get request and also use the results in many of my views. It makes more sense at this point for me to call the query once and be able to use it globally without ever having to call it again.
Here's the query:
$followers = Follower::where('user_id', '1')
->get();
How can I do this?
Why not just execute the query once in an init function and store the result into a global variable?
global $followers = Follower::where('user_id', '1')
->get();
you can store it to the session every time the user logs in
Like this exemple
$followers = Follower::where('user_id', '1')
->first();
Session::put('followers', 'value');
whenever you want that you can access it like this
$value = Session::get('followers');
The another answer with session is a simple solution but
I would suggest you to use Laravel Cache for this purpose (because this is the standard practice).
The Laravel Cache::remember accepts three parameters.
key: make an md5 key of 'followers' and 'user id'
time: time in minutes you want to cache the values (depending how frequently your values will be changed)
A closure function which runs when no value is found corresponding to the key. (this method will query once, in this case, and store the value in your cache)
Just do the following in your BaseController's constructor:
$id = 1; //User id
$key = md5('followers'.$id);
$minutes = 60; //cache for 1 hour, change it accordingly
$followers = Cache::remember($key, $minutes, function() use ($id) {
return Follower::where('user_id', $id)->get();
});
Now of course to use Cache you need to use some Cache driver like Redis.
If you don't have how to setup it Read my other answer.
Though it may be little longer solution for your problem, and may take you 15-20 min to set up and run everything, but believe me once you start using cache you will love it.

Session variable on refresh

I have laravel controller like this:
public function postSessionTopic() {
$article_id = Input::get('article_id', 0);
$comment_id = Input::get('comment_id', 0);
\Session::set('page_topic_id', $article_id);
\Session::set('page_comment_id', $comment_id);
\\comment - I have tried \Session::put too, but that doesn't change anything
}
I use it, when user click on a article. I print_r out my session variable in this controller and everything looks fine. But after that I refresh my page, and there I read value from session, and sometimes it load old value or doesn't load anything. I can't understand why, because in controller i can see, that correct value is saved!
In my page, i get that value like this:
\Session::get('page_topic_id', 0)
Probably you do something wrong. You should make sure that in both cases you uses exactly same domain (with or without www).
In this controller when you don't have any input you set to session variables 0. This can also be an issue if you launch this method when you don't have any input.
You could try with adding this basic route:
Route::get('/session', function() {
$page_topic = Session::get('page_topic_id', 1);
$page_comment = Session::get('page_comment_id', 1);
echo $page_topic.' '.$page_comment.'<br />';
$article_id = $page_topic * 2;
$comment_id = $page_comment * 3;
Session::set('page_topic_id', $article_id);
Session::set('page_comment_id', $comment_id);
});
As you see it's working perfectly (but you need to remove session cookie before trying with this path).
You get
1 1
2 3
4 9
8 27
and so on. Everything as expected
Answer was - two ajax at one time. Don't do that, if you store something in session.
The session in Laravel doesn't consider changes permanent unless you generate a response (and that's the result of using symphony as it's base). So make sure your app->run() ends properly and returns a response before refreshing. Your problem is mostly caused by a die() method somewhere along your code or an unexpected exit of PHP instance/worker.
This is probably not your issue but if you are storing your laravel session in the database their is a limit on how large that value can be. The Laravel session migration has a field called "payload" that is a text type. If you exceed the limit on that field the entire session gets killed off. This was happening to me as I was dynamically adding json model data to my session.
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->unique();
$table->text('payload');
$table->integer('last_activity');
});
How much UTF-8 text fits in a MySQL "Text" field?

Checking if specific user is online through php session variable

I'm currently trying to display all online users on my webpage using the php session variables. To do this, whenever a user logs in or out, a column in a database gets set to "online" or "offline".. However this doesn't entirely work since the database doesn't get updated when the user closes their browser (and therefor destroys the session).
So is there another way of checking if a certain sessionid is set??
Currently I am setting the session like this:
session_start();
$_SESSION['username']="Example Username";
To check from the current users page if there is a session variable set we can simply use:
if(isset($_SESSION['username']))
{
//username is set
}
But if we need to check if a specific user is online, how do we get for instance an array of all the session variables that have been set? e.g.
//Get all $_SESSION['username'] vars
//loop through array and check for specific $_SESSION
for($i=0; ... )
{
if( $_SESSION['username'][$i] == "User 1" )
{
//do something
}
}
From all that I've read so far, there doesn't seem to be a way to get an array of all sessions on your page..
So is there a better way of doing it, e.g. how do facebook, twitter, etc handle this stuff?
Thanks for your help!
One solution is to store a timestamp in your database in addition to the online/offline flag that records the last time a user accessed any of your website resources. Then you might just consider them offline after 15 minutes or some other constant value.
The other solution is to play with the callbacks here http://php.net/manual/en/function.session-set-save-handler.php where I think you can handle the gc callback and set the offline flag in your database.
If you search on that page for class SessionDB or go here it looks like somebody has implemented some version of this already in a custom class!
you can use a simple update query
for example you have a table users and in that you have a column called status(online/offline)
on your login.php use
<?php
//your user verification code
if(variable that holds your sql query){
$user_status=('UPDATE user SET status= online WHERE email="'your user email selector'")
}
then on the logout do a similar script just change the online value to offline
You could try this:
foreach ($_SESSION as $sessionKey => $sessionValue)
{
if( $sessionKey == 'username' ) && ( $sessionValue == 'User 1' )
{
//do something
}
}

How do I create, write, and read session data in CakePHP?

can anyone give me an example on how to create Sessions and write data to it. I've seen syntax on how to write data to a session using write command. But how to create a session and retrieve the values in it.
In my application, I have two data, form_id and user_id that needs to be used in all the page requests. So how do I save it as a session variable and use it across the application?
EDIT
function register()
{
$userId=$this->User->registerUser($this->data);
$this->Session->write('User.UserId',$userId);
//echo "session".$this->Session->read('User.UserId');
$this->User->data=$this->data;
if (!$this->User->validates())
{
$this->Flash('Please enter valid inputs','/forms' );
return;
}
$this->Flash('User account created','/forms/homepage/'.$userId);
}
How to use the session variable 'User.UserId' instead of $userId in $this->Flash('User account created','/forms/homepage/'.$userId);
And can I use this variable in all my view files,because in all the page requests I also pass the userId?
EDIT 2
I have 2 controllers,user and form. I write the userid to a session variable in the users_controller. I have a view file called homepage.ctp,whose action is in the forms_controller. Now how can I use the session variable defined in the users_controller in the homepage? Sorry if I am asking silly questions. I went through the cakebook,but my doubts weren't cleared. I'm also trying trial and error method of coding,so please help me.
EDIT 3
I have a session variable 'uid' which is the user id in the home page action of a controller.
$this->Session->write('uid',$this->data['Form']['created_by']);
I need the same variable in the design action method of the same controller.
When I give
$uid=$this->Session->read('uid');
echo "uid: ".$uid;
the value is not echoed.
Can't I use the session variable in the same controller?
The bakery is your best friend:
http://book.cakephp.org/view/398/Methods
All your session read/writes belong in the controller:
$this->Session->write('Person.eyeColor', 'Green');
echo $this->Session->read('Person.eyeColor'); // Green
In cake php you can create session like this
$this->request->session()->write('user_id', 10);
and you can read session value like this
echo $this->request->session()->read('user_id');
Super Simple!
You don't have to write any code to create session, they are already built in. Then you just use the read and write sessions as mentioned above. Also see here for more details:
http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html
Used in Controllers
http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html
Used in Views
cakephp 4 example of session usage in controllers, views and cells
$session = $this->request->getSession();
$session->write('abc', 'apple');
echo $session->read('abc');
In this case it would be:
$this->Flash('User account created','/forms/homepage/'.$this->Session->read('User.UserId'));
and your second question is anwered by Jason Miy (http://api.cakephp.org/class/session-helper). You can simply use this in your view:
$userId = $session->read('User.UserId');
Reading the appropriate cookbook pages slowly and carefully usually helps a lot...
I found out the reason why the uid wasn't being echoed(edit 3 part of the question).
It is due to a silly mistake, had a white space after the end tag ?> in the controller. Now it is working fine.
when I have strange session behavior, and this help me.
MODEL:
function clearAllDBCache() {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$db->_queryCache = array();
}
`
Acess your Helper SessionHelper in lib/Cake/View/Helper/SessionHelper.php and add the method:
public function write($name = null) {
return CakeSession::write($name);
}

Resources