How set uploaded avatar in this.$page.props.user with inertiajs? - laravel

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.

Related

Check access for website addresses in Laravel

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

How can I get api/register with Passport in laravel working?

Following a tutorial: https://www.twilio.com/blog/build-secure-api-php-laravel-passport
I manAged to get Laravel/Passport installed formy Laravel Api and Vue application.
I managed to create attoken with:
localhost:8000/oauth/token
get the login working in Postman:
localhost:8000/api/login?email=jennie05#example.com&password=password
Now when I try to register a user I get returned to the home-page.
I do get some "undefined method" errors from VS Code, but they show up in the login method,
and not in the failinf register method:
Here is the controller:
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
class AuthController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:55',
'email' => 'email|required|unique:users',
'password' => 'required|confirmed'
]);
$validatedData['password'] = bcrypt($request->password);
$user = User::create($validatedData);
$accessToken = $user->createToken('authToken')->accessToken;
return response([ 'user' => $user, 'access_token' => $accessToken]);
}
public function login(Request $request)
{
$loginData = $request->validate([
'email' => 'email|required',
'password' => 'required'
]);
if (!auth()->attempt($loginData)) {
return response(['message' => 'Invalid Credentials']);
}
$accessToken = auth()->user()->createToken('authToken')->accessToken;
return response(['user' => auth()->user(), 'access_token' => $accessToken]);
}
}
In these are the routes in api.php:
Route::post( 'register', 'App\Http\Controllers\API\AuthController#register');
Route::post( 'login', 'App\Http\Controllers\API\AuthController#login');
// Route::prefix('v2')->group(function(){ // prefix voor versie 2
Route::apiResource('/cards', 'App\Http\Controllers\CardController');
Route::apiResource('/games', 'App\Http\Controllers\GameController');
//Route::get('games', 'App\Http\Controllers\GameController#index')->middleware('auth:api');
//Route::post('games', 'App\Http\Controllers\GameController#store')->middleware('auth:api');
//Route::get('games/{id}', 'App\Http\Controllers\GameController#show')->middleware('auth:api');
//Route::put('games/{id}', 'App\Http\Controllers\GameController#update')->middleware('auth:api');
//Route::delete('games/{id}', 'App\Http\Controllers\GameController#destroy')->middleware('auth:api');
Route::get('/gameByPin/{pin}', 'App\Http\Controllers\GameController#searchPin');
Route::apiResource('/speler', 'App\Http\Controllers\SpelerController');
//});
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
is there anyone who can help troubleshooting this?
Postman does not give me errors, just the redirect to homepage..
Wow,
Thanks Patrick, your the best.
Just checked all the steps in the documentation.
reran the installation command I ran when setting up everything. ( Apperently need to do this twice ?!):
php artisan passport:install
It returned:
Encryption keys already exist. Use the --force option to overwrite them.
Personal access client created successfully.
Client ID: 5
Client secret: ikJEfthxxxxxxxxxxxxxxxxxxxxxxxxxxxBjJ36
Password grant client created successfully.
Client ID: 6
Client secret: H42lpMxxxxxxxxxxxxxxxxxxxxxxxxxxxQGZgH
Now the post request results in a token!
The error VS Code shows d for "use HasApiToken" is:
Undefined type 'Laravel\Passport\HasApiTokens'.intelephense(1009)

Laravel Error: Object of class Torann\GeoIP\Location could not be converted to string

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'),
]);

Laravel Email Verification in custom registeration controller not working

I have made a registration form in my frontend ( Not a laravel default registration form ) . I have used Laravel Email Verification
I have implements MustVerifyEmail in User Model
But In that custom registraion form in my frontend when i hit submit it redirects the page to /admin/home but email is not been sending when i register but If I click on resend email again it sends the email . I want to fix that
Does anyone know how ?
Do I have to implements MustVerifyEmail to that controller too or what ?
IGNORE THAT CITY AND ROOM IN THE FUNCTION !!!!!
class QuickRegisterController extends Controller
{
public function quickList(Request $request)
{
$this->validate($request ,[
'features' => 'required',
'rommies' => 'required',
'price' => 'required',
'avaiability' => 'required',
'utility' => 'required',
'owner_working_email' => 'required',
'address' => 'required',
'exact_address' => 'required',
'owner_of_the_room' => 'required',
]);
$user = User::firstOrCreate([
'name' => $request->owner_of_the_room,
'email' => $request->owner_working_email,
'password' => bcrypt($request->password),
'role_id' => config('quickadmin.default_role_id'),
]);
\Auth::loginUsingId($user->id);
if (\Auth::check()) {
$city = TotalCity::firstOrCreate([
'name' => $request->city,
'created_by_id' => \Auth::user()->id,
]);
if ($city) {
$room = new MyRoom;
$room->location_id = $city->id;
$room->features = $request->features;
$room->rommies = $request->rommies;
$room->price = $request->price;
$room->utility = $request->utility;
$room->avaiability = $request->avaiability;
$room->owner_woring_email = $request->owner_working_email;
$room->address = $request->address;
$room->exact_address = $request->exact_address;
$room->owner_of_the_room = $request->owner_of_the_room;
$room->save();
}
return redirect('/admin/home');
}
else {
return redirect()->back()->with('Form Submission Failed . Try Again Later');
}
}
}
If you look into the RegisterController that Laravel provides with its auth scaffolding, not sure if you are using that or not, it implements the RegistersUsers trait. That trait implements an event that is triggered upon registration. You can use the RegistersUsers trait in your class or create your own custom event.
I'll show you how to use the trait.
At the top of your file:
use Illuminate\Foundation\Auth\RegistersUsers;
Right inside your class:
use RegistersUsers;
For Example:
use Illuminate\Foundation\Auth\RegistersUsers;
class QuickRegisterController extends Controller
{
use RegistersUsers;
// ....
}
You'll need to set up the route as well.
// The register method is coming from the trait
Route::post('/register', 'QuickRegisterController#register');
Also,
You'll want to update your method name to create, the trait calls a create method from the implementor, which is where the user gets created and then the event is triggered, and in that create a method just return the new user, instead of redirecting back.
This might not be all you need to do to get this working, but it will get you started. If you are interested in creating your own event:
https://laravel.com/docs/5.8/events
Or, as #Bipin Regmi pointed out you can just use the event that is being used in the trait
event(new \Illuminate\Auth\Events\Registered($user = $this->create($request->all())));

How can I return two times back in Laravel 4.2?

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?

Resources