How to add additional data to object Auth in Laravel 5.3? - laravel

There is default object Auth in Laravel after authification.
It contents data about current user from table Users.
How can I add the additional data to this object from other related table?
Edit:
So, if I am right, the object Auth is created when user is authenticated. In this moment I need to fill object by additional data.

I presume you want to retrieve a user in a controller and return it as a response, maybe json? or not, it's doesn't really matter. here what you could do
public function getUser()
{
$user = auth()->user();
$user->load('relationName');
$user->load('anotherRelationName');
}

Related

laravel using validation request with except method

I am using request validation as
php artisan make:request ClientRequest
As you can see, on client edit form if password field is not empty I am able to use $request->validated() method on database update,
However if password field empty(user dont want to change password),
I am not able to use $request->except('password')->validated() method.
I use $request->except() method due to this situation.
Does this pose a security problem?
public function update(ClientRequest $request, Client $client)
{
$validated = $request->validated();
if($request->filled('password') )
{
Client::whereId($client->id)->update($validated);
}else{
Client::whereId($client->id)->update($request->except('password'));
}
return redirect('/clients')->with('success', 'success');
}
Client::whereId($client->id)->update($request->except('password'));
That line is does pose a big security problem especially if you are relying on validation to set fields rather than the fillable attribute. $request->except('password') will return all the other fields that the user submitted so if the user had added something like is_admin => true in the request, you'll end up setting it on the db if it exists.
You can use \Illuminate\Support\Arr::except() on the validated data to make sure that you are only getting the data you expect. That would change the that particular line to
Client::whereId($client->id)->update(\Illuminate\Support\Arr::except($request->validated(), 'password'));
PS: You already have the client through route model binding so you don't need to query it you can update that client directly i.e
$client->update(\Illuminate\Support\Arr::except($request->validated(), 'password'));
You are validating all fields sent to update() in both scenarios.
You would have had an issue if you sent the password field in both cases, but only validated it in one of them. That's not the case.
So looks fine to me from that perspective.

Yii2 how to I get user from database in findIdentityByAccessToken method?

I need to set up JWT authentication for my Yii2 app. The authentication itself works fine, the token gets parsed and I can read it's data in my User model. But the problem is that I need to compare this data to a real user in my DB. So, I've got this method in the User model which extends ActiveRecord
public static function findIdentityByAccessToken($token, $type = null) {
$user = User::findOne(['ID' => 1]);
die(json_encode($user));
}
It's very simplified just to see that it finds a user. It does not and it always returns this:
{"id":null,"userLogin":null,"userPass":null,"userNicename":null,"userEmail":null,"userUrl":null,"userRegistered":null,"userActivationKey":null,"userStatus":null,"displayName":null}
The data is not populated. But if I do the same inside any controller, like so
class TokenController extends ActiveController
{
public $modelClass = 'app\models\User';
public function actionFind(){
return User::findOne(['ID' => 1]);
}
}
It works great and I get the User object populated with correct data.
Is it possible to get user from not within an ActiveController class?
Well, I don't know exactly what is wrong with this line here die(json_encode($user));
But it actually finds and populates the user and I can access it later via
Yii::$app->user->identity
so I can also blindly compare its ID and password to the real ones here

View Share doesn't return updated data, how then to share live data?

I currently have a model which access data like so:
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
return view('layouts.cart')->with('cartDetails', $displayCart);
This model correctly retrieves the data in a current session.
To access this same data in a header file I'm using View::Share in the AppServiceProvider like so:
public funciton boot()
{
$currentSessionID = session()->getId();
$inCartDetails = Cart::where('session_id', $currentSessionID)->get();
View::share('inCartDetails', $inCartDetails);
}
In my blade the $inCartDetails returns empty. I get [].
My suspicion is that this function ONLY gets called at boot. Hence the name :) and that it's empty cause at the time of starting the session it's empty since user hasn't selected anything. If this is correct how would I then pass live data to multiple views?
The session is not available in the boot method of the service providers. You should create a middleware for this. Check out this answer here: How to retrieve session data in service providers in laravel?

Laravel How to store extra data/value in session Laravel

