Sorry because my English is weak and I can not speak well!!
This is the route I defined on the web.php page :
<?php
use App\Http\Controllers\Controller;
use App\Http\Controllers\GoogleAuthController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UrlController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('project.index');
});
Route::group(['middleware' => ['auth' , 'InfoFolder' , 'verified' , 'Roles'] , 'prefix' => 'users/'] , function(){
Route::get('{url}', [UrlController::class , 'urlpanel'])->name('users_url');
});
And my controller code :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class UrlController extends Controller
{
//
public function urlpanel($url){
$admin = "admin";
$pages = "admin.pages";
$charts = "admin.pages.charts";
$examples = "admin.pages.examples";
$forms = "admin.pages.forms";
$mailbox = "admin.pages.mailbox";
$tables = "admin.pages.tables";
$UI = "admin.pages.UI";
$link_panel = [
'index' => "$admin.index",
'index2' => "$admin.index2",
'index3' => "$admin.index3",
'calendar' => "$pages.calendar",
'widgets' => "$pages.widgets",
'chartjs' => "$charts.chartjs",
'flot' => "$charts.flot",
'inline' => "$charts.inline",
'404' => "$examples.404",
'500' => "$examples.500",
'blank' => "$examples.blank",
'invoice-print' => "$examples.invoice-print",
'invoice' => "$examples.invoice",
'lockscreen' => "$examples.lockscreen",
'login' => "$examples.login",
'profile' => "$examples.profile",
'register' => "$examples.register",
'advanced' => "$forms.advanced",
'editors' => "$forms.editors",
'general' => "$forms.general",
'compose' => "$mailbox.compose",
'mailbox' => "$mailbox.mailbox",
'read-mail' => "$mailbox.read-mail",
'data' => "$tables.data",
'simple' => "$tables.simple",
'buttons' => "$UI.buttons",
'general' => "$UI.general",
'icons' => "$UI.icons",
'sliders' => "$UI.sliders",
];
$link_permission_owner = [
'index2',
];
if(!isset($link_panel[$url])){
return abort(404);
}
if(in_array($link_panel[$url] , $link_panel)){
if(in_array($url , $link_permission_owner) && Auth::user()->hasRole(['member']))
{
return abort(404);
}
try {
$active = "active";
return view($link_panel[$url] , compact('active'));
}
catch (\Exception $e)
{
return abort(404);
}
try {
$active = "active";
return view($link_panel[$url] , compact('active'));
}
catch (\Exception $e)
{
return abort(404);
}
}
}
}
This is the code I wrote for users to access the files
But it is very dirty
Is there no better way to reach users?
I want some of the pages I have specified in the presentation to be viewed only by admins
Thank you for your help
Step one, get a laravel package that is going to help you manage roles and permissions, I would recommend something like spatie laravel permissions
Step two would be to have a controller for reporting and assign it a route, when a user with a particular role, logs in, then just get redirected to that route.
For redirecting part you can use middleware for this purpose and then in controller constructor use it as in the example below.
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
And then you need to secure routes where you want from user to be logged in to access.
Route::group(['middleware' => 'auth'], function() {
Route::get('/yourReportPath', 'YourReportController#index');
});
Please do a little reading on middleware here
Related
In Laravel 8 app with inertiajs/inertia-vue 0.7/vuejs2 with fortify (but without jetstream)
I use "spatie/laravel-medialibrary": "^9.9" for avatar uploading like
$loggedUser = auth()->user();
$avatar_file_path = $avatarImageUploadedFile->getPathName();
$loggedUser->addMedia( $avatar_file_path )->toMediaCollection('avatar');
and it works, but in which way can I use avatar in on client part when I use
this.$page.props.user
in vue components properties to check which user is logged and show his info?
Thanks!
You can do this with the 'Shared data' feature via the HandleInertiaRequests middleware.
For example, to share user info you can do the following:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
class HandleInertiaRequests extends Middleware
{
public function share(Request $request)
{
return array_merge(parent::share($request), [
'user' => function () {
return Auth::user() ? [
'id' => Auth::user()->id,
'name' => Auth::user()->name,
'email' => Auth::user()->email,
// get path to avatar
'avatar' => Storage::url('avatar-of-the-user.jpg'),
] : null;
},
]);
}
}
Client side you can then access the avatar's URL with this.$page.props.user.avatar.
I am getting error on send Location Data To Database Using Laravel GeoIP::getLocation('2405:204:970a:d9b3:10a3:5280:9064:3f31'),
Error:
Object of class Torann\GeoIP\Location could not be converted to string
This Is My Auth LoginController. How to Insert GeoIP Loacation data into database. Please Help me
If i remove this code 'current_location' => GeoIP::getLocation('2405:204:970a:d9b3:10a3:5280:9064:3f31'), i am no longer getting this error, every data inserted into database but i add this code i am getting this error
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Carbon\Carbon;
use App\User;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Closure;
use GeoIP;
use Location;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
function authenticated(Request $request, $user)
{
// Chrome, IE, Safari, Firefox, ...
$agent = new Agent();
$browser = $agent->browser();
// Ubuntu, Windows, OS X, ...
$platform = $agent->platform();
$user->update([
'last_signin' => Carbon::now()->toDateTimeString(),
'ip_address' => $request->getClientIp(),
'browser_login' => $agent->browser(),
'browser_version' => $agent->version($browser),
'device_login' => $agent->platform(),
'device_version' => $agent->version($platform),
'current_location' => GeoIP::getLocation('2405:204:970a:d9b3:10a3:5280:9064:3f31'),
'language' => $agent->languages(),
'root' => $agent->robot(),
'https' => $request->server('HTTP_USER_AGENT'),
]);
}
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest',['except'=>['logout', 'userLogout', 'profile']]);
}
public function userLogout()
{
Auth::guard('web')->logout();
return redirect('/');
}
}
Auth Route :
//User Auth Route Function
Auth::routes();
This is happending because GeoIP::getLocation('2405:204:970a:d9b3:10a3:5280:9064:3f31') returns an instance of Torann\GeoIP\Location and you are trying to save it as a String.
Checking the documentation of this object it has this shape:
\Torann\GeoIP\Location {
#attributes:array [
'ip' => '232.223.11.11',
'iso_code' => 'US',
'country' => 'United States',
'city' => 'New Haven',
'state' => 'CT',
'state_name' => 'Connecticut',
'postal_code' => '06510',
'lat' => 41.28,
'lon' => -72.88,
'timezone' => 'America/New_York',
'continent' => 'NA',
'currency' => 'USD',
'default' => false,
]
}
You have to choose a way to represent this location as a String, a possible way can be to save the latitude and the longitude separately.
If you need to use only one column at the DB, you can check some GeoHashing implementations skthon/geogash.
You Might be trying to use getLocation method from wrong instance.
1.) Try as below way :
"use Torann\GeoIP\GeoIPFacade as GeoIP"
$location = GeoIP::getLocation();
2.) Or try as Geoip package documentation suggest here (http://lyften.com/projects/laravel-geoip/doc/methods.html)
from this instance \Torann\GeoIP\GeoIP and then use geoip()->getLocation('27.974.399.65');
This seems to be an issue in the current_location field and how it is typed in your database. From what I read, I guess your field is defined a string, and when trying to save your record to the database, it fails since the data you're trying to save is an Location object.
I would recommend changing your current_location column in your database to make it a json type.
Then you'd be able to insert your data as:
$user->update([
'last_signin' => Carbon::now()->toDateTimeString(),
'ip_address' => $request->getClientIp(),
'browser_login' => $agent->browser(),
'browser_version' => $agent->version($browser),
'device_login' => $agent->platform(),
'device_version' => $agent->version($platform),
'current_location' => json_encode(GeoIP::getLocation('2405:204:970a:d9b3:10a3:5280:9064:3f31')->toArray()),
'language' => $agent->languages(),
'root' => $agent->robot(),
'https' => $request->server('HTTP_USER_AGENT'),
]);
My view provides links like http://finance.dev/home/customer/6#tab_1_3 so that user a can directly navigate to a tab in the page using the link.
In my routes I have :
Route::get('/home/customer/{id}',[
'as' => 'home.customer',
'uses' => 'CustomerController#show'
]);
Route::get('/home/customer/{id}/{navigate}/{tab}',[
'as' => 'home.customer.navigate',
'uses' => 'CustomerController#navigate'
]);
I am passing the required variables to route using:
window.location.href = '/home/customer/'+id+'/'+navigate+'/'+tab;
And my controller logic is :
public function navigate($id, $navigate, $tab)
{
$user = customer::find($id);
if($navigate == 'previous')
{
// get previous user id
$go = customer::where('id', '<', $user->id)->max('id');
}
elseif ($navigate == 'next') {
// get next user id
$go = customer::where('id', '>', $user->id)->min('id');
}
else{
return \Redirect::back();
}
return \Redirect::route('home.customer', array('id' => $go));
}
The above code successfully returns a URL like http://finance.dev/home/customer/6
Now I am trying to figure out how to define \Redirect::route and \Redirect::back() to return a URL like http://finance.dev/home/customer/6#tab_1_3
How can I go about this?
$url = URL::route('home.customer', ['id' => $go])."#tab_1_6";
return \Redirect::to($url);
Reference Link
Which classes to use for caching certain token or url? After login, I want the user to redirect two urls back in Laravel 4.2? I have tried already with URlGenerator and Request class in my User authentification function so I could catch my previous url which is GET request for login, while the desired url is before this request.
My login function:
namespace \Users\Repositories;
use View , Input , Redirect , Config;
use Illuminate\Routing\UrlGenerator;
use Users\Repositories\Contracts\AuthRepositoryInterface;
use Illuminate\Support\MessageBag;
use Illuminate\Http\Request;
class AuthRepository implements AuthRepositoryInterface {
private $messageBag;
private $errors;
private $urlGenerator;
private $request;
public function __construct(MessageBag $messageBag, UrlGenerator $urlGenerator, Request $request) {
$this->messageBag = $messageBag;
$this->urlGenerator = $urlGenerator;
$this->request = $request;
}
public function postLogin() {
$remember_me = (Input::get('remember_me') == 1 ? true : false);
try
{
// Login credentials
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
);
// Authenticate the user
$user = \Sentry::authenticate($credentials, $remember_me);
// giving example
//if(token or url)
//redirect to 'frontend.fee.registration'
//else
return Redirect::route('profile')->with('success' , trans('users::success.login_success'));
}
My routes:
Route::get( '/login' , array( 'as' => 'login' , 'uses' => 'HomeController#userLogin' ) );
Route::post('/login' , array( 'as' => 'postLogin' , 'uses' => '\Users\Controllers\AuthController#postLogin' ) );
Redirect destination:
Route::get('/fee/{id}/register/' , array( 'as' => 'frontend.fee.registration' , 'uses' => 'FeeController#feeRegistration' ) );
There is no built in solution, but you can use session to save current URLs and then use them to go back 2-3-4 etc pages back.
Look at the answer and the code here: How to return back twice in Laravel?
I have made the login/tregistration form. Registration works well but login redirect doesn't work. I have the following function in my controller:
public function doLogin() {
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($credentials)) {
return Redirect::to('/');
} else {
dd('error');
}
}
and the routes.php
Route::resource('car', 'CarController');
Route::get('users', 'UserController#index');
Route::post('users/register', array('uses' => 'UserController#store'));
Route::post('users/signin', array('uses' => 'UserController#doLogin'));
Route::get('users/logout', array('uses' => 'UserController#doLogout'));
Route::get('/', 'CarController#index');
CarController
public function index() {
$cars = DB::select('select * from cars');
$result = DB::select('select c.*, i.sgs, i.tpl, i.kasko, i.inter_permis from cars as c left join insur_docs as i on i.car_id = c.id');
$date = Carbon::now();
$limit_date = Carbon::now()->addMonths(1);
return View::make('pages.index', array(
'cars' => $cars,
'result' => $result,
'date' => $date,
'limit_date' => $limit_date,
));
}
The problem is that it doesn't redirects to index page just refresh the page. If not correct credentials it shows "error" else if correct credentials it just refresh page and doesn't redirects. I f I replace redirect with success message it shows it. I have the same code localy and login with redirect is ok, but in google app engine (my project online) doesn't redirect.
The example you have used wouldn't actually redirect the user for two reasons.
The use of Redirect::route() excepts the parameter passed to be the name of a route, eg one defined like so
Route::get('/', ['as' => 'home', 'uses' => 'YourController#yourMethod']);
To redirect here you would use Redirect::route('home').
You aren't actually returning the redirect. Any response for a route, whether it be within a controller method or a closure, must be returned using the return keyword.
So to correct your code, it'd be like this:
public function doLogin() {
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($credentials)) {
return Redirect::to('/');
} else {
dd('error');
}
}
I moved the credentials to an array as it looks tidier and it makes it easier to read when displaying on this site, so you don't have to do that, but it may make things easier for you.