External API auth should be a ServiceProvider or Controller in Laravel? - laravel

Im building an app using Laravel, that app will allow the customers to send and get contacts from/to Mautic (email marketing software) via API, but first the app need to get an autorization to use Mautic API and store the user credintals to database for future use.
This is an example for how i make an autorization to connect to that api
$settings = [
'userName' => '', // Create a new user
'password' => '', // Make it a secure password
];
// Initiate the auth object specifying to use BasicAuth
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings, 'BasicAuth');
and then i can get the contact by id using this
$api = new MauticApi(); //This class is from the API package
$contactApi = $api->newApi('contacts', $auth, $apiUrl);
$response = $contactApi->get($id);
So my question is how can i organize that logic, should i just put all of it in a controller or it's better to create a service provider which should be responsible of the autorization and then return $auth handle that i can use then later for each customer, and if it's better to user the serviceprovider approch then i'm wondering how can i do that, should i just put the autorization logic in the boot method?

Related

Laravel socialite

I have used laravel auth and socialite package in my web app. I have followed https://www.youtube.com/watch?v=uavoKwhGBKI&t=932s link and it working fine.To be brief, If I register using socialite it fetches the name of the user and email but needs to be filled other details as DOB and password but if I submit without filling that it shows 500 error while if I register without socialite then my validation works fine.The registration page is same.
Socialite only gives you access to a select set of data returned from a successful connection.
# Retrieving User Details
https://laravel.com/docs/6.x/socialite#retrieving-user-details
$user = Socialite::driver('github')->user();
// OAuth Two Providers
$token = $user->token;
$refreshToken = $user->refreshToken; // not always provided
$expiresIn = $user->expiresIn;
// OAuth One Providers
$token = $user->token;
$tokenSecret = $user->tokenSecret;
// All Providers
$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();
# Modifying LoginController
https://scqq.blogspot.com/2017/11/laravel-55-socialite-login-with-twitter.html
This guide you followed does not actually register a user by social platform. It only pre-populates the default Laravel registration form with the fields name and email as shown below. This is where you can add another property from above, such as the user's avatar, if desired. You would also need to add the corresponding field to the registration form.
return view('auth.register', [
'name' => $userSocial->getName(),
'email' => $userSocial->getEmail(),
// ... 'avatar' => $userSocial->getAvatar(),
]);
Google is NEVER going to give you someone's password!
The whole point of Socialite is to allow Google (or the selected provider) to authenticate the user — not your application.
If you wish to actually register a user with Socialite (without any additional forms or setting a password), you will need to modify or extend RegisterController.php to be able to support this.

Acessing auth user attribute

I am in the guzzle controller making a request to an external api.
I wanna use an id from the user who is logged in.
I have been doing the request with a static id, but now i want it dynamically.
I tried like this:
$science = Auth::user()->science_id;
$client = new Client(['headers' => ['Accept' => 'application/json']]);
$request = $client->get(
'https://url_to_the_api/'.$science.'/degree',
[
'auth' => ['client', 'secret'],
]
);
$data = $request->getBody()->getContents();
return $data;
And i have the error
500(internal server error)
and this message:
"Trying to get property 'science_id' of non-object"
What am i missing?
Thanks for your time
If you are using it in web app then make sure you first check if user is already authenticated by using auth middleware or manually by using Auth::check() function.
Or
If you are trying to hit this by api that will not work here because session will not be maintained in that case. That's why JWT tokens were introduced to maintain the state of an application.
I've solved it like this:
$science = auth('api')->user()->science_id;
Thanks for the help!

Token Passport Users

I'm new to building APIs, and I'm using Laravel and some packages, like Passport.
In this project I'm creating an API to communicate with a mobile app and make some tasks, like creating users and adding some information related to the users.
I'm already getting the idea of how it works with tokens, and I already have almost everything done. My only question is, for example, before I create a register user to receive the token I have other information being presented in the mobile app, like news, and some listing information that is not needed to login or register.
In my API I already have these routes ready, but I cant access this information because I need a token.
How do iI handle this situation? When I need to access information, where I cant present it?
Use your controllers to retrieve the data you need from your database and then return a response with the data and create a token for the user:
...
$status = 200;
$response = [
'data' => Your data (user info, listings, news...),
'token' => Auth::user()->createToken("YourTokenName")->accessToken,
];
return response()->json($response, $status);
Then you could store that token in localStorage:
axios.post('your-api-route')
.then((response) => {
localStorage.setItem(`${"YourTokenName"}.jwt`, response.token);
...
})
And finally attach that token to the api routes that require authentication:
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem(`${YourTokenName}.jwt`);

Authentication check for non auth url in laravel passport api

i am using passport authentication for my Laravel 5.4 API.here i have a api for company details and it is a non auth api.i need to check logined user liked this company using auth in this url ...how i can do this.
This is my route
Route::get('/company/{company}','Api\V1\CompanyController#show');
Route::group(['middleware' => 'auth:api','prefix'=>'v1'], function(){
//auth urls
}
and this is my controller
class CompanyController extends Controller
{
public function show(Company $company,Request $request)
{
$data = array();
$flag = 0;
$data['status'] = 1;
$data['message'] = 'success';
$data['baseUrl'] = url('/');
$data['is_login'] = Auth::check();
Here is_login always return false,if i added autherization token in headers of api.
What is your default guard set as?
Auth::check() is Auth::guard(null)->check() which uses the current default guard.
If you want to check for an api you probably want to use the api guard just like your auth middleware is using when you use auth:api.
Auth::guard('api')->check() tells it to explicitly use the api guard instead of what the default is, which could be anything since we don't know what you have set.
When the auth middleware is ran it actually will set the default guard for you depending upon what guards are passed to it and which one it can resolve a user from. Which is why you can just call Auth::user() and get the correct user from the correct guard, because the middleware sets the current to the one that resolved the user. (When calling routes that have this middleware)

list blogs list of blogger in Google PHP SDK

I am using Google API SDK in CakePHP application.
I have to list the blogs owned by the user after authenticating the application.
The user will select from the list of blogs and I will record the blog ID to make further requests.
According to the documentation, we need to make GET request to
GET https://www.googleapis.com/blogger/v3/users/self/blogs?key=YOUR-API-KEY
But I have my API Key and user's access token.
How can I list the blogs using the access token?
I tried using the SDK Services
$client = new \Google_Client();
$client->setApplicationName(GOOGLE_APP_NAME);
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setAccessToken($access_token);
$client->setAccessType("offline"); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope('https://www.googleapis.com/auth/userinfo.email');
$client->addScope('https://www.googleapis.com/auth/blogger');
$callback_url = Router::url(['prefix' => 'dashboard', 'controller' => 'SharingLogin', 'action' => 'bloggerCallback'], true);
$client->setRedirectUri($callback_url);
$service = new \Google_Service_Blogger($client);
$listblog = $service->blogs;
debug($listblog);
But this lists nothing and empty array object.

Resources