combining cakephp's auth with hybridauth (oauth) - php

I suppose I'm just looking for a bit of guidance as to how to set up my User + Authentication area on my website with cakephp 2.0.
I have a basic login and register functionality set up within my UserController.php, which also contains functions for looking up and displaying other users.
I also want to use the hybridauth plugin to allow for users to login/register using their social media / oauth account (allowing for more than one social account per user in the database, so that the same user could use either their twitter or facebook details, for example). I'm only having 3 providers at this time, so I plan to just create 6 columns in my user database, with the token and outhid in the same user row. This is in another controller - HybridauthController.php.
I have the hybridauth set up so that it creates its 'hybridauth' object from the account details, which is fine - but I want to be able to merge the whole 'authentication' together, so that my cakephp session contains the hybridauth session data (object) creating my general "current user" array that I can use, and set some generic variables within, depending on whether they are from oauth or not.
I don't currently store sessions in a database, and ideally I would like for allow persistent sessions for all, whether they use an oauth account or not. I don't really understand how persistent sessions are supposed to work with hybridauth, because how in this example would the $current_user_id be filled in when the user returns the next day? Not via a cookie, surely?
http://hybridauth.sourceforge.net/userguide/HybridAuth_Sessions.html
So in summary I'm looking for a simple solution to combine all of my 'session' / 'auth' / 'user' data into one simple array in the users session. Hopefully that all makes sense!
Thanks

