laravel login with google account - laravel

I am making an application and I want users to login with their google account. I have user oauth-4-laravel and I have this:
UserController.php
// get data from input
$code = Input::get('code');
// get google service
$googleService = Artdarek\OAuth\Facade\OAuth::consumer("Google");
if (!empty($code)) {
// This was a callback request from google, get the token
$token = $googleService->requestAccessToken($code);
// Send a request with it
$result = json_decode($googleService->request('https://www.googleapis.com/oauth2/v1/userinfo'), true);
$user = DB::select('select id from users where email = ?', array($result['email']));
if (empty($user)) {
$data = new User;
$data->Username = $result['name'];
$data->email = $result['email'];
$data->first_name = $result['given_name'];
$data->last_name = $result['family_name'];
$data->save();
}
if (Auth::attempt(array('email' => $result['email']))) {
return Redirect::to('/');
} else {
echo 'error';
}
}
// if not ask for permission first
else {
// get googleService authorization
$url = $googleService->getAuthorizationUri();
// return to facebook login url
return Redirect::to((string) $url);
}
}
After this i get successfully user info and can save user name, in my database. The problem is that after this I want to redirect user to home page and can't do this because with normal login i chec authentication:
if (Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')))) {
return Response::json(["redirect_to" => "/"]);
and with google login i get onlu username , user id and email. How to login directly the user after google login?

If you need to log an existing user instance into your application, you may simply call the login method with the instance:
$user = User::find(1);
Auth::login($user);
This is equivalent to logging in a user via credentials using the attempt method.
For further info see: http://laravel.com/docs/security#manually

Related

Login with only email in Lumen (JWT Auth)

I want to make the password optional while login into the system. If the user enters the password the login works fine and return the jwt token, when I entered to try to login only with email it gives the following error:-
Undefined index: password (500 Internal Server Error)
The following is the code of my login method
public function authenticateUser($request)
{
$input = $request->only('email','password');
if (!$authorized = Auth::attempt($input, true)) {
return $this->failure('Credentials doesnot match our records!', 401);
} else {
$token = $this->respondWithToken($authorized);
return $this->success('Login Successfully !', $token, 200);
}
}
protected function respondWithToken($token)
{
return [
'token' => $token,
'token_type' => 'Bearer',
'expires_in' => Auth::factory()->getTTL() * 60,
'user' => Auth::user()
];
}
so basically, what I want is when a user enters an email it will login and should return the token, and if the user login with email and password then it should also work and return the token.
You can create a custom Authentication User Provider that will work around this potentially missing 'password' field. Though, I would probably not here. You can check the input yourself to see if there is a password or not. If there is pass it through attempt like normal. If it is not there find the user using the configured User Provider and login to the guard (what attempt is doing).
Perhaps something like this:
public function authenticateUser($request)
{
if ($request->has('password')) {
$token = Auth::attempt($request->only(['email', 'password']));
} else {
$token = ($user = Auth::getProvider()->retrieveByCredentials($request->only(['email'])))
? Auth::login($user)
: false;
}
return $token
? $this->success('Login Successfully !', $this->respondWithToken($token), 200)
: $this->failure('Credentials do not match our records!', 401);
}
The error that you're getting means that there is no password key in the input array that you're sending via request. This happens on this line:
$input = $request->only('email','password');
In order to bypass that, you would need go get all inputs, or check if those inputs exist and then read from them:
//Get all inputs
$input = $request->input();
//Or get email first, and then check for password
$input['email'] = $request->email;
$input['password'] = $request->filled('password') ? $request->password : null;
Note: Since I can't see your actual login functions, this might not work with only email, since password might be required parameter. If that's the case, you will have to alter those functions.

Struggling to store token for AdSense API

I've successfully managed to connect to the AdSense API and run a report. However, it requires a log in each time I run it, so it won't run as a cron job.
I've found a few other questions related to this. Some advise a service account, while others point out that a service account does not work with AdSense. The proposed solution is to store a token on my server, but I've been struggling to get that to work. Here is my code so far (which works, but requires manual log in):
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApplicationName('My Application name');
$client->setClientId(' MY ID ');
$client->setClientSecret(' MY SECRET ');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(' MY KEY '); // API key
$accountId = " MY ACCOUNT " ;
$adClientId = " MY CLIENT " ;
// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
$startDate = '2015-11-01';
$endDate = 'today';
$optParams = array(
'metric' => array(
'EARNINGS'),
'dimension' => array('DATE'),
'sort' => '+DATE',
'filter' => array(
'CUSTOM_CHANNEL_NAME==Mega Seating Plan'
)
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $startDate,
$endDate, $optParams);
if (isset($report) && isset($report['rows'])) {
// Get results.
foreach($report['rows'] as $row) {
$date = $row[0] ;
$earnings[$date] = $row[1] ;
}
} else {
print "No rows returned.\n";
}
Can anybody give me any pointers about how I can incorporate token storage into the above code, please?
Thank you to #jkns.co for the previous answer here which helped me to get it working.
Here's my final code:
$scriptUri = "I HAD TO PUT MY ABSOLUTE URL HERE, OTHERWISE THE CRON JOB WOULD LOOK IN THE WRONG PLACE" ;
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt ("force"); // This line had to be added to force the approval prompt and request a new token
$client->setApplicationName('My Application name');
$client->setClientId('BLAH');
$client->setClientSecret('BLAH');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('BLAH'); // API key
$accountId = "BLAH" ;
$adClientId = "BLAH" ;
// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
// If it successfully authenticates, I request the refresh token
$refreshToken = $client->getRefreshToken();
storeRefreshToken($refreshToken) ; // This function stores the token in MySQL
}
else { // Otherwise it loads the refresh token from MySQL
$refreshToken = getRefreshToken() ;
$client->refreshToken($refreshToken);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}

