Problems with cookies / MAMP / CodeIgniter - codeigniter

I'm having a problem with reading cookies on localhost, using MAMP and Codeigniter.
I'm trying to ude a cookie to authenticate acess to an admin area. I can set the cookie (I see it on my browser - Chrome) but i'm not able to read it after doing that to grant the acess. I've already tried lots of configurations, but none works. I really need some help on this.
Those are the essencial parts of my code:
Here I set the cookie
$cookie = array(
'name' => 'login',
'value' => 'true',
'expire' => '0',
'secure' => TRUE
);
set_cookie($cookie);
Here I redirect the user to login page if there is no cookie and to control panel if the cookie is set
function login_redirect() {
$this->load->helper('cookie');
if (uri_string() == 'admin/controlpanel') {
if ($this->input->cookie('login')) {
} else {
redirect('admin/');
}
}
if (uri_string() == 'admin') {
if ($this->input->cookie('login')) {
redirect('admin/controlpanel');
}
}
}
OBS: all this code is in the admin_model
Any tips?
Thanks and sorry about my english. I hope I've made myself clear.

Codeigniter has some problems with the Cookie and Session libraries when run on some localhost configurations. You'll spend hours trying to find out the particular problem with your setup. The best bet is to use generic PHP cookie/session when on localhost and use another library when in testing.
I appreciate that this is by no means the best solution but it's the best advice I can offer.

Related

sessions in cakephp4 vs. cakephp2.3

Currently i am rewriting a cakephp2.3 application in cakephp4+.
in my controller (just for test reasons) I wrote this five lines.
$session = $this->request->getSession();
$session->write([
'TDSPeople.active' => $this->request->getData('active'),
'TDSPeople.filter' => $this->request->getData('filter')
]);
debug($session);
my debug output only shows:
object(Cake\Http\Session) id:0 {
protected _engine => null
protected _started => true
protected _lifetime => (int) 1440
protected _isCLI => false
}
what went wrong?
Do i have to declare that I want to use the session component or is it a configuration problem related to working on my development server without SSL.
Any help appreciated
thx
Thanks to the hidden hint of ndm´s comment the problem ist solved the data is where it should be and all is fine. sorry for the confusion. I´ve tried to access the keys in $session->read (obviously) directly and there it appeared.

how to fix Cookies not setting in laravel 9?

I'm trying to set a httpOnly cookie for token but it's not saving cookie.
I'm trying to login users via OTP and when user entered correct OTP, I'll sign them in app and so far I've done it like below :
$user = User::where('mobile_number', $request->mobileNumber)->first();
if ($user) {
Auth::login($user);
$token = $user->createToken('authToken')->accessToken;
$cookie = cookie('token', $token, 60 * 24 * 24); // 24 day
return response([
'status' => 'success',
'message' => 'loggedIn',
'user' => auth()->user(),
])->withCookie($cookie);
}else{
return response()->json([
'status' => 'success',
'message' => 'notExist'
], 200);
}
User will successfully login and if I refresh the page I should login again, and when I check Application\Storage\Cookies in Firefox and Storage\Cookies in chrome there's no sign of returned cookie(even if I don't refresh the page cookies won't be saved at all).
I'm using Laravel Passport, and so far, i don't think there should be any problem related to VUE side, since cookies not even saving in browser.
I've also tried to add more cookies to just test if everything work, but same problem happened again and nothing saved in browser.
I've also tried other solutions in Stackoverflow but they didn't worked.
Edit 01 : Removed refresh page...
Edit 02 : Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse and Queue tested.
Well, i found it, looks like problem was from VUE side actually. app URL was 127.0.0.1 for default in env file, but in VUE it was calling API via Localhost, and it was working but cookie wasn't saving due to this conflict, and when i changed it to 127.0.0.1 as default baseURL in axios, it worked.
Add cookie name in $except.
/app/Http/Middleware/EncryptCookies.php
Use the Cookie Facade that Laravel provides:
use Illuminate\Support\Facades\Cookie;
Cookie::queue('token', $token, 60 * 24 * 24);
In your Kernel.php, search for AddQueuedCookiesToResponse and uncomment it if it's commented.

