How to Get facebook friendlist in laravel - laravel-5

how to get facebook friendlist in laravel when user login by facebook login. Already I get the name, email. But I want frienlist also. Here is my existing code.
public function redirectToProvider()
{
return Socialite::driver('facebook')->redirect();
}
public function handleProviderCallback()
{
$socialize_user = Socialite::driver('facebook')->user();
$facebook_user_id = $socialize_user->getId(); // unique facebook user id
$facebook_name = $socialize_user->getName();
$facebook_email = $socialize_user->getEmail();
$facebook_image = $socialize_user->getAvatar();
$user = Register::where('facebook_id', $facebook_user_id)->first();
if ($user) {
Session::put('id',$user->id);
Session::put('name',$user->name);
return redirect::to('welcome');
}
// register (if no user)
if (!$user) {
$user = new Register;
$user->facebook_id = $facebook_user_id;
$user->name = $facebook_name;
$user->email = $facebook_email;
$user->image = $facebook_image;
$user->save();
return redirect('welcome');
}
}

Before anything you will need the user permission, even if they have already signed in
Short version:
You can't with only socialite or without adding few classes.
Long version:
You need to extend FacebookProvider and implement the user interface.
This is the user interface of the user so you can add the friend list method.
And this is the FacebookProvider which includes the required authentication for accessing the facebook state and token, you can read on the loginFlow process on facebook.
To get access to the user friend list, you need to get the user permission, hence you need to initiate the full process again and add the user permission or add it at the start of the process.
Quick version:
If it is only for the friend list, better to use JavaScript and add friend list permission, and then use the response that you get, facebook graph api JS.
Laravel version:
check this package from sammyK it gives you great control on FacebookPHPSDK if you want more functions.

Related

How to make login as other user in API using laravel passport?

I am using laravel passport for API authentication. and I want to log in as different users with different roles from superadmin. So how can I achieve this? Please give your suggestions.
public function masqueradeNotary($profileId)
{
$userId = decodeC($profileId);
$notaryUser = $this->adminService->getUser($userId);
if($userId){
//logout from current login user
$user = auth()->user()->token();
$user->revoke();
//login as notary user
$userRoles = $notaryUser->roles()->get();
// $scopes = [];
// if ($userRoles) {
// $scopes = Arr::pluck($userRoles,'code');
// }
if(Auth::login($notaryUser)){
\Log::info("auth user");
\Log::info(auth()->user());
// $token = $user->createToken($user->email . '-' . now(), $scopes);
}
}
}
Welcome to stackoverflow.
Well, you should look at spatie's package, it might make your life easier.
You can apply roles on the registration if you create two different registration functions. In the front-end, you have to somehow make the user decide and pass that value (a checkbox would be ideal).
I got the solution. there is no need to check auth login just log out the current user and revoke the access token and create a token for the user directly.
$token = $user->createToken($user->email . '-' . now(), $scopes);

Pin Verification In Laravel

I'm a beginner. I have a pin field in my user database. I want users to verify the pin before they can access there profile. how can I do this any logic?
in livewire components
public function verify (){
$user = User::select('id')->where('pin',$pin)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/user');
}
in my livewire blade I will call the verify method in the form will this work
laravel login using pincode :check the following code example may be you get the hint how to implement that, in this example code pin authentication is done using JWT and then user is allowed to access to those specific routes.
$user = User::find($uid);
try {
if (!$token = JWTAuth::fromUser($user)) {
return $this->onUnauthorized();
}
} catch (JWTException $e) {
return $this->onJwtGenerationError();
}
For somereason if you dont want to use the above JWT method you can use this one. i'm sharing the code for an example from by program which may help you
$user = User::select('id')->where('pin',$pin)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/user');

how to check if user is authenticated with passport (get user from token using laravel-passport)

