laravel authentication

 authcontroller 

autho login 

auth register

admin.php, that routes register in routeserviceprovider

https://www.youtube.com/watch?v=9VFbIUIiioU&list=PLJlg6RBt94MG7UygN6gE1UHGWBHr4lJqi&index=11&pp=gAQBiAQB

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* @var string
*/
public const HOME = '/admin/home';

/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* @var string|null
*/
protected $namespace = 'App\\Http\\Controllers\\Web';

/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();

$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace('App\\Http\\Controllers\\Api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->prefix('admin')
->group(base_path('routes/admin.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}

/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
}

kernel.php

for passport  'api' => \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

if we give name space correctly , so dont need of declaratlion on web.php

protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'api' => \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,

];

csrf protection only for web based middleware

for api based middleware no csrf

authcontroler 

<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use App\Jobs\SendEmailJob as SEJ;
use App\Mail\MaillableTemplate;
use Illuminate\Support\Facades\Bus;
use App\Events\MyEvent;

class AuthController extends Controller
{

public function login(Request $request)
{
$validatedData = $request->validate([
'password' => 'required|string|min:6',
'identifier' => 'required|string', // Assuming the input field is named 'identifier'
]);

$loginField = filter_var($validatedData['identifier'], FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';

$credentials = [
$loginField => $validatedData['identifier'],
'password' => $validatedData['password'],
];
if (auth()->attempt($credentials)) {
return response()->json([
'status' => 'success',
'message' => 'Welcome back',
'data' => [
'access_token' => Auth::user()->createToken(Str::random(50))->accessToken,
],
], 201);
} else {
return response()->json([
'status' => 'error',
'message' => 'something went wrong! please contact support Team',
], 422);
}
}

public function signup(Request $request)
{
$validatedData = $request->validate([
'mobile' => ['required', 'regex:/^[6789]\d{9}$/', 'unique:users,mobile'],
'email' => 'required|string|unique:users,email',
'name' => 'required|string',
'password' => 'required|string|min:6',
'confirm_password' => 'required|string|min:6|same:password',
]);
$password= $request->password;
// $password=$this->generateRandomPassword();
$user = User::create([
'mobile' => $request->mobile,
'email' => $request->email,
'name' => $request->name,
'password' =>Hash::make($password),
]);
$details = [
'title' => "Mail",
'password'=>$request->mobile,
'subject' => 'Heres Your Login Credentials',
'email' => $request->email,
'mail_type' =>'dummyMaillableTemplate',
'username'=> $request->name,
'url' => route('admin_login'),
];
Bus::dispatch(new SEJ($details));
if(!$user){
return response()->json([
'status' => 'error',
'message' => 'something went wrong! please contact support Team',
], 422);
}
return response()->json([
'status' => 'success',
'message' => 'User created successfully',
], 201);
}


function logout(Request $request)
{
Auth::user()->tokens()->update([
'revoked' => true
]);
// Auth::user()->tokens()->delete();
return response()->json([
'status' => 'success',
'message' => 'Successfully Logged Out',
], 201);
}

}

$request->session()->invalidate();
$request->session()->regenerateToken();

config/auth.php


'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],

routes api

Route::middleware(['auth:api'])->group(function () {
Route::resource('users', UserController::class)->names([
'index' => 'api_users.index',
'create' => 'api_users.create',
'store' => 'api_users.store',
'show' => 'api_users.show',
'edit' => 'api_users.edit',
'update' => 'api_users.update',
'destroy' => 'api_users.destroy',
]);

web.php

Route::middleware(['auth'])->group(function () {
Route::get('/home', function () {
return view('home');
});

composer require laravel/passport

composer require laravel/passport:^10.0
php artisan passport:install php artisan migrate

php artisan passport:install

use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; }

auth.php

'guards' => [ 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],

  1. Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); });

php artisan passport:keys


authcontroller.php

web


<?php

namespace App\Http\Controllers\Web;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use App\Jobs\SendEmailJob as SEJ;
use App\Mail\MaillableTemplate;
use Illuminate\Support\Facades\Bus;
use App\Events\MyEvent;

class AuthController extends Controller
{

public function login(Request $request)
{
$validatedData = $request->validate([
'password' => 'required|string|min:6',
'identifier' => 'required|string', // Assuming the input field is named 'identifier'
]);

$loginField = filter_var($validatedData['identifier'], FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';

$credentials = [
$loginField => $validatedData['identifier'],
'password' => $validatedData['password'],
];
if (auth()->attempt($credentials)) {
return redirect()->route('cards.index')->with('success', 'Welcome Back');
} else {
return redirect()->back()->with('failed', "Please enter correct credentials");
}
}

public function signup(Request $request)
{
$validatedData = $request->validate([
'mobile' => ['required', 'regex:/^[6789]\d{9}$/', 'unique:users,mobile'],
'email' => 'required|string|unique:users,email',
'name' => 'required|string',
'password' => 'required|string|min:6',
'confirm_password' => 'required|string|min:6|same:password',
]);
$password= $request->password;
// $password=$this->generateRandomPassword();
$user = User::create([
'mobile' => $request->mobile,
'email' => $request->email,
'name' => $request->name,
'password' =>Hash::make($password),
]);
$details = [
'title' => "Mail",
'password'=>$request->mobile,
'subject' => 'Heres Your Login Credentials',
'email' => $request->email,
'mail_type' =>'dummyMaillableTemplate',
'username'=> $request->name,
'url' => route('admin_login'),
];
Bus::dispatch(new SEJ($details));
if(!$user){
return redirect()->back()->with('failed', "something went wrong! please contact support Team");
}
return redirect()->route('cards.index')->with('success', 'User Created Successfully.');
}


function logout(Request $request)
{
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();

return redirect()->route('admin_login');
}

}

two level authenticaiton 

means after every login , send otp to mail then autheitcate taht

ist we will check password is correc tor not 


$user = Adminiy::where('email',$request->email)->where('is_active',1)
// ->where('password',Hash::make($request->password))
->first();
if ($user) {
$password=$request->password;
if (Hash::check($password, $user->password)) {

then
$user = Adminiy::where('email',$request->email)->where('is_active',1)
// ->where('password',Hash::make($request->password))
->first();
if ($user) {
$password=$request->password;
if (Hash::check($password, $user->password)) {
if($user)
{
$otp=$this->generateRandomPassword();
$user->email_otp = $otp;
$user->update();
Session::put("email", trim($user->email));
$details = [
'title' => "Terbium One Time Password",
'password'=>$otp,
'subject' => 'Terbium One Time Password',
'email' => $user->email,
'mail_type' =>'dummyMaillableTemplate',
'username'=> 'vamsi',
'url'=>route('emailotpvalidate')
];
Bus::dispatch(new SEJ($details));
return redirect()->route('emailotpvalidate');
}
else
{
//return redirect('loginwithotp')->with('message', 'Welcome to ItSolutionStuff Tutorials!');
return redirect()->route('login')->withInput($request->input())->withError("Email not available");
}
} else {
return redirect()->route('login')->withInput($request->input())->withError("Invalid Credentials");
}

then attempt 

public function EmailValidateotp(Request $request)
{
$request->validate(
[
'otp' => 'required'
]
);
// print_r($request->otp);exit;
$user = Adminiy::where('email',Session::get('email'))->first();
\Log::info("yes");
if($user)
{
if($user->email_otp == $request->otp)
{
// if (Auth::guard('adminiy')->attempt(['email' => $user->email], true)) {
if(Auth::guard('adminiy')->attempt(['email'=> $user->email, 'email_otp'=> $user->email_otp])){
$Admin_session = Admin_session::where("check_login" , 1)->where("check_logout" , 0)->where("user_id" , $user->id)->orderBy('created_at', 'desc')->first();
if($Admin_session){
}elseif (Auth::guard('adminiy')) {
$Admin_session = Admin_session::create([
"user_id" => $user->id,
"check_login" => 1,
"check_logout" => 0,
]);
}
$user->email_otp = "";
$user->update();
return redirect()->route('adminiy.panel');
}
else
{
return redirect()
->route('emailotpvalidate')
->withInput($request->input())
->withErrors(['otp' => 'some thing went wrong please contact support team']);
}
}
else
{

\Log::info("yes");
return redirect()
->route('emailotpvalidate')
->withInput($request->input())
->withErrors(['otp' => 'Incorrect OTP']);

return redirect()->route('emailotpvalidate')->withInput($request->input())->withError("Incorrect Otp");
}
}
//return view('validateotp');
}

===

USER vendor/laravel/framework/src/illuminate/auth/databaseuserprovider.php

pwd

/opt/lampp/htdocs/hpanel/pavan/16_feb/git/terbium_pavan/vendor/laravel/framework/src/Illuminate/Auth


we have to modify the databaseuserprovider.php 

validatecreadentails like this 

public function validateCredentials(UserContract $user, array $credentials)
{
if (array_key_exists('email_otp', $credentials)) {
// Perform your specific logic when email_otp is present
return $credentials['email'] == $user->email && $credentials['email_otp'] == $user->email_otp;
} else {
return $this->hasher->check(
$credentials['password'], $user->getAuthPassword()
);
}
}


laravel i have web.php and admin.php if i login from web.php it will generate one password or authetnicate with one password if login from web.php i cannnot login to admin.php or i canno taccess athis


Yes, you can achieve this behavior in Laravel by making changes to the configuration and routes setup. Here's a general approach to implement it:

  1. Separate Authentication Guards:

    • In your config/auth.php file, define separate guards for the web and admin areas. By default, Laravel uses the web guard for web authentication.
    • Create a new guard (e.g., admin) for admin authentication.
  2. Define Multiple Providers:

    • Within the config/auth.php file, define different user providers for each guard if needed. For example, you might have a database user provider for both guards, but they could point to different database tables.
  3. Update Route Middleware:

    • Define custom route middleware to differentiate between web and admin routes. For example, create a middleware named admin.auth specifically for admin routes.
    • Assign this middleware to the admin routes in your admin.php route file.
  4. Configure Routes:

    • In your web.php file, handle the user login and authentication using the web guard.
    • In your admin.php file, use the admin guard for authentication, and apply the admin.auth middleware to restrict access to admin-specific routes.

Here's an example of how your config/auth.php file might look:

php
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'database',
        'table' => 'users',
    ],
    
    'admins' => [
        'driver' => 'database',
        'table' => 'admins',
    ],
],

In your route files (web.php and admin.php), you'll need to handle authentication accordingly:

  • In web.php, use the auth()->guard('web')->attempt() method for user authentication.
  • In admin.php, use the auth()->guard('admin')->attempt() method for admin authentication.

And in your route middleware, define the admin.auth middleware to ensure that only authenticated admin users can access admin-specific routes.

By setting up separate guards, providers, and middleware for web and admin areas, you can control access based on the user's authentication context.



'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'adminiy' => [
'driver' => 'session',
'provider' => 'adminiy',
],
'api' => [
'driver' => 'token',
'provider' => 'user',
'hash' => true,
],
],

providers

'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'adminiy' => [
'driver' => 'database',
'model' => App\Models\Adminiy::class,
'table'=>'adminiy',
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],

=

if (Auth::guard('adminiy')->user()->role != "admin") {

=

routed middleware

'adminiy' => \App\Http\Middleware\adminiy::class,

app/http/middlware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class adminiy
{
// public function handle($request, Closure $next)
// {
// }
// public function terminate($request, $response){
// }
public function handle($request, Closure $next)
{
if(Auth::guard('adminiy')->check()){
return $next($request);
} else {
return redirect()->route('login');
}
}
public function terminate($request, $response){
}
}

web.php

Route::middleware('adminiy')->group(function () {

=

https://laravel.com/api/7.x/Illuminate/Auth/DatabaseUserProvider.html


after login it will redirect to 

redirectifauthenticated



==

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...