What's wrong with this Oauth process for LinkedIn + email? - authentication

I'm using the oneAuth bundle in laravel, based on NinjAuth from Fuel by Phil Sturgeon, I believe, and trying to get the user's email address.
I've added the proper scope to my request, and the LinkedIn auth screen successfully asks for the users permission for basic profile AND email address.. so far, so good..
A possible issue is: what is the proper name of the email field?
I've found references to email-address, emailAddress, 'emailaddress`...
The docs indicate email-address, but its not working for me :)
I'm using the URL: https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,member-url-resources,picture-url,location,public-profile-url,email-address)?format=json
This is the problematic snippet from /bundles/oneauth/libraries/oauth/provider/linkedin.php
// Create a response from the request
return array(
'uid' => array_get($user, 'id'),
// 'email' => array_get($user, 'email-address)',
// 'email' => array_get($user, 'emailAddress)',
'name' => array_get($user, 'firstName').' '.array_get($user, 'lastName'),
'image' => array_get($user, 'pictureUrl'),
'nickname' => $nickname,
'description' => array_get($user, 'headline'),
'location' => array_get($user, 'location.name'),
'urls' => array(
'linkedin' => $linked_url,
),
);
If I uncomment the email field, the request fails somehow (URL still shows mysite.com/connect/callback but the favicon shows linkedin and i get ablank page in chrome: "Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.")
If the email line in the code above IS commented out, I successfully receive all the other details and a new record is added to my users table and the table oneauth_clients, but email is naturally blank..
I must be missing something simple!
Update
The request URL works with email-address, but returns a json object containing emailAddress!!
The script still dies if the return array code above includes emailAddress...
Here is someone's success story:
"I made these two changes to the library and the demo.php respectively:
const _URL_REQUEST = 'https://api.linkedin.com/uas/oauth/requestToken?scope=r_basicprofile+r_emailaddress';
$response = $OBJ_linkedin->profile('~:(id,first-name,last-name,picture-url,email-address)');

The issue was that the Request Token Call is:
https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,member-url-resources,picture-url,location,public-profile-url,email-address)?format=json
but the json response is:
array(8) {
["emailAddress"]=>
string(18) "email#email.com"
["firstName"]=>
string(3) "Tim"
...
Note that in the first case email is named email-address, in the second emailAddress.
The secondary problem was a shortcoming of my code - now working perfectly!

Related

Send email with TDD Laravel 5.6

I am doing the registration user
public function register(RegistrationUser $request)
{
$user = $this->usersRepo->create($request->all());
$user->activation_token = str_random(48);
$user->save();
Mail::to($user->email)->queue(new ActivationAccount($user->first_name, $user->last_name, $user->email, $request->input('password'), $url));
return redirect()->route('successful.registration')
}
My registration test is:
public function it_creates_a_new_user()
{
$this->withExceptionHandling();
$response = $this->get(route('register'))
->assertStatus(200);
$this->post('register', [
'first_name' => 'Juan',
'last_name' => 'Lopez',
'email' => 'jlopez#gmail.com',
'password' => 'secret',
'activation_tone' => str_random(48)
])->assertRedirect(route('successful.registration'));
$this->assertDatabaseHas('users', [
'email' => 'jlopez#gmail.com',
]);
}
I have two questions:
1) How can I write a test to send the registration email and verify that it sends and arrives well?
2) When the user clicks on his email he calls a method where the activation token is passed to activate his account
In my opinion you should use mail fake ,which will prevent mail from being sent. You may then assert that mailables were sent to users and even inspect the data they received.
please read laravel docs: https://laravel.com/docs/5.6/mocking#mail-fake
There must be a route which is handling activation token and functionality, so try to get the token and call route with specific token
Note: As a developer we need to make sure that our code works which our tests are confirming, Sending and delivering email should be not be covered as they considered to work as expected(by any email service provider).

Passport - "Unauthenticated." - Laravel 5.3

I hope someone could explain why I'm unauthenticated when already has performed a successfull Oauth 2 authentication process.
I've set up the Passport package like in Laravel's documentation and I successfully get authenticated, receives a token value and so on. But, when I try to do a get request on, let say, /api/user, I get a Unauthenticated error as a response. I use the token value as a header with key name Authorization, just as described in the docs.
Route::get('/user', function (Request $request) {
return $request->user();
})->middleware("auth:api");
This function is suppose to give back my self as the authenticated user, but I'm only getting Unauthenticated. Likewise, if I just return the first user, I'm again getting Unauthenticated.
Route::get('/test', function(Request $request) {
return App\User::whereId(1)->first();
})->middleware("auth:api");
In a tutorial from Laracast, guiding through the setup of Passport, the guider doesn't have the ->middleware("auth:api") in his routes. But if its not there, well then there's no need for authentication at all!
Please, any suggestions or answers are more then welcome!
You have to set an expiration date for the tokens you are generating,
set the boot method in your AuthServiceProvider to something like the code below and try generating a new token. Passports default expiration returns a negative number
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(15));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
Check your user model and the database table, if you have modified the primary id field name to say something other than "id" or even "user_id" you MIGHT run into issues. I debugged an issue regarding modifying the primary id field in my user model and database table to say "acct_id" instead of keeping it as just "id" and the result was "Unauthenticated" When I tried to get the user object via GET /user through the auth:api middleware. Keep in mind I had tried every other fix under the sun until I decided to debug it myself.
ALSO Be sure to UPDATE your passport. As it has had some changes made to it in recent weeks.
I'll link my reference below, it's VERY detailed and well defined as to what I did and how I got to the solution.
Enjoy!
https://github.com/laravel/passport/issues/151
I had this error because of that I deleted passport mysql tables(php artisan migrate:fresh), php artisan passport:install helps me. Remember that after removing tables, you need to re-install passport!
I had exactly the same error because I forgot to put http before the project name.
use Illuminate\Http\Request;
Route::get('/', function () {
$query = http_build_query([
'client_id' => 3,
'redirect_uri' => 'http://consumer.dev/callback',
'response_type' => 'code',
'scope' => '',
]);
// The redirect URL should start with http://
return redirect('passport.dev/oauth/authorize?'.$query);
});
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://passport.dev/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 3,
'client_secret' => 'M8y4u77AFmHyYp4clJrYTWdkbua1ftPEUbciW8aq',
'redirect_uri' => 'http://consumer.dev/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});

Laravel 4, how to send different flash messages depending on users credentials and hidden input

I am trying to check the status of a users account when the user logs into the application with Laravel 4.1.
$attempt = Auth::attempt(array('email' => $input['email'], 'password' => $input['password'], 'active'
=> $input['active']), true);
if($attempt) return Redirect::route('photos.index');
return Redirect::back()->withInput()->with('message', 'Your email or password are incorrect.');
I am using a hidden input "active" to check whether a user account is still active or not. This works fine. However, if this check fails, the user gets to see the same flash message that is displayed when he enters wrong credentials. How could I send a second flash message that states to the user that his account is not active anymore even if he had entered correct credentials?
Any help would be much appreciated.
Thanks!
If the Auth::attempt() fails you can check with this if it succeeded without an active account.
$attempt = Auth::attempt(array('email' => $input['email'], 'password' => $input['password'], 'active'
=> $input['active']), true);
if($attempt) return Redirect::route('photos.index');
// Check if credentials are correct but the account is not active
if (Auth::validate(array('email' => $input['email'], 'password' => $input['password'])))
{
// Valid but not active
return Redirect::back()->withInput()->with('message', 'Account not active.');
}
return Redirect::back()->withInput()->with('message', 'Your email or password are incorrect.');

Drupal 7 - how to allow an application to access a certain drupal url (from menu hook), either with super basic url-based auth or anonymously

I'm pretty new to drupal, so bear with me if I'm not using correct terms.
I'm trying to give a stupidly basic application access to a drupal url - this application cannot do any complicated authentication.
Otherwise, this drupal system needs authentication and all other menu hooks use 'access arguments' => array('access content')
Even before looking a solution for easy authentication method with drupal like http://user:password#server.com/awesome/member/12345, I've tried just giving anonymous access with the following code block in a drupal .module file
function awesome_module_menu() {
$items['awesome/member/%'] = array(
'title' => 'Awesome member',
'type' => MENU_NORMAL_ITEM,
'page callback' => 'aw_memberdata_fetch',
'delivery callback' => 'aw_memberdata_deliver',
'access arguments' => TRUE // this supposedly should allow anonymous access - from the web
);
return $items;
}
I have these two functions, one to fetch the data, one to show it:
function aw_memberdata_fetch(memberId)
{
//fetch array of objects from DB
...
return $items;
}
function aw_memberdata_deliver($items)
{
switch(arg(3)) //format, comes after items
{
case 'json':
drupal_json_output($items);
break;
default:
$output = makeHtml($items); //makes HTML
drupal_deliver_html_page($output);
}
}
With an authenticated browser, this works as intented. From a browser with no auth cookie I'm allowed to see the HTML, but the results are not there, it's like the page callback function doesn't run for anon users, but delivery callback does.
How do I make this work for anon users?
You are using access arguments with the default user_access function for permission verification. This will basically call user_access(true) which will return
true for authenticated user (you are probably testing with the administrator account (uid = 1)) which bypasses the verification check. Administrator has full privileges.
false for anonymous users because the string value of the first argument passed to the user_access true doesn't exist as a permission setting.
You should use either use
a custom YOURMODULE_access hook which does the permission verification
declare custom permissions for your module (YOURMODULE_permission hook)
don't use permission verification by using 'access callback' => true which gives access to anonymous and authenticated users
function awesome_module_menu() {
$items['awesome/member/%'] = array(
'title' => 'Awesome member',
'type' => MENU_NORMAL_ITEM,
'page callback' => 'aw_memberdata_fetch',
'delivery callback' => 'aw_memberdata_deliver',
'access callback' => true,
);
return $items;
}

AWeberApi - could not get Subscribers email

I run this code
print_r($list->subscribers);
You can see at the result I pasted below that there is no subscriber name and email... I tried all the sample codes i could find in the web and all of them have the same result.
Now my question is, how to get the emails of all the subscribers aside from the code I used above?
[last_followup_sent_link] => https://api.aweber.com/1.0/accounts/6023076/lists/20746327/campaigns/f105556951
[city] =>
[http_etag] => "d6a652460dae642a0732ecf75003de4t05be96f66a1-7c14178a7fa0b2a2b7fb74be93ff058ac477ea43"
[ad_tracking] => my_web_form
[dma_code] =>
[last_followup_message_number_sent] => 1
[last_followup_sent_at] => 2011-11-17 04:52:19-05:00
[latitude] =>
[is_verified] => 1
[status] => subscribed
[area_code] =>
[unsubscribed_at] =>
[self_link] =>
[unsubscribe_method] =>
[resource_type_link] => https://api.aweber.com/1.0/#subscriber
[subscription_method] => signup form
[subscribed_at] => 2011-11-17 04:51:41-05:00
[region] =>
[longitude] =>
[verified_at] => 2011-11-17 04:52:19-05:00
[country] =>
The problem is that you did not grant access to subscriber info in your app. Choose Edit -> Permission Settings, put a check mark in the Request Subscriber Info box then choose save permission settings and then choose save. If done correctly, you should be back at the apps page and it will now be displaying the additional permissions.
You will have to reset the key/secret and then get a new Oauth token and secret as well. When that takes place and it asks for permission, you should see a box above the login credentials detailing the request for personal subscriber details. If you don't see it, something is wrong.
Once completed you should see all subscriber data including email address.