Late to answer, but hopefully it'll help you or someone else searching.
I had a tough time integrating HybridAuth into a preexisting CakePHP (1.3) app that was already using Cake Sessions and the Auth component. I initially tried using the Cake example that I downloaded from the HybridAuth website, but that did not work for me.
Our preexisting User controller already had a bunch of logic in it including a beforeFilter method. That's where I inserted my session_start() as opposed to above the class declaration in the HybridAuth Cake example:
class UsersController extends AppController {
...
var $components = array('Session','Auth','Email');
...
public function beforeFilter(){
// following two lines may not be necessary for your setup
$this->Auth->allow('oauth', 'oauthLogout');
$excludeBeforeFilter = array('oauth', 'oauthLogout');
if ( ! in_array($this->action, $excludeBeforeFilter) ) {
// preexisting Auth logic -- I had to bypass it because
// calling `session_start` was messing up Cake's Auth
...
} else {
/* THIS IS NECCESSARY FOR HYBRIDAUTH (OAUTH) */
/* setting the session ID made it so users could NOT log
in from a 3rd party and our site */
session_id($_COOKIE['CAKEPHP']);
session_start();
}
}
...
public function oauth($provider){
$this->autoRender = false;
// include HybridAuth
require_once( WWW_ROOT . 'hybridauth/Hybrid/Auth.php' );
try {
// I stored my provider config in a Cake config file
// It's essentially a copy from the site/Cake example
$hybridAuth = new Hybrid_Auth(Configure::read('HAuth.config'));
$adapter = $hybridAuth->authenticate($provider);
$userProfile = $adapter->getUserProfile();
// method on the User model to find or create the 3rd party user
$user = $this->User->findOrCreate($userProfile, $provider);
if ( ! $user ) {
echo 'Unable to find/create user';
} else {
// configure your fields as necessary
$this->Auth->fields = array(...);
$this->Auth->login($user);
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
At this point the 3rd party (HybridAuth) user is accessible in the Auth Component. This way a user was only logged in one 3rd party service or the preexisting login (but not both).
I also had an issue logging out. To do that I basically destroyed all sessions/cookies to be safe. In the oauthLogout method of the UsersController:
// probably overkill/paranoia
$this->Auth->logout();
$this->Session->destroy();
session_destroy($_COOKIE['CAKEPHP']);
/* these two seemed to make the difference
especially the 4th parameter */
setcookie( 'PHPSESSID', '', 1, '/' );
setcookie( 'CAKEPHP', '', 1, '/' );
Seems super hacky -- sorry for that. Hope it helps though!

Related

Is it possible in LARAVEL to tag a user as logged in when getting his username from a custom URL?

I am currently doing a website wherein the login URLs are varying and displays the data according to the assigned projects to them.
For example, user A can only access www.example.com/projects/proj1. This is the homepage for user A and if he logs in he uses www.example.com/projects/proj1/login
While user B can only access www.example.com/projects/proj2. This is the homepage for user B and if he logs in he uses www.example.com/projects/proj2/login
Please note that proj1 and proj2 are varying depending on the database. So I have to check first that these projects are already registered in the database.
I am thinking of having a route like this.
For web.php
Route::get('/projects/{project_name}', 'PageHandler\CustomPageController#projects');
Route::get('/projects/{project_name}/login', 'PageHandler\CustomPageController#login');
Route::put('/projects/{project_name}/auth/{user}', 'PageHandler\TestUserPageController#auth');
Then my customepagecontroller.php looks like this
class CustomPageController extends Controller
{
public function projects(string $projectName)
{
if (auth()->user() == null)
return redirect('/projects'. '/' . $projectName . '/login');
}
public function login(string $projectName)
{
return view('login')->with('projectName', $projectName);
}
public function auth(Request $request, string $projectName)
{
$username = $request->username;
//How to set $username as logged in?
// rest of the code to show the home page after authentication
}
}
login.blade.php basically just looks like a form submitting username and password and calling auth of CustomPageController with a string parameter for the URL
So my question is how can I set $username as logged in already using the Auth of Laravel? Or should I create my custom Authentication Controllers?
Now, this is the only approach I have in mind for me to enable the logging in of users to varying URLs. Please let me know if you have better approach.
Thank you!
If you only want to limit the project the users can access, I do not see a need to use 2 different login URLs (please correct me if there is a reason why you want different URLs for that), instead, you simply find which project the user belongs to from the database.
For authentication, Laravel allows you to implement authentication in a very easy way, you can refer to the documentation. Using Laravel's authentication would be easier and safer than writing your own one, and even if the default functionalities it provides may not be exactly the same as those you would want to achieve, you can still add your own things, which is still a lot easier than implementing it from scratch.
As for setting a user as logged in with Laravel's authentication services, you can use Auth::login($user);. Here, $user must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. You can refer to this part of the documentation for more details.

How to bypass usual Laravel authentication process to set a user as logged in

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();
}

CodeIgniter Ion Auth: How is is_admin() working?

I'm using the Ion_auth for CodeIgniter in my project auth library. I'm trying to make a similar function as is_admin() for other user types (there are three user types other than the admin) to check whether the logging in user is of one of those three types so I can redirect them to their respective pages. Ion_auth is using an event called is_admin but I can't understand where this is happening in the Ion_auth_model.php and how it checks whether the logged in user is admin. So how can I make other functions/events similar to this one?
I know I can just do something like query the database and check the user group but I want to do the way Ion_auth has done. That way I can also satisfy myself by actually understanding the stock code.
I am just looking at source code on github.
As lots of auth libraries store, information you are looking for in session and library itself checks session variables.
your function you are looking for is on line 447 in file application/libraries/Ion_auth.php
public function is_admin($id=false)
{
$this->ion_auth_model->trigger_events('is_admin');
$admin_group = $this->config->item('admin_group', 'ion_auth');
return $this->in_group($admin_group, $id);
}
In order to create your own I suggest you to reverse engeneer model (ion_auth_model.php)
But! Ion already has a workaround for you, this method is what you are looking for
in_group()
$group = 'gangstas';
if (!$this->ion_auth->in_group($group))
{
$this->session->set_flashdata('message', 'You must be a gangsta to view this page');
redirect('welcome/index');
}
source
The function is_admin() refers to the admin group defined in the file /application/config/ion_auth.php: $config['admin_group'] = 'admin'; // Default administrators group, use name.
The admin_group name itself is stored in the ion_auth database field groups.name.

Zend_Auth and dynamically changing user details on the UI

When my users are logged in I display their details (name, email) on the UI. When they update their profile, I would like to show the updated details, without requiring the user to log out and back in.
The UI details are retrieved from Zend_Auth via a view helper. Zend_Auth is storing the 'identity' details in a session.
How should I go about updating the details in the session?:
I was considering retrieving the user's login credentials from the database and using them to call Zend_Auth->authenticate() again. The problem is that I don't know the password, only it's md5 hash. I could consider a new method, reauthenticate(), which configured the adapter to bypass the md5 and salt, but this sounds laborious.
I was considering writing directly to the Zend_Auth session namespace, but this sounds like a recipe for trouble?
Have you come across a similar problem? How did you handle it?
Your ideas are much appreciated!
You can update Zend_auth identity for the currently logged user. Very simplified action that updates only username could be as follows:
public function editAction() {
// check if user is logged, etc, and then
// show the edit user form and process the data after submission.
$userForm = new My_Form_EditUser();
if ($this->getRequest()->isPost()) {
if ($userForm->isValid($_POST)) {
// process the submitted data,
// and when you are sure that everything went ok,
// update the zend_auth identity
$authData = Zend_Auth::getInstance()->getIdentity();
// this line would depend on the format of your
// identity data and a structure of your
// actual form.
$authData->property->nickname = $formData['user']['nickname'];
$this->_helper->FlashMessenger('Your data was changed');
return $this->_redirect('/');
}
}
$this->view->form = $userForm;
}
Hope this helps.
What I really want is a method on Zend_Auth::setIdentity($user).
But in the absence of such a method, I have used a hack in which I have create an auth adapter that always returns success and sets the identity to the same user object I would have created in a "real" auth adapter. Then I just call Zend_Auth::authenticate($adapter) with that adapter and it sets the identity internally.
Now, looking mosre closely at the internals of Zend_Auth::authenticate(), I see that what we could do is just:
Zend_Auth::getInstance()->getStorage()->write($user);
Here's how I solved the problem for the time being. Not sure yet if it's the best solution:
create a wrapper for Zend_Auth
include a getAuthAdapter($raw) method
configure the adapter differently, depending on the value of $raw
if (false === $raw) {
$this->_authAdapter->setCredentialTreatment('SHA1(CONCAT(?,salt))');
} else {
$this->_authAdapter->setCredentialTreatment();
}

cakephp custom login conditions

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

Categories