Laravel 5 Auth - What exactly is it? - php

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

Related

Laravel Socialite pass and retrieve custom data?

I'm currently adding Socialite to my website to allow users to log in from Facebook.
public function redirectToProviderFacebook() {
return Socialite::driver('facebook')->redirect();
}
public function handleProviderCallbackFacebook() {
$userSocial = Socialite::driver('facebook')->user();
$email = $userSocial->getEmail();
if (User::where('email', $email)->count() > 0) {
// log them in
Auth::login(User::where('email', $email)->first());
return redirect()->route('home')->with('info', "You are now signed in.");
} else {
// register an account and log them in
}
}
During normal user registration, I ask for three things: username, email and password. The username and email are things you cannot change on my site, ever, as their usernames are bound to many things.
The problem with logging in with Facebook is that I have to register new users in the callback function. Therefore, I can't ask them for what they want their usernames to be.
Is there a way I could perhaps prompt the user for their preferred username? Then do the redirect like this:
return Socialite::driver('facebook')->with('username', $request->username)->redirect();
Then retrieve that data to use it for auth registration in the callback function?
For some reason, Optional Parameters didn't work for me, so i ended up by using session to pass variables from redirect method to the callback method. it's not the best way to do it, but it does the trick.
public function redirectToFacebookProvider()
{
// save anything you will need later, for example an url to come back to
Session::put('url.intended', URL::previous());
return Socialite::driver('facebook')->redirect();
}
public function handleFacebookProviderCallback()
{
// handling....
$url = Session::get('url.intended', url('/'));
Session::forget('url.intended');
return redirect($url);
}
Obtained this answer from https://laracasts.com/discuss/channels/laravel/socialite-return-parameters-in-callback?page=0
And from Sending additional parameters to callback uri in socialite package for laravel
i am not sure about facebook, but for github its working fine. Try this:
public function socialLogin($loginFrom){
return Socialite::driver('github') >redirectUrl('http://your-domain.com/callback?data=123')->redirect();
}
on github app you need to put only: http://your-domain.com/callback

Symfony check if user is authenticated

In my Symfony project I'm using UserInterface in my User entity to handle authentication. I also use EquatableInterface to check if user's email is changed while he's logged in.
public function isEqualTo(UserInterface $user)
{
if (!$user instanceof Account) {
return false;
}
if ($this->email !== $user->getEmail()) {
return false;
}
return true;
}
All works as expected, but when I change user's email in DB I'm not logged out, just not authenticated as you can see in the following screenshot.
So I would know how can I check in a controller if user is authenticated? And how can I force user to log out when isEqualTo returns false?
I found the solution and I want to share it if someone else have the same problem.
To check if user is authenticated, we need TokenInterface which is implemented by TokenStorage. Then we just need to call isAuthenticated() method.
$tokenInterface = $this->get('security.token_storage')->getToken();
$isAuthenticated = $tokenInterface->isAuthenticated()
Fast Method: see method getUser in Symfony\Bundle\FrameworkBundle\Controller at link. If you need this behavior somewhere in the service, then use the security.token_storage service as a dependency.
Try way method (symfony-like): you need use Symfony Security Voters

Is my CakePHP Session login secure?