The sessions are dying on redirect

The sessions are no longer working on redirect, if i set a session with session([ 'key' => 'value' ]); is working on the same page, but if i set the session in controller, after redirect is NULL, also, when i redirect, the values passed ->with(array) are NULL:
return redirect()->route('account.login', ['subdomain' => 'account'])->with(
[
'request-tfa' => true,
'requested-email' => $validatedData['email'],
'requested-password' => encrypt($validatedData['password'])
]);
When i get the value using Session::get('request-tfa') is NULL, until now, this worked perfectly.
Do anyone have any idea how to fix it?
Should i try to use a database as session storage? but i don't know how to setup the database to store the sessions.
EDIT: I changed the session driver to database and is still not working, but the sessions are stored.
And even \Auth::attempt is not working, like, if i use:
if(\Auth::attempt(['email' => $validatedData['email'], 'password' => $validatedData['password']]))
{
return \Auth::id();
}
it working, but if i have return redirect i am guest again.
EDIT X2
Well, i changed my virtual host domain and restarted my pc and now is working...
If you want to have a session after redirect you should use:
session()->put('something')

Laravel 5 and Socialite - New Redirect After Login

Another newb question here, but hopefully someone can shed some light:
I am using Socialite with Laravel 5, and I want to be able to redirect the user to a page on the site after they have logged in. The problem is that using
return redirect('any-path-I-put-here');
simply redirects back to 'social-site/login?code=afkjadfkjdslkfjdlkfj...' (where 'social-site' is whatever site is being used i.e. facebook, twitter, google, etc.)
So, what appears to me to be happening is that the redirect() function in the Socialite/Contracts/Provider interface is overriding any redirect that I attempt after the fact.
Just for clarification, my routes are set up properly. I have tried every version of 'redirect' you can imagine ('to', 'back', 'intended', Redirect::, etc.), and the method is being called from my Auth Controller (though I have tried it elsewhere as well).
The question is, how do I override that redirect() once I am done storing and logging in the user with socialite? Any help is appreciated! Thank you in advance.
The code that contains the redirect in question is:
public function socialRedirect( $route, $status, $greeting, $user )
{
$this->auth->login( $user, true );
if( $status == 'new_user' ) {
// This is a new member. Make sure they see the welcome modal on redirect
\Session::flash( 'new_registration', true );
return redirect()->to( $route );// This is just the most recent attempt. It originated with return redirect($route);, and has been attempted every other way you can imagine as well (as mentioned above). Hardcoding (i.e., 'home') returns the exact same result. The socialite redirect always overrides anything that is put here.
}
else {
return redirect()->to( $route )->with( [ 'greeting' => $greeting ] );
}
}
... The SocialAuth class that runs before this, however, is about 500 lines long, as it has to determine if the user exists, register new users if necessary, show forms for different scenarios, etc. Meanwhile, here is the function that sends the information through from the Social Auth class:
private function socialLogin( $socialUser, $goto, $provider, $status, $controller )
{
if( is_null( $goto ) ) {
$goto = 'backlot/' . $socialUser->profile->custom_url;
}
if( $status == 'new_user' ) {
return $controller->socialRedirect($goto, $status, null, $socialUser);
}
else {
// This is an existing member. Show them the welcome back status message.
$message = 'You have successfully logged in with your ' .
ucfirst( $provider ) . ' credentials.';
$greeting =
flash()->success( 'Welcome back, ' . $socialUser->username . '. ' . $message );
return $controller->socialRedirect($goto, $status, $greeting, $socialUser);
}
}
I managed to workaround this problem, but I am unsure if this is the best way to fix it. Similar to what is stated in question, I got authenticated callback from the social media, but I was unable to redirect current response to another url.
Based on the callback request params, I was able to create and authenticate the user within my Laravel app. It worked good so far but the problems occured after this step when I tried to do a return redirect()->route('dashboard');. I tried all the flavours of redirect() helper and Redirect facade but nothing helped.
The blank page just stared at my face for over 2 days, before I checked this question. The behaviour was very similar. I got redirect from social-media to my app but could not further redirect in the same response cycle.
At this moment (when the callback was recieved by the app and user was authenticated), if I refreshed the page manually (F5), I got redirected to the intended page. My interpretation is similar to what's stated in this question earlier. The redirect from social-media callback was dominating the redirects I was triggering in my controller (May be redirect within Laravel app got suppressed because the redirect from social-media was still not complete). It's just my interpretation. Experts can throw more light if they think otherwise or have a better explaination.
To fix this I issued a raw http redirect using header("Location /dashboard"); and applied auth middleware to this route. This way I could mock the refresh functionality ,redirect to dashboard (or intended url) and check for authentication in my DashboardController.
Once again, this is not a perfect solution and I am investigating the actual root of the problem, but this might help you to move ahead if you are facing similar problem.
I believe you are overthinking this. Using Socialite is pretty straight forward:
Set up config/services.php. For facebook I have this:
'facebook' => [
'client_id' => 'your_fb_id',
'client_secret' => 'your_fb_secret',
'redirect' => '>ABSOLUTE< url to redirect after login', //like: 'http://stuff'
],
Then set up two routes, one for login and one for callback (after login).
In the login controller method:
return \Socialize::with('facebook')->redirect();
Then in the callback function
$fb_user = \Socialize::with('facebook')->user();
// check if user exists, create it and whatnot
//dd($fb_user);
return redirect()->route('some.route');
It should be pretty much similar for all other providers.
We are using the Socialite login in our UserController as a trait. We simply overrode the AuthenticatesSocialiteLogin::loginSuccess() in our controller.
use Broco\SocialiteLogin\Auth\AuthenticatesSocialiteLogin;
class UserController extends BaseController
{
use AuthenticatesSocialiteLogin;
public function loginSuccess($user)
{
return redirect()->intended(url('/#login-success'));
}
....

remember me functionality in codeigniter

I have implemented remember me functionality as this question
How to create "remember me checkbox" using Codeigniter session library?
first answer.
I created a cookie with a random number code as value and it stored in db(user table). On login, db code checks with cookie value.It works fine on my localhost server. But in live server which has a subdomain url has problem.Also I tested it with another server with ip address as url. There also it is not working. In both cases cookie created but cant read the cookie. Please help me.
cookie set by
$auto_login_hash_code = uniqid();
$domain = $_SERVER['SERVER_NAME'];
$cookie = array(
'name' => 'rememberMe',
'value' => $auto_login_hash_code,
'expire' => 31536000,
'domain' => $domain,
'path' => '/'
);
$this->input->set_cookie($cookie);
and reading cookie by
if (get_cookie('rememberMe')) {
$hashcode = $this->CI->input->cookie('rememberMe');
$this->CI->load->model('loginmodel', '', true);
$username = $this->CI->loginmodel->get_username_by_hashcode($hashcode);//in this function setting session variables
}
Thanks in advance
iijb
you are getting library for that on github.
search remember me on github, load it and just follow below steps.
Verify cookie if token is present in database go to home page
$this->load->library('rememberme');
$cookie_user = $this->rememberme->verifyCookie();
if ($cookie_user)
{
$this->load->view('search_view');
}
else
{
// If checkbox is checked it return true either false
$checked = (isset($_POST['Checkbox1']))?true:false;
if($checked== true)
{
//$this->load->view('tested');
$this->load->library('rememberme');
$this->rememberme->setCookie($this->input->post('loginemil'));
//$this->rememberme->setCookie('set cookie here');
}
else{
dont set anything
}
}
Also this can be done by editing/extending system Session library.
First: In user login function add remember me check-
if($remember)
{
$data['new_expiration'] = 60*60*24*30;//30 days
$this->session->sess_expiration = $data['new_expiration'];
}
$this->session->set_userdata($data);
Second: Edit system Session library [I am not sure whether extending Session will work or not]
Go to this line in sess_read() method
if (($session['last_activity'] + $this->sess_expiration) < $this->now)
Before that line add following code
if(isset($session['new_expiration'])){
$this->sess_expiration = $session['new_expiration'];
}
This works fine for me.

Resources