Currently I am using Codeigniter library for my project and have a custom CMS made. Which obviously password protected but before loading every controller I have a function which I run to check if session exists and admin login otherwise redirect to login page.
public function checkLoginStatus(){
if($this->session->userdata('is_admin_login') != true) {
redirect(base_url().'admin/');
}
}
Is there a way I can check this globally and don't have to load in every controller?
my solution is.
if(empty($this->session->userdata('is_admin_login') ) {
redirect(base_url().'login/');
}else{
redirect(base_url().'admin/');
}
Related
I am building a new Laravel application (v5.4) that will run alongside (installed in the same environment) an existing PHP application that has it's own authentication system. I want the users who have successfully logged in to the existing system to be automatically authenticated in the Laravel app so they can navigate seamlessly between the applications.
My Laravel app has read-only access (through a second db connection) to the existing system's database so it can safely check that the PHP Session matches the session cookie recorded in the database and I can even pull out the user object and hand it to Auth's login() method.
I want to know the best way to put Auth into an authorised state (not guest) and where is the best place to put such code?
Options I've thunked of so far:
Middleware: Check session and call the login() method on Auth from some application-wide middleware?
Extend Illuminate/Auth/SessionGuard.php and override the attempt() method? If so, how do I tell the other parts to use my extended SessionGuard? (I suspect this was not designed to be easily overridden)
Super hacky disgusting way of dynamically setting the user's password to a random hash and then calling Auth/LoginController#login() in the background with a faked request containing that hash as the password field. (I seriously hope this doesn't end up being the most popular answer)
Some other option (?)...
Thanks in advance for your help SO community!
The solution I ran with in the end was creating a middleware that contains this:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isSet($_SESSION['intranet_user_id']) && $_SESSION['intranet_user_id']) {
// Log them in manually
$intranet_user_id = $_SESSION['intranet_user_id'];
if (!Auth::guest() && Auth::user()->getId() !== $intranet_user_id ) {
Auth::logout();
}
if (Auth::guest()) {
Auth::login( User::find($intranet_user_id), true);
}
} else {
Auth::logout();
}
We have a admin panel built in codeigniter, where two types of user get logged in (admin and super admin). Admin permissions are control by super admin. Admin permissions are stored in session at time of login. We are using codeigniter redis library for storing session data.
Now, the challenge is to update admin user session data without effecting admin login when permissions are changed by super admin.
if you want to do this on runtime i think with redis it shouldnt be really a problem
Create a pre Controller Hook where you check on every request if users session has been changed
since you use redis - you really don't need to use a DB Query in order to check it - just simply create an object which holds all changed users whose session have been changed and save it to redis
the hook could look like
class AppRefreshSession
{
private $ci;
public function __construct()
{
$this->ci = get_instance();
}
public function initialize()
{
if (!$this->isSessionValid())
{
//refresh users Session
}
}
private function isSessionValid()
{
$obj = $this->ci->cache->redis->get("ModifiedSessions_Object");
if ($obj->hasSessionModified())
{
return false;
}
return true;
}
}
And your modified sessions object should get filled with user ids or something like that whenever a superadmin changes the permission.
Save this object to redis and that should pretty much do what you want.
I'm trying to get my Yii app to auto logout after a set number of seconds when a particular type of user is logged in.
I have made the following amends to my protected/components/WebUser.php file:
public function init() {
parent::init();
if (($user = $this->getState('userModel')) !== null) {
$this->setUserData(unserialize($user));
if ($this->isNonAdminUser()) {
$this->authTimeout = 3600; // 1 hour timeout
}
}
$this->updateAuthStatus();
}
// function automatically directly after $this->logout()
protected function afterLogout() {
Yii::app()->request->redirect(('site/front/login'));
//Yii::app()->request->redirect((Yii::app()->user->returnUrl));
}
This will basically logout a 'non admin user' out of the session after 1 hour of no activity - this works however I'd like to be able to 'force' them back to the homepage as well. I've tried to use the redirect function in the afterLogout() but it doesn't seem to do a redirect for some reason?
Any ideas why not?
Note - I am using Yii 1.x
Try to use Yii::app()->user->homeUrl instead of Yii::app()->user->returnUrl inside afterLogout function.
After the user has logged in I want to be able to save the userId for later use within the application. The only place in the application I retrieve the username is from the login form, through the login controller. However, that structure in my application is that the only thing that is passed to my master controller from the login controller is HTML.
Of course I could include the userId in a hidden field inside the HTML that's passed back to the master controller, but that seems too hacky.
So, is there a way that I can save a value (in this case the username) so that it's accessible from other classes/namespaces/functions whatever? I have read a bit about 'global', but haven't managed to get it work in my application.
from LoginController.php:
if ($loginView->TriedToLogin()){
$loginUsername = $loginView->GetUserName(); //Retrieved from form
$loginPassword = $loginView->GetPassword();
}
Upon login, you need to store your user token in a session.
See: http://au1.php.net/manual/en/features.sessions.php
Store user when logging in:
$_SESSION['user_id'] = 32; // fetch from your user provider
You can then write a class/function that utilises the session to check their login status and fetch their details when required.
Like so:
function getUserId()
{
return isset($_SESSION['user_id']) ? $_SESSION['user_id'] : false;
}
function isLoggedIn()
{
return isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']);
}
Then use anywhere in your application:
echo isLoggedIn() ? getUserId() : 'Anonymous';
Also, for great information on how to build an MVC framework, check out "Create your own framework... on top of the Symfony2 Components".
How about Sessions?
Session support in PHP consists of a way to preserve certain data
across subsequent accesses.
http://de2.php.net/manual/en/features.sessions.php
If it's only the username you want store, I would go with $_SESSION[].
It's not the most secure in a (shared) hosted environment, but it's so easy to call session_start(); first thing on pages using the stored data.
I would like to check, whether user's account is activated while loggin in, but cake's Auth component takes care of the login in a way I don't know how to control. Cake basically uses blank login function and I have no idea how to check value of User.active.
Thanks in advance
The AuthComponent has a property for setting additional conditions just like this, called $userScope.
Just include this line in your beforeFilter() Auth setup block:
$this->Auth->userScope = array('User.active' => true);
Note: the above applies to Cake 1.x. For 2.x use:
$this->Auth->scope = array('User.active' =>true);
Then you can leave your login method blank and the AuthComponent will append this extra condition when authenticating the visitor.
You can see all the additional properties here:
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers
If you don't include this extra scope, then inactive users will still be able to log in and you'd have to log them out in your login() method after checking.
On your Users controller, or wherever you want to place it (the action that the login form links to):
function login() {
if ($this->Session->read('Auth.User')) {
$active = $this->Auth->user('active');
if ($active) {
//(do stuff)
}
else {
//(do other stuff)
}
}
}
This assumes that there is an "active" column in your User table that contains either true or false (or 1 or 0). $this->Auth->user() allows you to access the current logged in user's data. More information in here: http://book.cakephp.org/view/1264/user