Laravel Stormpath not able to access User Object

I am using Laravel and Stormpath for User Management. I am able to register and login user successfully using AJAX.
After successful login only the url is returned to AJAX, but after login when I go to User specific pages I am not able to fetch User Data.
Registration and Login happens in RegisterController
User Pages are rendered using UserController
I've tried to get User data using
$user = app('stormpath.user');
in UserController, but when I do dd($user) null is returned.
How to persist or get User Data after successful login or sign-up in other Controllers?
Any help appreciated! Thanks in advance!
For the Stormpath Laravel integration, when you run AJAX calls, we do not set any cookies. We provide you with the JWT in the header response that you will need to look at and then store them youself. The JWT will then need to be attached to all other requests as a Bearer token which will allow you to use the `$user = app('stormpath.user') method to get the user information out of the JWT.
I finally got everything working. Thank you #bretterer
// Stormpath user account creation
\Stormpath\Client::$apiKeyProperties = "apiKey.id="
.env('STORMPATH_CLIENT_APIKEY_ID').
"\napiKey.secret=".env('STORMPATH_CLIENT_APIKEY_SECRET');
$client = \Stormpath\Client::getInstance();
$apps = $client->tenant->applications;
$apps->search = array('name' => 'My Application');
$application = $apps->getIterator()->current();
$account = \Stormpath\Resource\Account::instantiate(
[
'givenName' => $request->input('username'),
'middleName' => '',
'surname' => 'StromTrooper',
'username' => $request->input('username'),
'email' => $request->input('user_mail'),
'password' => $request->input('user_pass'),
'confirmPassword' => $request->input('user_pass')
]
);
// Create User Account and Log-in the User
try
{
$response = $application->createAccount($account);
$passwordGrant = new \Stormpath\Oauth\PasswordGrantRequest(
$request->input('user_mail'),
$request->input('user_pass')
);
$auth = new \Stormpath\Oauth\PasswordGrantAuthenticator($application);
$result = $auth->authenticate($passwordGrant);
$atoken = cookie("access_token",
$result->getAccessTokenString(),
$result->getExpiresIn()
);
$rtoken = cookie("refresh_token",
$result->getRefreshTokenString(),
$result->getExpiresIn()
);
$response_bag['success'] = url('userprofile');
}
catch (\Stormpath\Resource\ResourceError $re)
{
$response_bag['error'] = $re->getMessage();
$atoken = 'null';
$rtoken = 'null';
}
return response()
->json($response_bag)
->withCookie($atoken)
->withCookie($rtoken);
and in the User controller I am able to access the user details using app('stormpath.user');
and since I was using Laravel 5.1
I had to comment out $token = $request->bearerToken(); from vendor/stormpath/laravel/src/Http/Middleware/Authenticate.php from function public function isAuthenticated(Request $request)

Laravel - authenticating with session token

Upon login, I return the user object + session token in JSON form, so that the mobile device that connects to my application can be authenticated.
However, I have a difficulty understanding how would I go about authenticating the user only with his session id?
Once logged in, the mobile device sends the session token upon every request, which means I somehow need to check whether it's the same user (using a custom auth filter).
How would I do it?
You may have a table for saving tokens
Add a filter in routes.php
Route::group(array('before' => 'auth'), function() { ... })
And in the filters.php you can search the token in the database, if isn't exist you return a no access response
Route::filter('auth', function () {
$input_token = Input::get('token');
if (!empty($input_token)) {
$validator = Validator::make(
['token' => $input_token],
['token' => 'token']
);
if (!$validator->fails()) {
$token = Token::where('hash', $input_token)->first();
if ($token) {
$user = User::find($token->user_id);
if ($user) {
Auth::login($user);
return;
}
}
}
}
$response = Response::make(json_encode([
'error' => true,
'messages' => [
Lang::get('errors.NO_ACCESS')
]
]), 200);
$response->header('Content-Type', 'application/json');
return $response;
});
You could do it like this:
$sessionID = '4842e441673747d0ce8b809fc5d1d06883fde3af'; // get this from \Session::getId(); from your previous authenticated request (after logging in because it changes).
$s = new \Illuminate\Session\Store(NULL, \Session::getHandler(), $sessionID);
$s->start();
$userID = $s->get('login_82e5d2c56bdd0811318f0cf078b78bfc');
\Session::set('login_82e5d2c56bdd0811318f0cf078b78bfc', $userID);
return \Auth::user();
Not the prettiest code but it works. It creates an instance of a session using the previous Session ID, then start loads it up from file. The user ID is in that key, so then it just sets the user id on the current session. Then when you call Auth::user() it loads up the User using that user id.
The reason for all the numbers in the key is because the larval developer thought it would be smart to hash the Auth class name to make the key as unique as possible... :-S

Laravel, log in user for one request

I am building a REST API with Laravel, and I have a filter that checks for a TOKEN:
Route::filter('api.auth', function() {
$token = Request::header('X-CSRF-Token') ? Request::header('X-CSRF-Token') : '';
if (empty($token)) {
return Response::json(
['message' => 'A valid API key is required!'],
401
);
};
$user = User::where('token', '=', $token);
if ($user->count()) {
$user = $user->first();
Auth::login($user);
} else {
return Response::json(
['message' => 'Your token has expired!'],
401
);
};
});
If everything is ok, the filter will log in the user with uth::login($user);
How can I log him for only 1 request?
Since this filter is going to be checked on every request, I think it would be better to log the user out each time.
I have seen this in Laravel's docs, not sure how to apply it:
if (Auth::once($credentials))
{
//
}
Could I have a callback in my response? where I could log the user out?
/*
Get all products.
*/
public function getProducts() {
$products = Auth::user()->products;
return Response::json($products, 200);
}
Any ideas?
If you haven't user's password use this:
if(Auth::onceUsingId($userId)) {
// do something here
}
If I correctly understand the question then I would say that, just replace following
Auth::login($user);
with this (To log the user in only for current request):
Auth::once(['email' => $user->email, 'password' => $user->password]);
If you log in a user only for once then you don't have to manually logo out the user, the user will be asked again for to log in on next request.

Resources