Symfony keep user logged after manual authentication - session

To authenticate manually a user I used the following code:
$user = new User($token, null, array("ROLE_USER"));
$token = new UsernamePasswordToken($user, null, 'secured_area', array("ROLE_USER"));
$this->get("security.context")->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
The problem is that when I change page (also same controller) I lost the token/session.
Sometimes I get this: There is no user provider for user "Acme\MyBundle\Security\User".
How I should configure the secured area with pattern: ^/?
secured_area:
pattern: ^/
Thanks

In FosUserBundle you can see an example of how to do Manual login correctly.

Related

How to make login as other user in API using laravel passport?

I am using laravel passport for API authentication. and I want to log in as different users with different roles from superadmin. So how can I achieve this? Please give your suggestions.
public function masqueradeNotary($profileId)
{
$userId = decodeC($profileId);
$notaryUser = $this->adminService->getUser($userId);
if($userId){
//logout from current login user
$user = auth()->user()->token();
$user->revoke();
//login as notary user
$userRoles = $notaryUser->roles()->get();
// $scopes = [];
// if ($userRoles) {
// $scopes = Arr::pluck($userRoles,'code');
// }
if(Auth::login($notaryUser)){
\Log::info("auth user");
\Log::info(auth()->user());
// $token = $user->createToken($user->email . '-' . now(), $scopes);
}
}
}
Welcome to stackoverflow.
Well, you should look at spatie's package, it might make your life easier.
You can apply roles on the registration if you create two different registration functions. In the front-end, you have to somehow make the user decide and pass that value (a checkbox would be ideal).
I got the solution. there is no need to check auth login just log out the current user and revoke the access token and create a token for the user directly.
$token = $user->createToken($user->email . '-' . now(), $scopes);

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?

symfony2/fos-user-bundle: Login User by Entity

I have a user entity in a symfony2 controller and i need to log that user in.
Apparently i do not understand how the process works with the Csrf Token and loging in a user.
What do i have to do to log in the user?
Having an user object you can login/authenticate a user programmatically
$token = new UsernamePasswordToken($user, $user->getPassword(),
"public", $user->getRoles());
$this->get("security.context")->setToken($token);
// Trigger login event
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")
->dispatch("security.interactive_login", $event);
You need to have this classes included
use Symfony\Component\EventDispatcher\EventDispatcher,
Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken,
Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

Facebook losing logged in user with ajax

I am writing a Facebook app and have used the Facebook php SDK so it can be authorized server side. I can see this is working because after authorization when Facebook redirects back to my app, I have the following code in my index.php...
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
...and $user returns not null. So far, so good!
I have a link on my app that loads content via ajax when clicked. Here's the JS:
$.post('my_content.php', {
action: 'render'
}, function(res){
if (res.html.length) {
$('.content').html(res.html);
}
},'json');
The problem is, the my_content.php script seems to be losing the fact the user has logged in and authorized the app.
The code I run in the my_content.php script to check whether the user is logged in is the same as in index.php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '111111111111111',
'secret' => '11111111111111111111111111111111',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
This time though $user = $facebook->getUser() returns null.
Is there a way to check if the user is logged in and authorized when running a PHP script with an AJAX call?
Should I store something in a session variable in my index.php script?
EDIT
After even more reading, I'm wondering if I need to retrieve the access token using the JavaScript SDK and pass it to my_content.php. Does anyone know if that's the correct way to do it?
EDIT 2
Turns out the line giving me the problem isn't $user = $facebook->getUser():
It is this one
$user_profile = $facebook->api('/me');
This line fails with the error 'OAuthException: An active access token must be used to query information about the current user.'
Strangely though, if I do this
$access_token = $facebook->getAccessToken();
$user = $facebook->getUser();
echo $access_token;
echo $user;
I do indeed have an access token and a user ID, so it looks like it may well be the bug reported by CBroe - check comments below.

CakePHP 2.0 Automatic Login after Account Activation

I'm just working on the user management-component of our new project.
The plan is:
User registers on the page with minimal amount of account data (username, pass, email)
User gets an email with an activation link to activate the account
User clicks on the link and activates his account
The system logs in the user after automatically after activation and redirects him to kind of a dashboard with account information (last login, hi "username", etc.)
But there are some problems with the auto login. this is the part of the code i use:
<?php
...
// set userstatus to "active" and delete meta information "activation_key"
// then automatically login
$this->User->id = $id;
$this->User->saveField('modified', date('Y-m-d H:i:s') );
$this->User->saveField('status', 1 );
// $this->User->deleteActivationKey ....
$this->Auth->login($this->User->read());
$this->Session->setFlash(__('Successfully activated account. You are now logged in.'));
$this->User->saveField('last_login', date('Y-m-d H:i:s') );
$this->redirect(array('controller' => 'pages'));
...
This works so far, until you want to get information about the logged in user with the user() function of the Auth Component.
We're using this in AppController->beforeRender, to have user information application wide:
$this->set('auth', $this->Auth->user());
but after that auto login action, i'm getting undefined index notices. (e.g. by accessing $auth['id'] in a view). print_r() shows me only the username and hashed password of the current user.
If you login manually, everything works fine. it must be something with the automatic login after the account activation.
Seems to be a problem with the session? What am i doing wrong?
Found a solution after testing many variations.
Works now with:
$user = $this->User->findById($id);
$user = $user['User'];
$this->Auth->login($user);
Don't know why, i thought i tried this way already and that did not work.
Have you tried this? (CakePHP 2.x)
public function signup() {
if (!empty($this->request->data)) {
// Registration stuff
// Auto login
if ($this->Auth->login()) {
$this->redirect('/');
}
}
}
That simple!

Resources