I'm using default auth() in laravel login (email & password)
Now i try to take input from the user in text field like (Age or City)
Now i want to store (Age/City) in my session.
Help me
You can use session() helper:
session('age', 18); // saves age into session
$age = session('age')`; // gets age from session
Update
If you want to save Age and City after user registration, you should store this data in a DB, not in a session. You can add some fileds in create method of app\Http\Controllers\Auth\AuthController.php
You can use
Session::put('key', 'value');
To get key from Session use
Session::get('key');
You can use the session() helper function as #Alexey Mezenin answer.
Laravel Session Documentation
Ok let me enlighten you. if you want to store it in session do it this way.
session('country', $user->country); // save
$country = session('country')`; // retrieve
But that is not the way we do in Laravel like frameworks, it uses models
once the user is authenticated each time when we refresh the page, application looks for the database users table whether the user exists in the table. the authenticated user model is a user model too. so through it we can extract any column. first thing is add extra fields to the User class(Model) $fillable array.
so it would look something like this.
User.php
protected $fillable = ['username', 'password', 'remember_token', 'country'];
so after simply logging in with user name and password in anywhere just use Request class or Auth facade. Facades are not too recommended so here for your good as a new one i would just say how to use Request. Suppose you want to retrieve your Authenticated user country inside TestController.php here is how it could be used in the methods.
TestController.php
use Illuminate\Http\Request;
public function testMethod(Request $request)
{
$someCountry = $request->user()->country; //gets the logged in user country
dd($someCountry); //dd is die and dump, could be used for debugging purposes like var_dump() method
}
Using Request
public function ControllerName (Request $request){
$request->session()->put('session_age', $age);
}
Get session_age
$get_session_age = $request->session()->get('session_age');
Using Session
public function ControllerName (){
Session::put('age',$age);
}
Get the session
$session_age = Session::get('age');
Don't forget to define Session or Request in your controller!!!
use App\Http\Requests;
use Session;
To work with session in your controller you need to include session first in your controller
use Session;
After that for store data in session. There is several ways to do it. I prefer this one (in controller)
session()->put('key',$value);
To display session data in your View you can do it like this
#if(Session::has('key'))
I'v got session data
#else
I don't have session data
#endif
To get session data in your Controller you can do it like this
session()->get('key')
//or
session()->get('key','defaul_value_if_session_dont_exist')
When you are done with your data in session you can delete it like this (in controller)
session()->forget('key');
All this basic usage of session is well documented in official Laravel documentation here.
Hope it helps you

Can I store an access Cookie in a Laravel session?

I am working with a remote API that is normally accessed directly via JavaScript. In the normal flow, The user authenticates by sending Auth headers and in return is granted a cookie.
What I am trying to do is send auth headers from a laravel app, authenticate in the app controller, and provide API access through laravel controller functions.
I was hoping this would be as simple as authenticating and sending my subsequent API calls, hoping that the cookie given to the PHP server would continue to grant authentication.
Well that doesn't work and thats fine, but now I am thinking that I need to store my access cookie in the Session, and send it in the headers for future API calls.
Will this work/how can I go about this? My supervisors don't want to implement OAuth type tokens on the remote server and to me that seems like the best route, so I am a bit stuck.
Cookies cannot be shared across multiple hosts. The cookie (on the client) is only valid for path which set it.
EDIT - ADDING ADDITION AUTH DETAIL
Setting up remember me in Laravel
When migrating (creating) you User table add $table->rememberToken()
to create that column in your User table.
When user signs up to your service add a check box to allow them to
make the decision OR you can just set it true if you don’t to offer
the user the option as described in step 3
< input type="checkbox" name="remember" >
In your controller you add the following code:
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}
Users table must include the string remember_token column per 1. , now assuming you have added the token column to your User table you can pass a boolean value as the second argument to the attempt method, which will keep the user authenticated indefinitely, or until they manually logout. i.e. Auth::attempt([$creditentials], true);
Side note: the Illuminate\Contracts\Auth\UserProvider contract, public function updateRememberToken(Authenticatable $user, $token) uses the user’s UID and token stored in the User table to store the session auth.
AUTH ONCE:
Laravel has once method to log a user into the application for a single request. No sessions or cookies. Used with stateless API.
if (Auth::once($credentials)) {
//
}
OTHER NOTES
The remember cookie doesn't get unset automatically when user logs out. However using the cookie as I explained below in cookies example you could add this to your logout function in your controller just before you return the redirect response after logout.
public function logout() {
// your logout code e.g. notfications, DB updates, etc
// Get remember_me cookie name
$rememberCookie = Auth::getRecallerName();
// Forget the cookie
$forgetCookie = Cookie::forget($rememberCookie);
// return response (in the case of json / JS) or redirect below will work
return Redirect::to('/')->withCookie($forgetCookie);
OR you could q$ueue it up for later if you are elsewhere and cannot return a response immediately
Cookie::queue(forgetCookie);
}
Basic general cookie example that might help you. There are better approaches to do this using a Laravel Service provider
// cookie key
private $myCookieKey = 'myAppCookie';
// example of cookie value but can be any string
private $cookieValue = 'myCompany';
// inside of a controller or a protected abstract class in Controller,
// or setup in a service ... etc.
protected function cookieExample(Request $request)
{
// return true if cookie key
if ($request->has($this->myCookieKey)) {
$valueInsideOfCookie = Cookie::get($this->myCookieKey);
// do something with $valueInsideOfCookie
} else {
// queue a cookie with the next response
Cookie::queue($this->myCookieKey, $this->cookieValue);
}
}
public function exampleControllerFunction(Request $request)
{
$this->cookieExample($request);
// rest of function one code
}
public function secondControllerFunction(Request $request)
{
$this->cookieExample($request);
// rest of function two code
}

Resources