Situation
I'm using Laravel Passport API to communicate between Laravel and external "agents" via Personal Access Tokens: https://laravel.com/docs/5.5/passport#personal-access-tokens
You can create multiple tokens per user.
Authentication works and I can retrieve the User via Auth::User()
Question
How can I check which token is used?
Background
I want to use different tokens for different "agents" for the same user and I need to know which token is used to see who is connecting.
You can use:
Auth::user()->token()
function to get token model. This is object of class "Token extends Model" so you should be able to use it like any other model.
In addition in my project I also have that model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class OauthAccessToken extends Model
{
//
}
and relation:
class User extends Authenticatable
{
//...
public function accessTokens()
{
return $this->hasMany('App\OauthAccessToken');
}
}
So I can simply access all tokens and for example delete them:
Auth::user()->accessTokens()->delete();
Related
I am trying laravel sanctum for the first time.
I want to issue tokens for an Eloquent Model called Campaign.
This is my Campaign.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Sanctum\HasApiTokens;
class Campaign extends Model
{
use HasApiTokens;
protected $guarded = ['id'];
public function users()
{
return $this->belongsToMany(User::class)->withPivot(['percentage'])->withTimestamps();
}
}
As you can see, I put the HasApiTokens trait on it.
With this, I can issue a token to any campaign like that:
$campaign->createToken('my-token-name');
So far, so good. It works and is correctly stored at the database.
The problem begins when I try to use the token to make any request protected with sanctum's middleware. This is the error that shows when I do it:
Call to undefined method App\\Campaign::getAuthIdentifier()
Well, I guess this getAuthIdentifier() comes from use Illuminate\Foundation\Auth\User class, which is commonly imported on the User model as Authenticatable;
I tried to create this method on my Campaign model and give it a try, that's what I've done:
public function getAuthIdentifier()
{
return 'id';
}
When I tried to post again, it seems to work. But I think it's not correct because it's kind weird. And it gets even worse when I call auth()->user() and I am able to access the Campaign object. I know that this is a consequence of what I have done here.
Can this package issue tokens based on something that is not actually an User?
If you know how to do it correctly, I would appreciate an answer :)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Auth\Authenticatable;
class Campaign extends Model implements AuthenticatableContract
{
use HasApiTokens,Authenticatable;
protected $guarded = ['id'];
public function users()
{
return $this->belongsToMany(User::class)->withPivot(['percentage'])->withTimestamps();
}
}
In addition to your comment, if you like to get campaign send token in the header in the request and then search in the token table to find the related campaign
Continuing with my Laravel 5.5 project, I'm confused as to where you define the slack webhook URL in the Laravel app.
https://laravel.com/docs/5.5/notifications#routing-slack-notifications shows defining a routeNotificationForSlack method on the User (or whatever notifiable model) that returns $this->slack_webhook_url-- but that var is never populated:
class User extends Authenticatable
{
use Notifiable;
public function routeNotificationForSlack()
{
return $this->slack_webhook_url;
}
Should the slack_webhook_url be hardcoded in this model, or is it passed in when you instantiate the notification?
it's up to you how to implement routeNotificationForSlack(), Laravel will only call it and use the return value to determine what url to ping.
If all your users share same webhook endpoint, you can store it in .env, if they are different for each user, return a database column like the example. If it depends on group/privilege, you should implement it accordingly
I am trying to integrate our SSO (Single Sign On solution) to a oldish laravel app and after upgrading to 5.1.26 I want to try the ACL solution but running into an issue. I have added a basic ability to try this out but it doesn't work and I want to help to solve it.
<?php
namespace App\Providers;
use Auth;
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
public function boot(GateContract $gate){
$this->registerPolicies($gate);
$gate->define('create-report', function ($userRoles) {
return in_array('super_admin', $userRoles);
});
}
public function register()
{
//
}
}
And I try this with
if(\Illuminate\Support\Facades\Gate::allows('create-report', $roles)){
dd("This never happens");
} else {
dd("This always happen!");
}
Do I need to "log my user in"? Since we have our central user mgmt system I never handle any users in the app. I only have a user object (fetched from the sso api) saved in a session variable.
Yes
"The Gate will automatically return false for all abilities when there is not an authenticated user or a specific user has not been specified using the forUser method."
Laravel - Authorization - Defining Abilities
I'm just running through the process of upgrading my app to Laravel 5. I was using the Laravel 4 user authentication library, along with my own 'Profile' model, for storing user profile information, defined like this:
User model:
class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract {
//...
public function Profile()
{
return $this->hasOne('Profile');
}
//..
}
Profile model:
class Profile extends Eloquent {
//...
public function User()
{
return $this->belongsTo('User');
}
//...
}
Previously (when the app was Laravel 4), I would be able to access the profile for the logged in user by loading the user object through the Auth facade:
$user = Auth::user();
echo $user->profile->picture;
However, since upgrading to Laravel 5 this has been throwing a Trying to get property of non-object error.
I am able to load the profile, via the user, if I load the user object directly through the user model, like this:
$user = User::findOrFail(Auth::user()->id)->first();
echo $user->profile->picture;
...but this seems like a long-winded way of doing it.
Is there a better way, or is there something I'm missing? Any help appreciated.
If it's what I think it is, then you might need to update config/auth.php's model option to be your user model's class name.
This property is the model that laravel's auth driver will use. By default, it is App\User.
I'm building a web application where users can signup and post questions. Everything went alright until I was trying developing a function where users will be automatically logged in upon registration. I used Auth::login() class just like I used to do with Laravel 3 but I'm getting the following error:
"ErrorException Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Auth\UserInterface, instance of Member given"
while I implemented the class with registered user's creds. I guess Laravel 4 has changed the way the class would work in it's previous version but I can't figure it out in their documentation as well as searching here in StackExchange before I post this question.
Here is the codes in my UserController
public function postCreate() {
$validator = Member::validate(Input::all());
if ($validator->passes()) {
$user = Member::create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'))
));
Auth::login($user);
return Redirect::route('home')->with('message', 'Thanks for registering!');
} else {
return Redirect::route('register')->withErrors($validator)->withInput();
}
}
I'm a bit confused about the default User.php model provided with Laravel 4. I usually would create a User model based on the users table in my database while I would work in laravel 3. But this time in laravel 4 I had to change my user table name to members so that I can use my own model Member.php. Is it alright if I remove the codes in default User model or should I place my own functions at the top keeping the existing codes provided by Laravel?
P.S. I'm relativeley new with the MVC concept and started learning with tutorials on Laravel 3 and that's why I'm finding it hard to get myself used to with Laravel 4.
You must implement UserInterface to fix the error. In addition, if you need password reminder functionality, you have to implement RemindableInterface as well.
In your Member class add the following lines:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Member extends Eloquent implements UserInterface, RemindableInterface {
As the Exception says, your Member-Model needs to implement UserInterface in order to use the Auth helper:
class Member extends Eloquent implements UserInterface
Here a quote from Code Bright by Dayle Rees:
Our User model implements both UserInterface and RemindableInterface. What are these for?
Well the UserInterface let’s Laravel know that the model contains all methods needed for it to
authenticate with Laravel’s own authentication system. The RemindableInterface allows Laravel
to retrieve the users email address or other contact information to allow for the functionality of
sending password reminder emails.