I don't know how to use AuthComponent then this is the way I do user authentication with multiple roles is as follows:
There is 3 roles: Administrators, Resales and Clients.. one controller for each one, for individual views, and this is my beforeFilter for each Role/Controller:
AdministratorsController:
function beforeFilter(){
if (!$this->isAuth('Administrator'))
$this->redirect('/');
}
AppController:
function isAuth($strRole = NULL){
$data = $this->Session->read('User');
if (!$this->Session->check('User') || (!is_null($strRole) && $data['Role']['nome'] != $strRole))
return false;
return true;
}
In UsersController I do only authentication checking if $this->Session->read('User') exists, if the user exists, he gets all info and put in Session like this: $this->Session->write('User', $user); assuming that $user is the find from Model with all user information.
the question is, will I have problems? is that "right"? do not know if I was clear, if missing information, ask..
You're replicating logic the framework already implements for you.
See http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html#authorization-who-s-allowed-to-access-what
Taken from that page (you should still read it..):
public function isAuthorized($user) {
// Admin can access every action
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
// Default deny
return false;
}
The user data gets passed to it, no need to fetch the user data yourself.
And if you ever have to fetch the user data use $this->Auth->user():
// Some field
$this->Auth->user('someField');
// Whole data
$this->Auth->user();
If the session key ever changes for some reason all you direct calls to the Session->read('User') will be in trouble. A good and not so unlikely example here is when the application has to be extended with a 2nd auth adapter that is not using the session. Auth will know about the data, Session won't have it.

keep user info throughout the web once logged in. PHP MVC

I do know how to use sessions/cookies. I do keep session and a cookie + token for a user logged in.
I'm using MVC structure (my own) and i have a Login.php controller. I also have User.php class that is a singleton class having only 1 instance.
My base controller gets the instance of User and stores in a variable like this:
abstract class Controller {
private $model;
private $user;
function __construct($model = '') {
..... //some code
$this->user = User::getInstance();
}
public function user() {
return $this->user;
}
}
In my login.php i have the following once the user submits form with user name and pass:
function logUserIn() {
if (! isset($_POST['UName']) || ! isset($_POST['UPass'])) {
$this->_404();
}
$uname = strtolower($_POST['UName']);
$pass = Hash::strongHashMD5($_POST['UPass']);
$token = $_POST['token'];
$isValid = $this->model->userCheck($uname, $pass);
$res = $this->validateUser($isValid, $token, $uname);
if ($res === false) {
echo 'User Does Not Exist!';
} else if ($res === 'Token_Error') {
echo 'Invalid Form Submission';
} else if ($res === true) {
//update token
$this->model->updateToken($isValid['ID'], $token, $_SERVER['REMOTE_ADDR']);
header("Location: ../login");
}
exit;
}
this is my method that validates user
private function validateUser($UInfo, $token, $UName) {
if ($UInfo !== false && isset($UInfo['ID']) && $UInfo['ID'] > 0) {
if ($UInfo['token'] == $token) {
return 'Token_Error';
} else {
$this->user()->setValues($UInfo['ID'], $UName, $token);
$this->user()->setSessions();
return true;
}
}
return false;
}
setsessions() method just sets the session/cookies of that user
Now everytime i want to access to see whether user is logged in or not i have to do it through controller and pass it to anywhere else.
Is there any better way of doing this? Is there any problem with my code in terms of security issues etc...
Any suggestions/advices will be appreciated, thanks guys
Currently you have domain business logic leaking all over the place. It should stay in the model layer (yes, in proper MVC the Model is a layer not a class or object), instead of being in the presentation layer.
Also, please stop hashing passwords with MD5. You might as well leave them as plain-text if you do so. Instead you should be using either crypt() with CRYPT_BLOWFISH or PBKDF2 algorithm.
Oh .. and redirecting people to 404, if one of the form fields is empty, seems a bit like overreacting.
anyway ..
the main topic:
The user authentication should happen entirely in the model layer (more precisely: in some Recognition service). Controller should only provide model layer with data and notify the current view that POST has request has been sent.
The service, upon receiving data, should create domain object for the User and assign the values. If the data passes the validation (which is one of responsibilities of a domain object) the service should instantiate the appropriate data mapper and fetch the data from storage (which might or might not be an SQL database). If this goes thought with any problems (like missing record in storage), the domain object should conform the credentials.
If any of this failed at some point, service should act upon the error state and put it in temporary storage (most likely - session).
When application gets to the part where view is supposed to generate the response, the view instance would react on the indication about POST request by checking for error state in model layer and perform the redirect by sending an HTTP header as only response based on whether or not there has been an error.

Programmatic authenticatication using a session variable

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

Categories