Laravel multi table authentication is not logging in - php

In my laravel project , am implementing another login for agencies, which i want to take from agencies table.Agencies table have email and password fields. But when i try to login it not get logged in and redirecting to same page and prducing validation error.But i provided exact email and password from agencie table
Following is my code in model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Agencie extends Authenticatable
{
use Notifiable;
use Sortable;
protected $guard = 'agencie';
protected $table = 'agencies';
protected $primaryKey = 'agency_id';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'agency_id', 'agency_name','agency_user_name' ,'agency_password', 'agency_city', 'agency_state', 'agency_zip', 'agency_email','status','created_at','updated_at'
];
}
Following i have addeed to config/auth.php
'guards' => [
'agencie' => [
'driver' => 'session',
'provider' => 'agencies',
],
],
'providers' => [
'agencies' => [
'driver' => 'eloquent',
'model' => App\Agencie::class,
],
],
Following is my code in LoginController
<?php
namespace App\Http\Controllers\Agency\AgencyAuth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Hesto\MultiAuth\Traits\LogsoutGuard;
use JsValidator;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers, LogsoutGuard {
LogsoutGuard::logout insteadof AuthenticatesUsers;
}
protected $validationRules = [
'email' => 'required|email',
'password' => 'required'
];
/**
* Where to redirect users after login / registration.
*
* #var string
*/
// public $redirectTo = '/user/home';
public $redirectTo = '/user/dashboard-graph';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest:agencie', ['except' => 'logout']);
// $this->middleware('guest:agency')->except('logout');
}
public function username()
{
return 'agency_email';
}
/**
* Show the application's login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
$validator = JsValidator::make($this->validationRules,[],[],'#loginform');
return view('agency.auth.login')->with('validator', $validator);
}
/**
* Get the guard to be used during authentication.
*
* #return \Illuminate\Contracts\Auth\StatefulGuard
*/
protected function guard()
{
return Auth::guard('agencie');
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
}
I have added following codes to app/Expecations/Handler.php
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$middleware = request()->route()->gatherMiddleware();
$guard = config('auth.defaults.guard');
foreach($middleware as $m) {
if(preg_match("/auth:/",$m)) {
list($mid, $guard) = explode(":",$m);
}
}
switch($guard) {
case 'agencie':
$login = 'agency/login';
break;
default:
$login = 'user/login';
break;
}
return redirect()->guest($login);
}
I have also added additonal 2 files in middleware named RedirectifAgency.php & Redirectifnotagency.php
Following is the code
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAgency
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'agencie')
{
if (Auth::guard($guard)->check()) {
return redirect('agency/home');
}
return $next($request);
}
}
What is the problem here.Please help

Related

Error Invalid route action: [App\Http\Controllers\Auth\AuthController] when trying to set up authentication in Laravel

I am trying to update an old (5.2) laravel installation to the newest one (9.2) and most is working except the authentication part.
I already installed laravel/ui, I have an authentication middleware, route and controller but for some reason I get:
Invalid route action: [App\Http\Controllers\Auth\AuthController].
My Authenticate.php middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string|null
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
}
My route in web.php :
Route::get('/login', 'App\Http\Controllers\Auth\AuthController')->name('login');
And my AuthController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Topsite\Dataroom\Models\LogEntry;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\RegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use RegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* The custom login view.
*
* #var string
*/
protected $loginView = 'pages.login';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
/**
* Send the response after the user was authenticated.
*
* #param \Illuminate\Http\Request $request
* #param bool $throttles
* #return \Illuminate\Http\Response
*/
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
LogEntry::create([
'account_id' => Auth::id(),
'message' => 'Ingelogd'
]);
return redirect()->intended($this->redirectPath());
}
}
I thought maybe I need to set a method in the route so I changed the route to:
Route::get('/login', 'App\Http\Controllers\Auth\AuthController#handleUserWasAuthenticated')->name('login');
But this gives:
Too few arguments to function App\Http\Controllers\Auth\AuthController::handleUserWasAuthenticated(), 1 passed in C:\xampp\htdocs\dataroom.website.nl.test\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
I think the $throttles variable is empty but what needs to be passed there? Or maybe I am thinking wrong alltogether and the fix is something else?

