How Can I retrieve logged in user details in router [Laravel 5]? - php

I have created my router block like this:
Route::group(['middleware' => 'access.routeNeedsPermission:view-backend'], function() {
Route::group(['namespace' => 'Hospital'], function () {
Route::resource('hospital','HospitalController',
['except' => app('\App\Http\Controllers\Backend\Access\Hospital\HospitalController')->allowed_actions()]);
Route::post('hospital/locations', 'HospitalController#locations');
});
}
);
And I am writing the method like this
public function allowed_actions(){
$page_access = Pageaccess::where('page_id','hospital-management')->firstOrFail();
$roles = unserialize($page_access->role_id);
$views = unserialize($page_access->view);
$read = unserialize($page_access->read);
$write = unserialize($page_access->write);
$common_variable = Auth::check() ? Auth::user()->id : 0;
$actions = ['create'];
return $actions;
exit;
}
But the Auth::check() returns 0 and I cannot access anything in Auth::user(). Am I missing something?

Related

How to asign user's role in route prefix in Laravel?

I've done something like this:
web.php
Route::group(['prefix' => {User Role}, 'middleware' => 'AuthUser:superadmin,admindesa'], function() {
Route::get('/', 'DashboardC#index');
Route::get('/penduduk', 'PendudukC#index');
Route::get('/penduduk/{id}/detail', 'PendudukC#detail');
});
Route::group(['prefix' => 'superadmin', 'middleware' => 'AuthUser:superadmin'], function() {
Route::get('/pengguna', 'PenggunaC#index');
Route::get('/pengguna/{id}/edit', 'PenggunaC#edit');
Route::post('/pengguna/{id}/prosesedit', 'PenggunaC#prosesEdit');
Route::get('/pengguna/{id}/hapus', 'PenggunaC#hapus');
Route::post('/ajax/pengguna', 'AjaxC#pengguna');
});
AuthUser.php
class AuthUser
{
public function handle($request, Closure $next, ...$roles)
{
$auth = auth('web')->user();
if (!$auth || !in_array($auth->role, $roles)){
\Session::flash('flash_message', array('pesan' => 'Silahkan login untuk melanjutkan', 'tipe' => 'warning'));
return redirect()->route('login');
}
return $next($request);
}
}
Anyone know what should I write to asign user's role in route prefix? {User Role}
I've found the solution by simply adding role variable to the request
web.php
Route::group(['prefix' => '{role}', 'middleware' => 'AuthUser:superadmin,admindesa'], function() {
Route::get('/', 'DashboardC#index');
Route::get('/penduduk', 'PendudukC#index');
Route::get('/penduduk/{id}/detail', 'PendudukC#detail');
});
Route::group(['prefix' => 'superadmin', 'middleware' => 'AuthUser:superadmin'], function() {
Route::get('/pengguna', 'PenggunaC#index');
Route::get('/pengguna/{id}/edit', 'PenggunaC#edit');
Route::post('/pengguna/{id}/prosesedit', 'PenggunaC#prosesEdit');
Route::get('/pengguna/{id}/hapus', 'PenggunaC#hapus');
Route::post('/ajax/pengguna', 'AjaxC#pengguna');
});
AuthUser.php
class AuthUser
{
public function handle($request, Closure $next, ...$roles)
{
$auth = auth('web')->user();
if (!$auth || !in_array($auth->role, $roles)){
return redirect()->route('login')->with('gagal','Silahkan login untuk melanjutkan');
}
$request->role = $auth->role; // <- this one
return $next($request);
}
}
Everytime you want to get {id} in any controller you HAVE to get {role} too like this:
public function detail(Request $request, $role, $id) // <- this one
{
$penduduk = Penduduk::with(['kabupaten', 'kecamatan', 'kelurahan', 'dusun', 'pendudukjb'])->find($id);
$bantuan = array_column(json_decode($penduduk->pendudukjb, TRUE), 'id_master_jenis_bantuan');
$detail = $request->modal ? '_detail' : 'detail';
return view('penduduk/'.$detail, compact('penduduk', 'bantuan'));
}

Laravel session data empty after user login

