I'm making custom login and authentication, thing is whenever I try to log in, no matter what account I login with it logs into the first account in database
Login Controller function:
public function login(Request $request)
{
$request->validate([
'email' => 'required|min:4',
'password' => 'required|min:4|max:16'
]);
$validatedCredentials = [];
///check if the input is email or a username
$isAnEmail = filter_var($request->email, FILTER_VALIDATE_EMAIL);
if ($isAnEmail) {
$validatedCredentials = ['email' => $request->email, 'password' => $request->password];
} else {
///Is a username
$validatedCredentials = ['username' => $request->email, 'password' => $request->password];
}
///Authenticate
if (Auth::attempt($validatedCredentials, true)) {
$request->session()->regenerate();
// dd(Auth::user()->email);
return redirect()->intended(route('profile', ['locale' => app()->getLocale()]))->with("success", __("loggedInSuccessfully"));
} else {
return back()->with('error', 'Credentials error');
}
public function store(Request $request)
{
// Validating
$request->validate([
'username' => 'required|unique:users|min:4',
'email' => 'required|unique:users|email:rfc,dns',
'contact_phone' => 'nullable|digits_between:9,12',
'bio_en' => 'nullable',
'bio_ar' => 'nullable',
'icon' => 'nullable',
'logo' => 'nullable',
'plan_id' => 'required',
'category_id' => 'required',
'is_local' => 'required',
]);
// Generating Password
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i ) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$pass = implode($pass); //turn the array into a string
$hashedPassword = password_hash($pass, PASSWORD_DEFAULT);
$password = (Str::random(8));
$remember_token = (Str::random(10));
//Insert data into database
$uuid = Str::orderedUuid();
$user = User::create([
'id' => $uuid,
'username' => $request->username,
'email' => $request->email,
// 'password' => $hashedPassword,
'contact_phone' => $request->contact_phone,
'bio_en' => $request->bio_en,
'bio_ar' => $request->bio_ar,
'logo' => $request->logo,
'icon' => $request->icon,
'plan_id' => $request->plan_id,
'category_id' => $request->category_id,
'referred_by_id' => Auth::user()->id,
'password' =>password_hash($password, PASSWORD_DEFAULT),
// 'remember_token' => $remember_token,
]);
$user = Auth::user();
Mail::send('user.mail', ['password' => $password, 'email' => $user->email, 'url' => 'localhost:8888'], function ($message) use ($user) {
$message->from("[email protected]", "Mham360");
$message->to('[email protected]', $user->username);
$message->subject("Your Login Password");
});
if ($user) {
$request->session()->regenerate();
return back()->with("success", __("createdSuccessfully"));
} else {
return back()->with('error', __("somethingWentWrongTryAgainLater"));
}
}
// MIDDLEWARE
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AdminAuthentication
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
{
// $guards = empty($guards) ? [null] : $guards;
// foreach ($guards as $guard) {
// if (Auth::guard($guard)->check()) {
// return $next($request);
// }
// }
if (Auth::check()) {
if(Auth::user()->role == "ADMIN" ){
return $next($request);
}
else {
return redirect(app()->getLocale() . "/")->with("error", "You are not authorized!");
}
} else {
return redirect(app()->getLocale() . '/login')->with('error','ERROR');
}
}
}
and this is the add user function (as in only admin can add users none can register on his own.)
hoping anyone experienced and solved this kind of problem before to share their experience
CodePudding user response:
Sorry for write in answer but i cant comment, where u check the user role?
In this cases is better protect your route with a midleware that check is user was admin.
Imagine you have in your user table the column is_admin
in your view just do a group surrounding your admin routes like that:
Route::middleware([IsAdminMiddleware::class])->group(function(){
//All Routes which needs user to be logged in
});
or
//Individiual Route Middleware
Route::get('/path/to', 'controller@instance')->middleware([IsAdminMiddleware::class]);
As for checking user role, you can basically create a middleware for this using the following steps:
run your php artisan make:middleware IsAdminMiddleware open your
open your IsAdminMiddleware and add this code inside the handle function.
public function handle($request, Closure $next) { if(!Auth::check()){ return redirect()->route('login'); } if(Auth::user()->isAdmin == true){ return $next($request); } return redirect()->back()->with('unauthorised', 'You are unauthorised to access this page'); }
you can see oficial laravel middleware info here.
CodePudding user response:
If you have the middleware auth in your project, you can get data from the logged in user easily like this:
{{ auth()->user()->name }}
In this case, it will print the user name, but you can get all the user data like this:
{{ auth()->user() }}