Test laravel sanctum with tokens

I would like to test if a user is logged out,I am using Sanctum with Laravel Breeze, I am trying like this:
public function test_users_can_logout()
{
$this->signIn();
$response = $this->postJson(
'/api/logout'
);
$this->assertGuest();
}
And this is AuthenticatedSessionController .php, This came from Breeze, I modified it:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Handle an incoming authentication request.
*
* #param \App\Http\Requests\Auth\LoginRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function store(LoginRequest $request)
{
$request->authenticate();
$token = $request->user()->createToken('MyAuthApp')->plainTextToken;
return response()->json(
[
'access_token' => $token,
'token_type' => 'Bearer',
'user' => $request->user()
]
);
}
/**
* Destroy an authenticated session.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function destroy(Request $request)
{
$request->user()->tokens()->delete();
return response()->json(
[
'message' => 'log out successfully'
]
);
}
}
LoginRequest.php
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => 'required|string|email',
'password' => 'required|string',
];
}
/**
* Attempt to authenticate the request's credentials.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function authenticate()
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->filled('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => __('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* #return void
*
* #throws \Illuminate\Validation\ValidationException
*/
public function ensureIsNotRateLimited()
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*
* #return string
*/
public function throttleKey()
{
return Str::lower($this->input('email')).'|'.$this->ip();
}
}
TestCase.php
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Laravel\Sanctum\Sanctum;
use App\Models\User;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
protected function signIn($user = null)
{
$user = $user ?: User::factory()->create();
Sanctum::actingAs($user);
return $user;
}
}
EDITED: now I am testing only the logout route, my test fails, maybe because sanctum is using cookies? is it ok use sanctum with breeze?
I would like to test if the token no longer exists, what can I do?

User login does not work in laravel with sql server. previously created database

I am working on a project where the database on sql server already existed, so I had to change the names of the tables and columns to run the user registry. Registration works perfectly, now, login does not work. When trying to login, the page does nothing, just reload. If you could help me, I would appreciate it very much, thanks
------------User model--------------
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
protected $table = 'tb_postulantes';
protected $primaryKey = 'id_postulante';
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'nombre_postulante', 'appaterno_postulante', 'correo_postulante', 'password_postulante',
'apmaterno_postulante', 'telefono_postulante', 'fechaingreso_postulante', 'estado_postulante'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password_postulante', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
-------RegisterController----------
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'nombre_postulante' => ['required', 'string', 'max:255'],
'correo_postulante' => ['required', 'string', 'email', 'max:255', 'unique:tb_postulantes,correo_postulante'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'nombre_postulante' => $data['nombre_postulante'],
'correo_postulante' => $data['correo_postulante'],
'password_postulante' => Hash::make($data['password']),
'appaterno_postulante' => $data['nombre_postulante'],
'apmaterno_postulante' => $data['nombre_postulante'],
'telefono_postulante' => $data['nombre_postulante'],
'fechaingreso_postulante' => '2012-02-21T18:10:00',
'estado_postulante' => '1',
]);
}
}
----------LoginController--------
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function beforelogin()
{
return view('Auth.beforelogin');
}
}
well first of all Laravel authentication uses field 'email' to login user - you dont have this field in your User model so if you want to change this you have to define username in your LoginController like so:
public function username()
{
return 'correo_postulante';
}
And for different password field you can use accessor in your User Model like so:
public function getAuthPassword()
{
return $this->password_postulante;
}
You can find some more informaction in Laravel Documentation https://laravel.com/docs/5.5/authentication#included-authenticating
But if you want to use all three parameters to log in users I will recommend making your own LoginController with different logic.

Laravel JWT - Getting Unauthenticated with the valid login token

I am working on a simple JWT authentication system. User will get a token from login and when he passes the token, the user information will be given as the response. I have followed the procedure from: https://jwt-auth.readthedocs.io/en/develop/laravel-installation/ .
When I pass email and password to the login method I am able to get a token. But when I pass the token (to the me function) it returns 'Unauthorized'.
User Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
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',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
```````
api.php (Route)
`````
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'AuthController#login');
Route::post('logout', 'AuthController#logout');
Route::post('refresh', 'AuthController#refresh');
Route::post('me', 'AuthController#me');
});
````
AuthController
```
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\User;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
//return response()->json(User::all());
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
//return response()->json("hellllo");
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
```