I am using laravel version 6.17.0.
If I put data to session Session::put('cart_merge', $data) in authenticated() method of AuthenticatesUsers trait and I try to get them with Session::get('cart_merge') in Controller, the session is empty. If I do Session::get('cart_merge') right after insertion in authenticated() method, they are still there.
I tried grouping routes as adviced in https://stackoverflow.com/a/35140419/5821265 but it didn't help.
Why do session doesn't make it untill Controller?
AuthenticatesUsers.php:
protected function authenticated(Request $request, $user)
{
$cart = getCart::getCart();
$savedCart = $user->cart;
if (empty($cart['cart'])){ // Shopping cart is empty
$cart = [];
foreach ($savedCart as $item) {
$product = Product::where('id', $item->id)->where('visibility', 1)->where('stock', '>', 0)->first();
if (is_null($product)) {
continue;
}
if ($item->pivot->amount > $product->stock){
$cart[$item->id]['amount'] = $product->stock;
}
else {
$cart[$item->id]['amount'] = $item->pivot->amount;
}
$cart[$item->id]['name'] = $product->name;
$cart[$item->id]['url'] = $product->url;
$cart[$item->id]['image'] = $product->image;
}
Session::put('cart', $cart);
}
else { // There are some items in shopping cart.
if ($savedCart->isEmpty()){ // User doesn't have any items saved in DB from last session.
foreach ($cart['cart'] as $item_id => $item){
DB::table('product_user')->insert([
'user_id' => $user->id,
'product_id' => $item_id,
'amount' => $cart['cart'][$item_id]['amount'],
'type' => 0
]);
}
}
else { // User has saved items in DB from last session.
Session::put('cart_merge', $savedCart->toArray());
// if I do Session::get('cart_merge') here, the data are correct.
}
}
}
SystemController.php:
class SystemController extends Controller
{
public function index(){
$data = Session:get('cart_merge');
dd($data);
// if I do Session::get('cart_merge') here, null is returned instead of data.
}
}
web.php:
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'SystemController#index');
Auth::routes();
});
You are accessing session in just in class directly
Session is depend on Request.
So might be your request method will route to some controller method and then u can access the session. otherwise how laravel will know whose session it is
Ex
Route::group(['middleware' => 'web'], function () {
Route::get('', function () {
Session::set('test', 'testing');
});
Route::get('other', function () {
dd(Session::get('test'));
});
});
check this at https://stackoverflow.com/a/35140419/4153682
Fixed by changing session driver to SESSION_DRIVER=file instead of cookies in .env file. It seems like cookies option isn't persistent.

Laravel, need show route url domen/specialist/id

I want show domen url user id after signin, example domen/specialist/id.
ALREADY AS DAY 2 IT IS NOT RECEIVED TO DO. Maybe I'm doing something wrong help please.
This my web.php code
// Front End Routes
Route::group([
'namespace' => 'landing',
'middleware' => 'groups',
], function (){
Route::get('/', 'PagesController#index')->name('landing.index');
Route::get('/specialist/{id}', 'SpecialistDashboardController#dashboard')-
>name('frontend.specialist.dashboard');
Route::get('/logout', '\App\Http\Controllers\Auth\LoginController#logout');
});
Specialist Dashboard Controller code
class SpecialistDashboardController extends Controller
{
public function dashboard($id){
$id = Auth::user()->id;
return view('Frontend.specialists.dashboard.index');
}
public function profile_settings(){
return view('Frontend.specialists.profile_settings.index');
}
}
GroupsMiddleware
public function handle($request, Closure $next)
{
// ADMIN = 5
if (\Auth::check() && Auth::user()->groups == 5){
return $next($request);
}
// PATIENTS = 1
elseif(\Auth::check() && Auth::user()->groups == 1){
return redirect()->route('landing.index');
}
// SPECIALISTS = 3
elseif (\Auth::check() && Auth::user()->groups == 3){
return redirect()->route('frontend.specialist.dashboard');
}
}
Error message:
Missing required parameters for [Route: frontend.specialist.dashboard] [URI: specialist/{id}].
Your frontend.specialist.dashboard route requires a id paramter but you didn't provide any when redirecting. Also looking at your SpecialistDashboardController, the $id can be omitted since you're overwriting it with Auth::id().
Try doing this:
# remove the {id} param
Route::get('/specialist', 'SpecialistDashboardController#dashboard')-
>name('frontend.specialist.dashboard');
class SpecialistDashboardController extends Controller
{
...
public function dashboard(){ // remove the $id param
$id = Auth::user()->id;
return view('Frontend.specialists.dashboard.index');
}
...
}
But if in any case you need the id param, you can provide the value for it in redirect by doing
return redirect()->route('frontend.specialist.dashboard', ['id' => $id]);

