I'm making a simple user authentication with laravel passport, I made an AuthController where I put login and register functions, whenever I try to login with the right email and password I get
{"message":"invalid user"}
its like the attempt() method always returning false, I am using laravel 8.
here is AuthController.php
<?php
namespace App\Http\Controllers;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request){
if(Auth::attempt($request->only('email', 'password'))){
$user=Auth::user();
return $user;
}
return response([
'message'=> 'invalid user'
], 401);
}
}
user model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname',
'lastname',
'email',
'password',
'phone',
'skype',
'birthdate',
'address',
'postalcode',
'city',
'country',
'status',
'image',
'description',
'geo_lat',
'geo_lng'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
AuthServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
Related
I want to create users with factories and directly assign roles to them. However, I encountered an error while seeding.
My Error was like there :
Method Illuminate\Database\Eloquent\Collection::assignRole does not exist.
Here is the code from my databaseSeeder.php :
$user = User::factory(10)->create()->assignRole('Admin');
That is my UserFactory code. This is default, I dont change anithing:
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
This is my user model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class User extends Authenticatable implements JWTSubject, HasMedia
{
use HasApiTokens, HasFactory, Notifiable, HasRoles, InteractsWithMedia;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'e-mail',
'passwords',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Please help me, Thanks!
Try assigning the role in your User factory callback like so:
class UserFactory extends Factory
{
...
public function configure()
{
return $this->afterCreating(function (User $user) {
$user->assignRole('Administrator');
});
}
...
This method will be automatically run when you run the factory. After each create it will run assignRole on the created User model.
Use the factory like so:
User::factory()->count(10)->create();
https://laravel.com/docs/8.x/database-testing#factory-callbacks
On laravel 9.19, laravel/passport": "^11.3 site
I added some more custom fields into users table, and making login method with code like :
public function login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
When I read logged user :
$user = Auth::user();
\Log::info($user);
$user has no my custom fields.
Just common app/Models/User.php :
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
How have I to define my custom fields ?
"laravel/framework": "^9.19",
"laravel/passport": "^11.3",
Thanks in advance!
I am having an issue following a tutorial on YouTube about relationships.
I have replicated this code from the tutorial and I keep getting errors.
I've tried changing the controller code from auth() to app etc.
Also, I've tried re-running migrations:fresh etc and nothing.
User Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Cashier\Billable;
class User extends Authenticatable
{
use Notifiable, Billable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the Instance associated with the user.
*
* #return HasMany
*/
public function instance()
{
return $this->hasMany(Instance::class);
}
}
Instance Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Instance extends Model
{
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
class SyncController extends Controller
{
public function successful()
{
return auth()->user()->instance()->create(['name' => 'test']);
}
}
Error
Call to a member function instance() on null {"exception":"[object] (Error(code: 0): Call to a member function instance() on null at /home/#/cc.#.io/app/Http/Controllers/SyncController.php:14)
[stacktrace]
Edit:
Route::middleware(['auth'])->group(function() {
Route::get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/subscribe', SyncController::class);
});
Check if your route is guarded by auth middleware. If not you can add that in order to fix. You might use Route group like following -
Route::group(['middleware' => ['auth']], function () {
Route::resource('your_url', 'YourController');
// Or whatever route you want to add...
});
This is because the auth()->user is getting null and it will be necessary to check if the value was actually received after the call was made.
I am trying to get all user in my table but I get an error 403 user does not have the necessary rights. I am using laratrust and vuejs. I have already logged in as a superadministrator. This is my controller class
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('role:user|superadministrator');
}
public function index()
{
return view('user.index');
}
public function getusers(){
$theUser = Auth::user();
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}
}
My api route
Route::get('/allusers','UserController#getusers');
I have tried to go through the documentation but no success.Kindly help me solve this issue
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laratrust\Traits\LaratrustUserTrait;
class User extends Authenticatable
{
use LaratrustUserTrait;
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
What about if you try this:
public function getusers(Request $request){
$theUser = $request->user('api');
if ($theUser->hasRole('superadministrator')) {
return $users;
}
}
I need to change default resetpassword message so i make my own ResetPassword notification and when i do that I got this Error Declaration of App\User::sendEmailVerificationNotification($token) should be compatible with Illuminate\Foundation\Auth\User::sendEmailVerificationNotification()
code in User model:
<?php
namespace App;
use App\admin\Course;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable; // حتى اقدر ارسل اله اشعار
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','type','mobile',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function courses()
{
return $this->belongsToMany(Course::class, 'course_user', 'user_id', 'course_id');
}
public function routeNotificationForNexmo($notification)
{
return $this->mobile;
}
public function sendPasswordResetNotification($token)
{
$this->notify(new \App\Notifications\ResetPassword($token));
}
public function sendEmailVerificationNotification($token)
{
$this->notify(new \App\Notifications\VerifyEmail($token));
}
}
Why !!