Register by phone number only laravel

how are you ?
i'm new in laravel and i'm working in someone project and i want to register by phone number instate of email so m i can login by phone number only but is there any way to register by phone number only and get SMS verification after register
so any one will help me please
this is register controller code
<?php
namespace App\Http\Controllers\Auth;
use App\Models\Auth\Role\Role;
use App\Notifications\Auth\ConfirmEmail;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use App\Models\Auth\User\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Ramsey\Uuid\Uuid;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$rules = [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
];
if (config('auth.captcha.registration')) {
$rules['g-recaptcha-response'] = 'required|captcha';
}
return Validator::make($data, $rules);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User|\Illuminate\Database\Eloquent\Model
*/
protected function create(array $data)
{
/** #var $user User */
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => Uuid::uuid4(),
'confirmed' => false
]);
if (config('auth.users.default_role')) {
$user->roles()->attach(Role::firstOrCreate(['name' => config('auth.users.default_role')]));
}
return $user;
}
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* The user has been registered.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function registered(Request $request, $user)
{
if (config('auth.users.confirm_email') && !$user->confirmed) {
$this->guard()->logout();
$user->notify(new ConfirmEmail());
return redirect(route('login'));
}
}
}
this is the api register controller code
<?php
namespace App\Http\Controllers\Api\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterRequest;
use App\Models\Auth\User\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles user registration via REST API
|
*/
/**
* Handle a registration request for the application.
*
* #param RegisterRequest $request
* #return \Illuminate\Http\Response
*/
public function register(RegisterRequest $request)
{
$user = $this->create($request->all());
// attach role
$role = \App\Models\Auth\Role\Role::where('name', 'user')->first();
$user->roles()->attach($role);
event(new Registered($user));
$token = $user->createToken('Default')->accessToken;
return response()->json(["token" => $token, "user" => User::find($user->id)]);
}
/**
* Verifies user's mobile
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function verifyMobile(Request $request)
{
Validator::make($request->all(), [
'mobile_number' => 'required|string|exists:users,mobile_number'
])->validate();
$user = User::where('mobile_number', $request->mobile_number)->first();
$user->mobile_verified = 1;
$user->save();
$token = $user->createToken('Default')->accessToken;
return response()->json(["token" => $token, "user" => $user]);
}
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function sendResetLinkEmail(Request $request)
{
Validator::make($request->all(), [
'email' => 'required|email'
])->validate();
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$response = Password::broker()->sendResetLink(
$request->only('email')
);
return $response == Password::RESET_LINK_SENT
? response()->json(["message" => "Email Sent"])
: response()->json(["message" => "Email Not Sent"], 400);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\Auth\User\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
]);
}
}
and this is register request code
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile' => 'required|unique:users',
'password' => 'required|min:6'
];
}
}
and this is login controller code
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Log the user out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
/*
* Remove the socialite session variable if exists
*/
\Session::forget(config('access.socialite_session_name'));
$request->session()->flush();
$request->session()->regenerate();
return redirect('/');
}
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
$errors = [$this->username() => __('auth.failed')];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
$errors = [];
if (config('auth.users.confirm_email') && !$user->confirmed) {
$errors = [$this->username() => __('auth.notconfirmed', ['url' => route('confirm.send', [$user->email])])];
}
if (!$user->active) {
$errors = [$this->username() => __('auth.active')];
}
if(!$user->hasRole('administrator')) {
$errors = [$this->username() => 'Only administrator can login'];
}
if ($errors) {
auth()->logout(); //logout
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors($errors);
}
return redirect()->intended($this->redirectPath());
}
}
and this is api login controller code
<?php
namespace App\Http\Controllers\Api\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users via REST API
|
*/
public function authenticate(LoginRequest $request)
{
$username = filter_var($request->login, FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';
if (Auth::attempt([$username => $request->login, 'password' => $request->password])) {
$user = Auth::user();
$token = $user->createToken('Default')->accessToken;
return response()->json(["token" => $token, "user" => $user]);
}
return response()->json(["error" => "Invalid Login"], 400);
}
}

Categories