User authentication via curl request

I've got same login page for every CRM.
These are the steps:
Enter password and login
Send curl to CRM on crm.dev/api/auth/check with user data, which checks if user exists in CRM
CRM returns success if user exists, after this authenticates user via Auth::user('user_data_here') and redirects to main page of CRM
My problem is that auth doesn't work. And no user data is stored in session (because of previous problem).
CRM auth code:
public function checkUserExists(Request $request)
{
$this->redirectIfAuthorized();
$user = User::find($request->uid);
if ($user) {
return ['response' => 'LOGIN_SUCCESS'];
}
return ['response' => 'DB_ERROR'];
}
public function login(Request $request)
{
$this->validateLogin($request);
$user = User::find($request->uid);
$user->remember_token = $request->token;
if ($user->update()) {
Auth::login($user, true);
return redirect()->intended($this->redirectPath());
} else {
return redirect($this->redirectAfterLogout);
}
}
public function redirectIfAuthorized()
{
if (Auth::check()) {
return redirect($this->redirectTo);
}
}
Api route:
Route::group(['prefix' => 'auth'], function () {
Route::post('check', 'LoginController#checkUserExists');
Route::get('login', 'LoginController#login');
Route::get('logout', 'LoginController#logout');
});
And login page's logic for this CURL request
private function sendToken($action, $user, $token)
{
$query = DB::table('user_base')->join('bases', 'bases.id', '=', 'user_base.base_id')
->where('user_base.user_id', $user);
$result = $query->get();
foreach ($result as $row) {
$urlAPI = $row->url_api;
if ($urlAPI == 'http://appliance.dev/api/auth') {
$urlAPI .= '/check';
}
$rsp = $this->curl($urlAPI, array(
'apiKey' => $this->apiKey,
$action => true,
'uid' => $row->base_uid,
'token' => $token
));
}
}
I needed to use routing in web.php file instead of api.php

Laravel 4.2 session::get() method not returning session data in controllers

Hi help me,
login code
public function store()
{
$credentials = array(
'u_email' => Input::get('email'),
'password' => Input::get('password'));
if (Auth::attempt($credentials) ) {
$user = Auth::user()->toArray();
$userrole = with(new User)->get_user_role($user['u_id']);
$userobj['u_id'] = $user['u_id'];
$userobj['u_shortcode'] = $user['u_shortcode'];
$userobj['utype'] = $user['utype'];
$userobj['u_title'] = $user['u_title'];
$userobj['u_fname'] = $user['u_fname'];
$userobj['u_lname'] = $user['u_lname'];
$userobj['u_email'] = $user['u_email'];
$userobj['u_role'] = $userrole;
$userobj['id'] = Session::getId();
Session::put('admin', $userobj);
$value = Session::get('admin');
return Response::json([
'user' => $userobj ],
202
);
}else{
return Response::json([
'flash2' => 'Authentication failed'],
202
);
}
}
and my second controller is:
public function get_sessionobj()
{
var_dump(Session::all());
$value = Session::get('admin');
print_r($value);
exit();
}
when i am calling second controller after login then session data not printed. in login controller Session::get('admin') function returning data. and i am using file driver for session storage. I have seen my session file there was some data like this:
a:5:{s:6:"_token";s:40:"XrUgs7QLPlXvjvyzFaTdmDpqGL0aSZRzkJS0il9f";s:38:"login_82e5d2c56bdd0811318f0cf078b78bfc";s:1:"1";s:5:"admin";a:9:{s:4:"u_id";s:1:"1";s:11:"u_shortcode";s:5:"u1001";s:5:"utype";s:1:"1";s:7:"u_title";s:3:"Mr.";s:7:"u_fname";s:6:"Aristo";s:7:"u_lname";s:5:"Singh";s:7:"u_email";s:24:"chandan.singh#jetwave.in";s:6:"u_role";a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}s:2:"id";s:40:"cd074f7f61fcc88b3d92c482e57e8a12dc888958";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1410525787;s:1:"c";i:1410525787;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}
Call a function get_sessionobj() in store function
Example:
public function store(){
$this->get_sessionobj();
}

Categories