Programmatic authenticatication using a session variable - php

I'm trying to get authentication working in Symfony2.
My users use a login form somewhere else on the site that is not controlled by symfony2.
what I would like is Symfony to detect the users are already logged in and authenticated by reading a session variable and comparing against the DB.
I don't want to reimplement a login form on the symfony part of the website.
In symfony 1.x, for example, I would simply overload the BasicSecurityUser class and use the setAuthenticated method, but it seems this is not possible in Symfony2.
Is there any simple way of achieving the same result?
Thank you!

Once you know the user name of the authenticated user, you can log them in with:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class MyController {
// Takes either userName or an actual user object
protected function setUser($userName)
{
if (is_object($userName)) $user = $userName;
else
{
$userProvider = $this->get('zayso_core.user.provider');
// Need try/catch here
$user = $userProvider->loadUserByUsername($userName);
}
$providerKey = 'secured_area';
$providerKey = $this->container->getParameter('zayso_area.provider.key'); // secured_area
$token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
$this->get('security.context')->setToken($token);
return $user;
}

Related

Set password after google authentication in laravel 5.3

I am trying to implement google login using socialite plugin in laravel in which I want to set password filed (is user should set a new password before entering into the profile page).
After the password entering I need to create a new user entry via User::create() method ,but I don't know how to access the $user variable in my createUser function
Code
public funtion handleCallback($provider) {
//get userinfo
$user = Socialite::driver($provider)->user();
//set new password
return view('views.new-password');
}
//new password and create user
public function createUser(Request $request) {
//$user from handleCallback
dd($user)
}
Can I use a session variable to store this data so that I can access across multiple controllers is it the right way to do this??

Laravel 5 Auth - What exactly is it?

I understand that the auth functions allows a user to login etc, but I wanted a confirmation on what exactly was happening in the background.
My guess is that it's just a cookie that holds the login details, correct?
Or is it only storing the remember_token and then automatically comparing that with what is stored in the users table?
So if I wanted to create an account edit page. Would I have to do anything like comparing the auth id with the users table id that the e-mail matches up with? Or is it handling all that automatically?
Laravel Auth is nothing but its class where already all authentication methods or functions are written in laravel out of box.so you need not required to write all that function which is relating to user login.for example to check user we simply use
Auth::check();
but in laravel auth class they written like this
public function check()
{
return !is_null($this->user());
}
in the same way for login attempt we are passing parameter to attempt method .Here also laravel built in function is there
public function attempt(array $credentials = [], $remember = false, $login = true)
{
$this->fireAttemptEvent($credentials, $remember, $login);
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
// If an implementation of UserInterface was returned, we'll ask the provider
// to validate the user against the given credentials, and if they are in
// fact valid we'll log the users into the application and return true.
if ($this->hasValidCredentials($user, $credentials)) {
if ($login) {
$this->login($user, $remember);
}
return true;
}
return false;
}
Here you are passing all credentials in array and remember password and all

Authenticating users in a Symfony2 Application

This is going to sound very weird but kindly bear with me. I have built a symfony2 application which runs pretty well on the web.
Some users in the field are having so much trouble accessing the application on their phones in the field because we all know how heavy symfony is. The situation is so bad i'm forced to heavily scale down their access to just a four page access with just three php files, 1 for authentication, one for data entry and one for viewing their entries, all these without using symfony2 but plain php.
Now to my question, how do i check password against database password/salt?
I'm using FOSUserBundle for security
Are you sure you're using FOSUserBundle for security? I think you'll find you're using the core SecurityBundle for that. The way the user's password is stored will depend on how you have configured the security system.
The MessageDigestPasswordEncoder is what is used to encode the passwords. From looking at that code you can replicated it as needed. The gist of it is merge the password and salt ($password.'{'.$salt.'}') and then run it through PHP's hash function hash($this->algorithm, $salted, true) for however many iterations are needed.
Although, not specifically related to the question you asked, I'm a little confused as to what you mean by having to scale back the PHP for mobile users? Server page generation will take just as long for mobile as desktop users so why are you reimplementing outside of the symfony framework?
you can use user manager to check user credentials validity. i've created the following function for such mission.
/**
* authorize user by username and password
*
* #param string $username
* #param string $raw_password
*/
public function authUserByUsernamePassword($username, $raw_password) {
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->findUserByUsername($username);
// username not found
if (!$user) {
throw new \Exception("User with username: $username not found!", 0);
}
$encoder_service = $this->container->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($user);
$encoded_pass = $encoder->encodePassword($raw_password, $user->getSalt());
if($encoded_pass != $user->getPassword()){
throw new \Exception("wrong password!", 0);
}
// Get UsernamePasswordToken
$token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
// Set token
$this->authUserByToken($token);
return $this->getUserToken($user);
}

How to programmatically recreate php yii session?

From my application view I need to programmatically logout current user and login another one right after that.
I want to login the second user into his own different CHttpSession (with another sessionID and so on). I need it for a security reasons.
How to implement this in Yii framework ?
Code below
$oSession->destroy();
$oSession->open();
doesn't work as expected..
looks like you are trying to impersonate users:
Create a function in your UserIdentity that would alow you to login as another known user:
protected function logInUser($user)
{
if($user)
{
$this->_user = $user;
$this->_id=$this->_user->id;
$this->setState('name', $this->_user->name);
$this->errorCode=self::ERROR_NONE;
}
}
In your controller, call this function to get the UserIdentity object and then use the Yii's CWebUser login
$ui = null;
$user = User::model()->findByPk($userId);
if($user)
{
$ui = new UserIdentity($user->email, "");
$ui->logInUser($user);
}
Yii::app()->user->login($ui, 0);
Remember to protect this controller's action from non authorized users.
A possible tricky way (tested):
session_unset();
Yii::app()->user->id = $the_new_id;
When the above code is executed, nothing visible happens on the page so you may want to redirect the browser:
$this->redirect('somewhere');
Upon the next page load, the user with the $the_new_id will be logged in

Privacy control using Zend

I am making a social website using Zend. The site allows users to become friends and access each other's profiles and blogs. I also want users to have control over their privacy, which can take parameters "Friends Only" and "Public". I looked at Zend_Acl but it seems to be only able to to handle single user's accessibility not users have relationship. Any ideas about the best way to do this?
For your purposes, if you use Zend_Acl, you should look at assertions.
Given the complex nature of the relationships between users in your applications, most of the access rules you will query seem very dynamic so they will largely rely on assertions that can use more complex logic to determine accessibility.
You should be able to accomplish what you want using Zend_Acl though.
You may set up an ACL rule like this:
$acl->allow('user', 'profile', 'view', new My_Acl_Assertion_UsersAreFriends());
The ACL assertion itself:
<?php
class My_Acl_Assertion_UsersAreFriends implements Zend_Acl_Assert_Interface
{
public function assert(Zend_Acl $acl,
Zend_Acl_Role_Interface $role = null,
Zend_Acl_Resource_Interface $resource = null,
$privilege = null)
{
return $this->_usersAreFriends();
}
protected function _usersAreFriends()
{
// get UserID of current logged in user
// assumes Zend_Auth has stored a User object of the logged in user
$user = Zend_Auth::getInstance()->getStorage();
$userId = $user->getId();
// get the ID of the user profile they are trying to view
// assume you can pull it from the URL
// or your controller or a plugin can set this value another way
$userToView = $this->getRequest()->getParam('id', null);
// call your function that checks the database for the friendship
$usersAreFriends = usersAreFriends($userId, $userToView);
return $usersAreFriends;
}
}
Now with this assertion in place, the access will be denied if the 2 user IDs are not friends.
Check it like:
if ($acl->isAllowed('user', 'profile', 'view')) {
// This will use the UsersAreFriends assertion
// they can view profile
} else {
// sorry, friend this person to view their profile
}
Hope that helps.

Categories