Debug School

rakesh kumar
rakesh kumar

Posted on

Different kind of user Authentication in laravel

Auto-login system allows for secure user authentication
login system Using Otp authentication
login system Using Google authentication

Auto-login system allows for secure user authentication

Route::get('/auto-login', function (Request $request) {
    try {
        if (!$request->has('token')) {
            Log::error('Token missing from request.');
            return redirect('/login')->withErrors('Missing authentication token.');
        }

        $data = Crypt::decrypt($request->query('token'));

        Log::info('Decrypted token:', $data);

        if (now()->timestamp - $data['timestamp'] > 300) {
            Log::error('Token expired:', ['email' => $data['email']]);
            return redirect('/login')->withErrors('Token has expired.');
        }

        $user = User::where('email', $data['email'])->first();

        if (!$user) {
            Log::info('Registering new user:', ['email' => $data['email']]);
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => bcrypt(Str::random(16)),
            ]);
        }

        Auth::login($user);
        Log::info('User logged in successfully:', ['user_id' => $user->id]);

        return redirect('/billing');
    } catch (\Exception $e) {
        Log::error('Auto-login failed:', ['error' => $e->getMessage()]);
        return redirect('/login')->withErrors('Invalid or expired token.');
    }
});
Enter fullscreen mode Exit fullscreen mode

Using Controller

use App\Http\Controllers\AutoLoginController;

