User Redirection based on Roles | Laravel - laravel

I want to redirect user to other view based on their roles.
for admin i want to redirect it to /home view and for normal user redirect it to emDashboard view. can anyone help me with this?
Thank you guys.
this is my Login Controller
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest')->except([
'logout',
]);
}
public function login()
{
return view('auth.login');
}
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$email = $request->email;
$password = $request->password;
$dt = Carbon::now();
$todayDate = $dt->toDayDateTimeString();
$activityLog = [
'name' => $email,
'email' => $email,
'description' => 'has log in',
'date_time' => $todayDate,
];
if (Auth::attempt(['email'=>$email,'password'=>$password,'status'=>'Active'])) {
DB::table('activity_logs')->insert($activityLog);
Toastr::success('Login successfully :)','Success');
return redirect()->intended('home');
}elseif (Auth::attempt(['email'=>$email,'password'=>$password,'status'=> null])) {
DB::table('activity_logs')->insert($activityLog);
Toastr::success('Login successfully :)','Success');
return redirect()->intended('home');
}else{
Toastr::error('fail, Wrong Username or Password','Error');
return redirect('login');
}
}
Route for Login and Home Dashboard
Route::controller(LoginController::class)->group(function (){
Route::get('/login', 'login')->name('login');
Route::post('/login', 'Authenticate');
Route::get('/logout', 'logout')->name('logout');
Route::controller(HomeController::class)->group(function () {
Route::get('/home', 'index')->name('home');
Route::get('em/dashboard', 'emDashboard')->name('em/dashboard');
this is the users Model
protected $table = 'users';
protected $fillable = [
'name',
'rec_id',
'email',
'join_date',
'phone_number',
'status',
'role_name',
'avatar',
'password',
];

Add a if check before return redirect()->intended('home'); in your authenticate method... something like this
if(Auth()->user()->role_name == "admin"){
return redirect()->intended('home');
} else {
return redirect()->intended('em/dashboard');
}

Related

Laravel Auth::attempt ans Hash::check not working

I try make rest API with Laravel 8 + Sanctum. And my database is MySql Maria DB.
I create LoginController and make function call login. When i try my API, it's always return Unauthorized. I pretty sure my USERNAME and PASSWORD is correct.
This is my LoginController
public function store(Request $request) {
$user = User::create(
[
"USERNAME" => $request->username,
"PASSWORD" => Hash::make($request->password),
"ADM_MST_SITE_ID" => 0,
]
);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
public function login(Request $request)
{
$data = $request->validate([
'username' => 'required|string',
'password' => 'required|string'
]);
$user = User::where('username', $data['username'])->first();
$credentials = request(['username', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$token = $user->createToken('apiToken')->plainTextToken;
$res = [
'user' => $user,
'token' => $token
];
return response($res, 201);
}
Model
////
protected $table = 'adm_mst_user';
protected $guarded = ['ID'];
public function getAuthPassword()
{
return $this->PASSWORD;
}
////
The store function is work well, the new data are inserted to my database. But, when i login with username and password, it's not working.
I try 2 different auth check, using Auth::attempt and Hash::check.
I don't know where the error coming from. It's always return Unauthorized.
$user = User::where('username', $data['username'])->first();
$this->guard()->login($user);
and make a guard function in same controller
protected function guard()
{
return Auth::guard();
}
import use Illuminate\Support\Facades\Auth; in top
include
use Illuminate\Support\Facades\Hash;
You need to make it with email not with username
$credentials = request(['email', 'password']);
OR, modify your attempt code
if(!Auth::attempt(['username' => $credentials['username'], 'password' => $credentials['password']))
this code worked with sanctum
use App\Models\User;
use Illuminate\Support\Facades\Hash;
function login($candidate)
{
$user = User::where('username', $candidate['username'])->first();
if (!$user || !Hash::check($candidate['password'], $user->password)) {
return [
'message' => 'These credentials do not match our records.'
];
}
$token = $user->createToken('my-token')->plainTextToken;
return [
'user' => $user,
'token' => $token
];
}

How to login right after registration in Laravel?

I am trying to register a new user into my system, and right after make the login automatically. How can I call another function in the same Controller and pass $request variables to it?
I did the var_dump, login function is getting data, the login is being made, but it's not redirecting to index (line 28)
public function login(Request $request)
{
//var_dump($request->only('email', 'password'));
$credentials = [
'email' => $request->email,
'password' => $request->password,
];
if(Auth::attempt($credentials)) {
return redirect()->route('movie.index');
}
return redirect()->route('login')->with([
'error' => 'danger',
'msg' => 'Error message',
]);
}
public function register(Request $request)
{
$newUser = new User;
$newUser->name = $request->name;
$newUser->email = $request->email;
$newUser->password = Hash::make($request->password);
$newUser->save();
$this->login($request);
}
Right way is
Auth::login($newUser);
Then redirect to your page after login.

Laravel passport create token doesnt work on plesk server

I use passport in my laravel project to authenticate users by api. API work correctly on my local host. But after i deploy it on Plesk server token doesnt create. Always show Server Error.
public function login(Request $request) {
$validator = Validator::make($request->all(),[
'email' => 'required',
'password' => 'required',
]);
if($validator->fails()) {
return response()->json(["validation errors" => $validator->errors()]);
}
$email = $request->email;
$password = $request->password;
error_log($password);
$user = DB::table("users")->where([["email", "=", $email]])->first();
if(is_null($user)) {
return response()->json(["success" => false, "message" => "User doesn't exist"]);
}
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$token = $user->createToken('token')->accessToken;
$success['success'] = true;
$success['user'] = $user;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token;
return response()->json(['success' => $success ], 200);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
$token = $user->createToken('token')->accessToken;
This line throw error
Problem was in my AuthServiceProvider
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
'Medicare\Model' => 'Medicare\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
//
}
}
After i commented 'Medicare\Model' => 'Medicare\Policies\ModelPolicy' everything works fine.

Laravel - Call to undefined method App\\User::getAvatarUrlAttribute()

I am using Laravel-5.8 as backend for an application. I have written all the Api for the endpoints.
Laravel: ApiController
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\User;
use App\Activity;
use Avatar;
use Storage;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Mail;
use Audit;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class ApiController extends Controller
{
public $successStatus = 200;
public function __construct() {
}
protected function guard()
{
return Auth::guard();
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()->email
], 200);
}
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|string|email|max:255|unique:users',
// 'phone' => 'required',
// 'password' => 'required',
'password' => 'required|string|min:6',
// 'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$input = $request->all();
// code for check email / username / phone exist or not
if(isset($input['email'])){
$alreadyExist = User::where(function ($query) use ($input) {
$query->where('email', '=', $input['email']);
})->get();
}
if (count($alreadyExist->toArray()) > 0) {
return $this->returnResponse(false, ['error' => 'Email Already Exist'], 1, 'User Data Already Exist');
}
// code for register user
$user = new User();
$user->name = $input['name'];
$user->email = $input['email'];
$user->password = bcrypt($input['password']);
$user->save();
$mainData = array();
$mainData['to'] = $user->toArray()[0]['email'];
$mainData['from'] = "support#tsllimited.com";
$mainData['subject'] = "Successful Signup";
$mainData['content'] = "Your signup was successful, you can login with the credentials.";
$this->mailSend($mainData);
Activity::create([
'user_id' => $user->id,
'owner_id' => $user->client_id,
'type' => "User Registration",
'title' => "Successful Signup of User",
'state' => 2,
'created_at'=> date('Y-m-d H:i:s')
]);
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}
public function login(Request $request) {
$authenticated = false;
$validator = Validator::make($request->all(), [
'email' => 'required|string|email',
'password' => 'required|string',
'remember' => 'boolean'
]);
if ($validator->fails()) {
return $this->returnResponse(false, ['error' => $validator->errors()], 1, 'Invalid User Data');
}
$remember = request('remember') ? true : false;
if (Auth::guard('web')->attempt(['email' => request('email'), 'password' => request('password')], $remember)) {
$authenticated = true;
}
if ($authenticated == true) {
$user = Auth::guard('web')->user();
$date = date('Y-m-d');
$success['userId'] = $user->id;
$success['avatar'] = url('/storage/user') . '/' . $user->avatar;
$success['email'] = $user->email;
$success['token'] = $user->createToken('MyApp')->accessToken;
return $this->returnResponse(true, $success);
} else {
$success = array();
return $this->returnResponse(false, $success, 1, 'Invalid User Credential');
}
}
}
api.php
Route::group([
], function () {
Route::post('login', 'ApiController#login');
Route::post('register', 'ApiController#register');
Route::post('forgetPassword', 'ApiController#forgetPassword');
Route::group([
'middleware' => 'auth:api'
], function() {
Route::get('logout', 'AuthController#logout');
Route::get('user', 'AuthController#user');
});
});
I stalled and configured Laravel Passport and also Spatie. I have checked the code and don't know what the error really is. When I test the resgister Post Request on the POSTMAN, I got the error shown below:
See the POSTMAN preview side:
What could have caused the error and how do I resolve it?
You do not have the column avatar on your users table.
Maybe you did not use the trait you need in your User class
class User extends Authenticatable {
use HasAvatar;
// ...
}
I eventually solved the problem myself. The issue is that, I forgot to add:
public function getAvatarUrlAttribute()
{
return Storage::url('avatars/'.$this->id.'/'.$this->avatar);
}
to User Model.
Thanks

Laravel 4 Authentication does not work and gives NO ERROR

I have been searching for solutions and changing my code back and forth but nothing worked for me and I honestly have given up hope to fix it by myself.
It stays on the same page and does not Redirect::to('test2'), but stays in the same page and when I remove the else { return Redirect::to('login'), it gives me a blank page.
Any help would be extremely appreciated.
This is my user model file:
protected $fillable=['email', 'password'];
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
protected $primaryKey = 'id';
public static $rules = array(
'email' => 'required|email',
'password' => 'required',
);
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
This is my routing functions:
Route::get('/login', function(){
return View::make('login');
});
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userData)) {
return Redirect::to('test2');
echo 'SUCCESS!';
} else {
return Redirect::to('login');
}
}
I have been struggling around with the hash at beginning.
1. If the length of your password column isn't 60 then it wouldn't allow you to login.
2. Before logging via Auth::attempt() instead try to fetch the data of the user using his username
and then compare the password using Hash::check()
try something this
Route::post('/login', function(){
$validator = Validator::make(Input::all(), User::$rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$email=Input::get('email');
$user=User::where('email','=',$email)->first();
$bool=Hash::check('your password for the email',$user->password);
if(bool)
{
if (Auth::attempt(Input::only('email','password')))
{
return Redirect::to('test2');
echo 'SUCCESS!';
}else{
return Redirect::to('login');
}
}else{
return echo 'password didn't matche';
}
}

Resources