What to do when lucadegasperi oauth2 server for laravel gets caught by auth middleware? - laravel

So currently building an oauth2 server with:
https://github.com/lucadegasperi/oauth2-server-laravel/blob/master/docs/authorization-server/auth-code.md
Auth Grant
laravel 5.2
Now no where in the instructions does it address what to do when the user is not logged in. (which most times will be the case)
So in that scenario - the user hits the auth middleware kicking them to the login screen... but what to do after that? There is nothing passed to the login page? so how do i know where to redirect the user back to?
Now yes of course I can just do this on my own, but before I do that I just want to make sure I am not missing anything? again it was not address in the documentation, so I can only assume this was thought through?
Let me know your thoughts.
Steve

So just ended up doing a work around in my Authenticate.php file. Incase anyone else is curious I did this:
$params = [];
if($request->has('client_id'))
$params['client_id'] = $request->client_id;
if($request->has('redirect_uri'))
$params['redirect_uri'] = $request->redirect_uri;
if($request->has('response_type'))
$params['response_type'] = $request->response_type;
if($request->has('scope'))
$params['scope'] = $request->scope;
if($request->has('state'))
$params['state'] = $request->state;
return redirect()->route('login', $params);
//return redirect()->guest('login');
Passed this to my loginController. Then in loginController:
$params = [];
if($this->request->has('redirect_uri'))
$params['redirect_uri'] = $this->request->redirect_uri;
if($this->request->has('response_type'))
$params['response_type'] = $this->request->response_type;
if($this->request->has('scope'))
$params['scope'] = $this->request->scope;
if($this->request->has('state'))
$params['state'] = $this->request->state;
if($this->request->has('client_id'))
{
$params['client_id'] = $this->request->client_id;
//dd($params);
return redirect()->route('oauth.authorize.get', $params);
}
Let me know if you see any issues.
Cheers
Citti

Related

login a user and granting core permissions in Joomla

I am working on a project which requires some manager level access to perform tasks, so when I receive a call I forcefully logging in the request as a superuser so that it will have all permissions to complete that task. For login I am using this code:
function forceLogin($superuserId)
{
$user = JFactory::getUser($superuserId);
//Will authorize you as this user.
JPluginHelper::importPlugin('user');
$options = array();
$options['action'] = 'core.login.site';
$response = new stdClass();
$response->username = $user->username;
$response->language = '';
$response->email = $user->email;
$response->password_clear = '';
$response->fullname = '';
$result = $app->triggerEvent('onUserLogin', array((array)$response, $options));
return true;
}
By this my current login user will be superuser. Now the concern is when any extension is searching for permissions, it is still getting that current session doesn't have them and so it returns false.
One of the solutions I came around is to redirect internally after login and then proceed to other tasks, in that way the system recognizes session to be availed with all permissions. For example -
I received something in getNotification()
function getNotification()
{
//from here I log in the user
$this->forceLogin($speruserId);
//and now redirect
$app = JFactory::getApplication();
$app->redirect('index.php?option=com_mycomponent&task=setNotification');
}
Now I proceed further request from setNotification()
function getNotification()
{
// do my work here
}
To be specific, the issue is arising in VirtueMart (e-commerce extension) in which I am creating a product from my call and while creating a product it checks vmAccess::manager('product.create') which is actually same as core.create of Joomla.
I think by redirecting session is being reset with current user and so it gets all permission. Can it be done without redirection? If yes, how?

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'));
}
....

Check if Admin is Logged in Within Observer

I'm attempting to check if the administrator is logged in from an observer. The problem is that while this is easy to do when viewing the admin module, viewing the frontend is another story.
There are several similar questions, but unfortunately none of them provide a working solution for Magento 1.6.2.
I wasn't able to successfully get isLoggedIn() to return true in the admin/session class. I also found out that there is a cookie for both frontend and adminhtml, which may help.
The accepted answer in this related question seems to suggest this may not be possible:
Magento - Checking if an Admin and a Customer are logged in
Another related question, with a solution that didn't help my specific case:
Magento : How to check if admin is logged in within a module controller?
It is possible. What you need to do is switch the session data. You can do this with the following code:
$switchSessionName = 'adminhtml';
if (!empty($_COOKIE[$switchSessionName])) {
$currentSessionId = Mage::getSingleton('core/session')->getSessionId();
$currentSessionName = Mage::getSingleton('core/session')->getSessionName();
if ($currentSessionId && $currentSessionName && isset($_COOKIE[$currentSessionName])) {
$switchSessionId = $_COOKIE[$switchSessionName];
$this->_switchSession($switchSessionName, $switchSessionId);
$whateverData = Mage::getModel('mymodule/session')->getWhateverData();
$this->_switchSession($currentSessionName, $currentSessionId);
}
}
protected function _switchSession($namespace, $id = null) {
session_write_close();
$GLOBALS['_SESSION'] = null;
$session = Mage::getSingleton('core/session');
if ($id) {
$session->setSessionId($id);
}
$session->start($namespace);
}
Late Answer but if as I found it on google:
This it not possible.
Why? Because the default session name in the frontend is frontend and the session name in the backend is admin. Because of this, the session data of the admin is not available in the frontend.
have you tried this :
Mage::getSingleton('admin/session', array('name' => 'adminhtml'))->isLoggedIn();
how about this ( I am not sure it will work or not )
require_once 'app/Mage.php';
umask(0);
$apps = Mage::app('default');
Mage::getSingleton('core/session', array('name'=>'adminhtml'));
$adminSession = Mage::getSingleton('admin/session');
$adminSession->start();
if ($adminSession->isLoggedIn()) {
// check admin
}