Route::get('/auto-login', [AutoLoginController::class, 'handle']);
Enter fullscreen mode Exit fullscreen mode
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class AutoLoginController extends Controller
{
    /**
     * Handle the auto-login functionality.
     */
    public function handle(Request $request)
    {
        try {
            if (!$request->has('token')) {
                Log::error('Token missing from request.');
                return redirect('/login')->withErrors('Missing authentication token.');
            }

            $data = Crypt::decrypt($request->query('token'));

            Log::info('Decrypted token:', $data);

            if (now()->timestamp - $data['timestamp'] > 300) {
                Log::error('Token expired:', ['email' => $data['email']]);
                return redirect('/login')->withErrors('Token has expired.');
            }

            $user = User::where('email', $data['email'])->first();

            if (!$user) {
                Log::info('Registering new user:', ['email' => $data['email']]);
                $user = User::create([
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'password' => bcrypt(Str::random(16)),
                ]);
            }

            Auth::login($user);
            Log::info('User logged in successfully:', ['user_id' => $user->id]);

            return redirect('/billing');
        } catch (\Exception $e) {
            Log::error('Auto-login failed:', ['error' => $e->getMessage()]);
            return redirect('/login')->withErrors('Invalid or expired token.');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

login system Using Otp authentication


  public function store(Request $request)
    {
        // Log the incoming request data for debugging
        Log::info('Request data:', $request->all());
        log::info("coming store here");
        $currentUrl = url()->current();  // Get the current URL
        log::info($currentUrl);
        // Log the start of the authentication process
        Log::info("Starting authentication process");
        // Retrieve the OTP entered by the user
        $inputOtp = $request->input('otp');

        // Retrieve the stored OTP from the session (or from the database if applicable)
        $storedOtp = $request->session()->get('otp');

        // Log the OTP comparison for debugging
        Log::info("Input OTP: $inputOtp, Stored OTP: $storedOtp");

        // Check if the input OTP matches the stored OTP
        if ($inputOtp != $storedOtp) {
            // Log the error and return a JSON response
            Log::info("OTP does not match");
            return response()->json([
                'success' => false,
                'message' => 'The OTP you entered is incorrect.'
            ], 400);  // HTTP Status 400 for Bad Request
        }

        // Log successful OTP verification
        Log::info("OTP matches");

        // Retrieve the phone number from the request
        $phone = $request->input('phone');

        // Clean the phone number by removing the country code (+91)
        $cleanPhone = preg_replace("/^\+91/", "", $phone);

        // Log the cleaned phone number for debugging
        Log::info("Cleaned phone number: $cleanPhone");
        Log::info("Cleaned phone number: $phone");
        // Find the user by phone number



        $user = User::where('number', $phone)->first();

        // If user is not found by phone number, try to find by email
        if (!$user) {
            Log::info("User not found by phone number, trying email search.");
            $user = User::where('email', $phone)->first();  // If no user found by phone, try with email
        }

        // Check if the user exists, if not, return a JSON response with an error
        if (!$user) {
            Log::info("User not found with phone or email: " . $phone);
            return response()->json([
                'success' => false,
                'message' => 'Authentication failed. User not found.'
            ], 404);  // HTTP Status 404 for Not Found
        }

        // Log user details for debugging
        Log::info("User found: " . $user->name);

        // Log the user in without requiring a password
        Auth::login($user);

        // Regenerate the session ID to prevent session fixation attacks
        $request->session()->regenerate();

        // Retrieve the user's role to determine where to redirect
        $role = $user->role;

        // Log the user's role for debugging
        Log::info("User role: $role");
        $inputroute_name = $request->input('route_name');
        // Return a JSON response with success and the role information
        return response()->json([
            'success' => true,
            'message' => 'Logged in successfully!',
            'role' => $role,
            'redirect_url' => $this->getRedirectUrlForRole($role,$inputroute_name)  // Dynamically provide the redirect URL
        ], 200);  // HTTP Status 200 for OK
    }
Enter fullscreen mode Exit fullscreen mode
    private function getRedirectUrlForRole($role,$inputroute_name)
    {

        log::info("getRedirectUrlForRole here");
        log::info("coming here");
        $currentUrl = url()->current();  // Get the current URL
        log::info($currentUrl);
        log::info(strpos($currentUrl, 'partner'));
            // Check if 'partner' exists in the current URL
            if ($inputroute_name == "partnerlogin") {
                log::info("partner coming here");
                // If 'partner' is in the URL, you can handle the redirect logic here
                return route('partner.dashboard');  // Adjust this as per your partner dashboard route
            }
        if ($role == 'admin') {
            return route('admin.dashboard');
        } elseif ($role == 'vendor') {
            return '/';  // Redirect to the root URL (home)
        } else {
            return '/';  // Redirect to the root URL (home)
        }

    }
Enter fullscreen mode Exit fullscreen mode

login system Using Google authentication

In env

GOOGLE_CLIENT_ID=305409954221-ercontent.com
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=https://motoshare.in/auth/google/callback
Enter fullscreen mode Exit fullscreen mode

C:\myworkspace\motoshare-web\config\services.php

   'google' => [
    'client_id' => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect' => env('GOOGLE_REDIRECT_URI'),
      ],
Enter fullscreen mode Exit fullscreen mode

    Route::get('auth/google', [AuthenticatedSessionController::class, 'redirectToGoogle'])->name('google.login');
    Route::get('auth/google/callback', [AuthenticatedSessionController::class, 'handleGoogleCallback']);
Enter fullscreen mode Exit fullscreen mode
 public function redirectToGoogle(Request $request)
    {
        log::info("inside i m redirectToGoogle");
        $from = $request->query('from');
        // You can log or use $from as needed
        Log::info('Redirected from route: ' . $from);
        if ($from) {
            session(['login_from' => $from]);
        }
        return Socialite::driver('google')->redirect();
    }
Enter fullscreen mode Exit fullscreen mode
    public function handleGoogleCallback(Request $request)
    {
        log::info("inside i m handleGoogleCallback");
        $inputroute_name = session('login_from');
        Log::info('Callback from route: ' . $inputroute_name);    

        try {
            $googleUser = Socialite::driver('google')->user();
            Log::info('Google User Data:', (array) $googleUser);

            // Log specific properties if you want
            Log::info('Google User Email: ' . $googleUser->email);
            Log::info('Google User Name: ' . $googleUser->name);
            Log::info('Google User ID: ' . $googleUser->id);

            $currentUrl = url()->current();  // Get the current URL
            log::info($currentUrl);

             $email= $googleUser->email;
             $user = User::where('email', $email)->first();

            if (!$user) {

                Log::info("User not found by phone number, trying email search.");
                return redirect()->route('login')->with('error', 'Email does not exist');
            }


            Auth::login($user);     

            // Retrieve the user's role to determine where to redirect
            $role = $user->role;
            if ($inputroute_name == "partnerlogin") {
                log::info("partner coming here");
                // Redirect to partner dashboard
                return redirect()->route('partner.dashboard'); // <-- Correct!
            }
            if ($role == 'admin') {
                return redirect()->route('admin.dashboard');
            } elseif ($role == 'vendor') {
                return redirect('/'); // Home page
            } else {
                return redirect('/'); // Home page
            }



        } catch (InvalidStateException $e) {
            \Log::error('Socialite InvalidStateException: ' . $e->getMessage());
            return redirect()->route('login')->with('error', 'Email does not exist');
        } catch (\Exception $e) {
            \Log::error('Socialite Exception: ' . $e->getMessage());
            return redirect()->route('login')->with('error', 'Email does not exist');
        }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)