i have a auth login that i make, which have 3 table to auth as admin, how can i fix this? thx
public function postlogin(Request $request)
{
$admin = DB::table('M_ADMIN')->select(['M_ADMIN.PERNR'])->get();
$user = DB::table('M_HEAD_SALLARY')
->join('M_USER', 'M_USER.PERNR', '=', 'M_HEAD_SALLARY.PERNR')
->where('M_USER.PERNR','LIKE','%'.$admin.'%')
->where('M_HEAD_SALLARY.USRID_LONG',strtoupper($request->USRID_LONG))
->where('M_USER.PASS',$request->PASS)
->first();
return redirect('/login');
}
In your LoginController, you can overwrite the attemptLogin method as follow
public function attemptLogin(Request $request) {
$user = Admin::whereHas('M_HEAD_SALLARY', function($query){
// condition
})->whereHas('M_USER', function($query) {
// condition
});
if (Auth::login($user)) {
// Authentication passed...
}
}
Related
I have facing the issue for after login user page 404 error. Please check the below code and help me the issue solve.
web.php
Route::get('/login','UserAuthController#login');
Route::post('/login-user','UserAuthController#LoginUser')->name('login-user');
Route::get('user/myprofile','UserAuthController#UserDashboard');
//Route::get('user/myprofile','UserAuthController#UserProfile')->name('UserProfile');
UserAuthController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Users;
use Hash;
use Session;
class UserAuthController extends Controller
{
public function login(Request $request)
{
return view('pages.login');
}
protected function LoginUser(Request $request)
{
$request->validate([
'username'=>'required',
'password'=>'required'
],[
'username.required'=>"The User Name is Required.",
'password.required'=>"The Password is Required."
]);
$user = Users::where('username', '=', $request->username)->where('status', '=', 1)->first();
if ($user){
if (Hash::check($request->password, $user->password)){
$request->session()->put('userId',$user->userid);
//return redirect('user.myprofile');
//return redirect()->route('user.myprofile');
//return redirect()->intended('user/myprofile');
return redirect('UserDashboard');
}else{
return back()->with('fail', 'Password not matches. Please try again!!');
}
}else{
return back()->with('fail', 'This Username is not registered.');
}
}
public function UserDashboard (){
return view('user.dashboard');
}
}
After Login Page
http://127.0.0.1:8000/UserDashboard
404 NOT FOUND
Hi Replace your code from
return redirect('UserDashboard');
to
return redirect('user/myprofile');
You should redirect with name route like:
Route::get('user/myprofile','UserAuthController#UserDashboard')->name('user-profile');
In Controller:
return redirect()->route('user-profile');
Also, make sure user.dashboard view file exist.
When the user is connected and wishes to consult the feedback section, the user see each feedbacks for eachs users. I would like to know if it's possible to limit this?
For example, if the user is jeremy#gmail.com, Jeremy can see only his feedback.
Here is an idea of my code, I thank you in advance for your help.
public function index(Request $request)
{
$user = $request->user();
$feedbacks = Feedback::query()
->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
\Auth::user()->load('feedbacks');
$feedbacksForThisUser = \Auth::user()->feedbacks;
})
->when($request->has('search'), function (Builder $query) use ($request) {
$query->join('eleves', 'feedbacks.fk_eleve', '=', 'eleves.id')->orderBy('eleves.nom', 'asc')->where('eleves.nom','like','%'.$request->input('search').'%');
})
->paginate(5);
return view('admin.feedbacks.index', compact('feedbacks'))
->with('display_search', $user->hasRole('admin'));
}
Edit
User Model
public function retours()
{
return $this->hasMany('App\Retour', 'user_id', 'id');
}
User Feedback
public function students(){
return $this->belongsTo('App\Student', 'fk_student');
}
public function feedbacks()
{
return $this->hasManyThrough(
'App\Feedback',
'App\Student',
'fk_seance',
'fk_student',
'id',
'id'
);
}
public function user()
{
return $this->belongsTo('App\User', 'id', 'user_id');
}
And
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('instruction', 30);
$table->text('description', 80);
$table->integer('fk_student')->unsigned();
$table->foreign('fk_student')->references('id')->on('students');
Sure. When its a normal user, you can just use feedbacks = \Auth::user()->feedbacks;. This will limit to only the logged in user's feedbacks.
If you want to allow an admin to see all feedbacks, then check for admin, and then provide all. So, for just the user or admin (without the search code) something like this:
public function index(Request $request)
{
if(\Auth::user()->hasRole('admin')){
$feedbacks = Feedback::all();
}else{
\Auth::user()->load('feedbacks');
$feedbacks = \Auth::user()->feedbacks;
}
return view('admin.feedbacks.index', compact('feedbacks'));
}
You can add the search code into either of the if-blocks, depending on how you want to allow users to see the search. You can use when() on the query, but I'll demonstrate with just if to make it easier to understand:
public function index(Request $request)
{
if(\Auth::user()->hasRole('admin')){
if($request->has('search'))
$feedbacks = Feedback::orderBy('nom', 'asc')->where('nom','like','%'.$request->input('search').'%');
else
$feedbacks = Feedback::all();
}else{
\Auth::user()->load('feedbacks');
$feedbacks = \Auth::user()->feedbacks;
}
return view('admin.feedbacks.index', compact('feedbacks'));
}
In LoginController I override the credentials method, like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
return $credentials;
}
And this work pretty fine. But when a try to add a parameter which is not a column of the Users table I don't know how to check there. Some like this:
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['status'] = User::STATUS_ACTIVE;
$credentials['customer-status'] = Customer::STATUS_ACTIVE;
return $credentials;
}
Where can I check if the value is correct? I tried to make an event listener to attempt login, but it doesn't work. My idea is to make an Eloquent query to return an account of customers activities. If more then one, customer-status for this user is true.
If anyone is interested in knowing how I solved it, the explanation is as follows:
Based on this code I found in github: https://gist.github.com/joseluisq/fb84779ea54eaebf54a9d8367117463e
In LoginController.php I override 2 methods(login and sendFailedLoginResponse):
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$this->incrementLoginAttempts($request);
$user = User::where('email', $request->email)->first();
if (!$user) {
return $this->sendFailedLoginResponse($request);
}
$customers = Customer::join('users_customers', 'users_customers.customer_id', 'customers.id')
->where([
['users_customers.user_id', '=', $user->id],
['customers.status', '=', Customer::STATUS_ACTIVE]
])
->count();
if ($customers === 0) {
return $this->sendFailedLoginResponse($request, 'auth.inactive');
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
return $this->sendFailedLoginResponse($request);
}
protected function sendFailedLoginResponse(Request $request, $trans = 'auth.failed')
{
$errors = ['email' => trans($trans)];
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()
->back()
->withErrors($errors);
}
Remember yourself to define message on auth.php and set uses needed.
Ps.: I don't use $credentials['customer-status'] = Customer::STATUS_ACTIVE;,
as I thought I would.
I am switching users in laravel and I succeeded in that as well but the thing is when I redirect the user to the dashboard after successful login it redirects to login form instead I don't know what am I doing wrong. Here is the code I am using.
public function user_reauthenticate(Request $request) {
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password)) {
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
return Redirect::back();
} else {
$response = 'Wrong Credentials';
}
} else {
$response = 'User does not exist';
}
}
Can anyone help me find out the issue?
Edited
You can log in with
Auth::loginUsingId(1);
New edited
// If you have the guard student and multiple auth
$auth = auth()->guard('student');
$objAuth = $auth->loginUsingId($input['new_user']);
//Single Auth
$objAuth = Auth::loginUsingId($input['new_user']);
Add this to your top of the file:- use Illuminate\Foundation\Auth\AuthenticatesUsers;
Afterwards add a if function like below in your already completed code:-
public function user_reauthenticate(Request $request)
{
use AuthenticatesUsers;
$input = Input::all();
$data = User::where('email', $input['email'])->first();
if ($data) {
if (Hash::check($input['password'], $data->password))
{
Session::put('email', $input['email']);
$newuser = Student::find($input['new_user']);
session(['orig_user' => $data->id]);
Auth::login($newuser);
if ($this->attemptLogin($request))
{
return $this->sendLoginResponse($request);
}
}
else
{
$response = 'Wrong Credentials';
}
}
else
{
$response = 'User does not exist';
}
}
After this method override this method as follows:-
protected function authenticated(Request $request, $user)
{
return redirect()->route('dashboard');
}
Check whether your dashboard route is named dashboard or if not name it.
How to redirect store to update method? I tryed the following code:
public function store(ProductRequest $request)
{
return $this->update(new Product, $request);
}
public function update(Product $product, ProductRequest $request)
{
// code
}
However, the first parameter of update need an already in database user and the above code does not work as expected. (it update the entire users in db!)
What is the correct way to achieve that?
public function store(UserRequest $request)
{
return $this->maintain(new User, $request);
}
public function update(User $user, UserRequest $request)
{
return $this->maintain($user, $request);
}
private function maintain($user, $request)
{
//code;
}
The model for the update method could be the problem, your code is okay for this part:
public function store(Request $request)
{
return $this->update(new Product, $request);
}
public function update(Product $product, Request $request)
{
$product->fill($request->all())->save();
// code
}
For example, with route model binding:
Route::resource('products', 'ProductController');
Route::model('products', App\Product::class);
Or with a custom binding:
Route::resource('products', 'ProductController');
Route::bind('products', function($param) {
return Product::where('slug', $param)->first();
});
Make sure you are not using get() in custom binding, it will pass back a collection.