I am using Passport to log in users to a Laravel API endpoint, users get authenticated using their social accounts (google, facebook) using laravel-socialite package.
the workflow of logging users in and out works perfectly (generating tokens...Etc). The problem is I have a controller that should return data based on whether there is a user logged in or not.
I do intercept the Bearer token from the HTTP request but I couldn't get the user using the token (I would use DB facade to select the user based on the token but I am actually looking whether there is a more clean way already implemented in Passport)
I also don't want to use auth:api middleware as the controller should work and return data even if no user is logged in.
this is the api route:
Route::get("/articles/{tag?}", "ArticleController#get_tagged");
this is the logic I want the controller to have
public function get_tagged($tag = "", Request $request)
{
if ($request->header("Authorization"))
// return data related to the user
else
// return general data
}
Assuming that you set your api guard to passport, you can simply call if (Auth::guard('api')->check()) to check for an authenticated user:
public function get_tagged($tag = "", Request $request)
{
if (Auth::guard('api')->check()) {
// Here you have access to $request->user() method that
// contains the model of the currently authenticated user.
//
// Note that this method should only work if you call it
// after an Auth::check(), because the user is set in the
// request object by the auth component after a successful
// authentication check/retrival
return response()->json($request->user());
}
// alternative method
if (($user = Auth::user()) !== null) {
// Here you have your authenticated user model
return response()->json($user);
}
// return general data
return response('Unauthenticated user');
}
This would trigger the Laravel authentication checks in the same way as auth:api guard, but won't redirect the user away. In fact, the redirection is done by the Authenticate middleware (stored in vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php) upon the failure of the authentication checking.
Beware that if you don't specify the guard to use, Laravel will use the default guard setting in the config/auth.php file (usually set to web on a fresh Laravel installation).
If you prefer to stick with the Auth facade/class you can as well use Auth::guard('api')->user() instead or the request object.
thanks to #mdexp answer
In my case I can resolve my problem with using
if (Auth::guard('api')->check()) {
$user = Auth::guard('api')->user();
}
In my controller.

having anonymous user on laravel

I'm using Laravel 5.8. And I have created a custom Guard that is using jwt. That I use as a middleware for authenticating users.
I have some routes that need to have different responses based on being an authenticated user or an unauthenticated user. what do you suggest me to do? what is the best practices to implement this?
I can define a custom guard which its check function always returns true.and returning an integer like -1 for unauthenticated user while the user is not authenticated.but it does not sound a clean way of implementing this.
Depending on how you want to set this up, you can just use the Auth facade helpers in your controller method to see whether a user is authenticated or not:
// SomeController.php
public function index(Request $request)
{
if(Auth::guest()) {
return response()->json('i am a guest');
} else {
return response()->json('im not a guest');
}
}
or use any of the related methods:
// Inverse of `Auth::guest()`
$isLoggedIn = Auth::check();
$loggedInUser = Auth::user();
https://laravel.com/api/5.8/Illuminate/Auth/GuardHelpers.html

How can I add ask username and password feature to only one of my laravel routes?

I have created a few forms in laravel. I want to restrict access to one of them only to a specific user.
I want to create a user and password myself.
This is my routes excerpt. This is the route I want to protect from access
Route::get('/tabledata_id_title', 'KedivimController#appearanceiddata');
This is my controller excerpt:
public function appearanceiddata()
{
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
This is a short fix for your problem.
public function appearanceiddata()
{
if (!Auth::guard('web')->check()) //check if someone is logged in
{
//redirect to login page.
}
else {
/*Check if the logged in user is your desired user.
Maybe try matching the logged in id with your desired id.
If you find that a user is logged in but they are not your desired user
then you may redirect them in some other place or show them a message. */
}
//$magic = DB::table('prog_title')->select('pr_id', 'pr_title')->get();
$magic = DB::table('prog_title')->select('pr_id', 'pr_title')-> where('pr_index', '=', 1)->get();
return view ('takealook', ['magical' => $magic]);
}
However, this practice is ok if you have one or two restricted field. But if you have more than that then you should read about middleware.

Resources