Anyway to redirect to previous URL after registration in Joomla?

I am developing a component that required login at some level, then if user is not logged in, I placed a login link, that take user to login page with following in query string.
return=<?php echo base64_encode($_SERVER['REQUEST_URI']);?>
After login, it comes back to that page, but is there some way to tackle this if user is not registered and user starts registering? Is there some way to do this without changing some thing in Joomla it self? like by just setting some thing in cookie e.t.c. Or I will need to change some thing in Joomla Registration component or module. Or is there some plugin for that?
Any response will be appreciated, please tell what ever way you know so that it may give me some better clue.
In your component you could try to store the referrer in the Joomla! session - I don't believe the session changes or is replaced during login. I haven't had time to try this but it should work.
To Save:
$session = JFactory::getSession();
$session->set('theReferrer', $_SERVER['HTTP_REFERER'], 'mycomponentname');
To Retrieve:
$session = JFactory::getSession();
$redirectTo = $session->get('theReferrer', '', 'mycomponentname');
Then you can just use a setRedirect before you return.
$this->setRedirect($redirectTo);
You can achieve this with a plugin (at least in Joomla 3.x - not sure how far back this will work off-hand). Key here is the onUserAfterSave event, which tells you whether the user is new or existing.
I wrote the code below some time ago, so can't recall the exact reason the redirect could not be done from within the onUserAfterSave event handler, but I think the redirect is subsequently overridden elsewhere in the core Joomla user management code if you try to do it from there, hence saving a flag in the session and checking it in a later event handler.
class PlgUserSignupRedirect extends JPlugin
{
public function onUserAfterSave($user, $isnew, $success, $msg)
{
$app = JFactory::getApplication();
// If the user isn't new we don't act
if (!$isnew) {
return false;
}
$session = JFactory::getSession();
$session->set('signupRedirect', 1);
return true;
}
function onAfterRender() {
$session = JFactory::getSession();
if ($session->get('signupRedirect')) {
JFactory::getApplication()->redirect($_SERVER['HTTP_REFERER']);
$session->clear('signupRedirect');
}
}
}

PHP / CI: Facebook Connect seems to use my site session instead of Facebook session

I've got a CodeIgniter project using the Facebook Connect "official" PHP implementation. For the most part it works fine, except for when a user first allows permissions. I've traced the problem deep into the provide facebook.php, the getSession() function:
public function getSession() {
if (!$this->sessionLoaded) {
$session = null;
$write_cookie = true;
// try loading session from signed_request in $_REQUEST
$signedRequest = $this->getSignedRequest();
if ($signedRequest) {
// sig is good, use the signedRequest
$session = $this->createSessionFromSignedRequest($signedRequest);
}
// try loading session from $_REQUEST
if (!$session && isset($_REQUEST['session'])) {
$session = json_decode(
get_magic_quotes_gpc()
? stripslashes($_REQUEST['session'])
: $_REQUEST['session'],
true
);
/* HERE IS WHERE IT GOES WRONG */
$session = $this->validateSessionObject($session);
}
My comment in the code is where things go wrong. The if block above gets evaluated successfully, but the code inside the json_decode() function parameter returns the string:
a:4:{s:10:"session_id";s:32:"********";s:10:"ip_address";s:13:"********";s:10:"user_agent";s:50:"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2";s:13:"last_activity";i:1304286136;}edc0c222265e0a16c0f3fe8a96decf77
This looks like my site session, rather than the facebook session that it's trying to access (which I can see in the URL). Why is this happening? What can I do about it?
In case anyone else hits this particular snag, I'll post how I solved it:
Just change $_REQUEST to $_GET
My guess is that CodeIgniter somehow puts your session information into the $_REQUEST array... why this happens is beyond me, but it solved the problem for me. Hope it helps!

Resources