Laravel - Api request - api

I have a website build with Laravel 4.2 and a controller that are accessible only to logged user:
Route::group(['prefix' => 'pannello-utente', 'before' => 'auth'], function ()
{
Route::get('elenco-animali/{nome?}', ['uses' => 'PazientiController#index']);
Route::get('download/{cartella}/{file}', ['uses' => 'PazientiController#download']);
});
the auth method request user to insert email and password.
In the PazientiController I have the __construct method that perform some queries that retrieve a code and use it in the other method:
public function __construct()
{
$this->current_user = Auth::user();
//Recupero il codice cliente salvato nel profilo utente
$this->codice = User::find($this->current_user->id)->first()->profile->codice_cliente;
}
This code is saved only in the database and, at the moment, no other application have it so I need to execute that query every time.
I need that, now via curl then via smartphone app, the user can access to the method, so I need users to log in before:
curl --user chri788#gmail.com:adminadmin localhost:8888/*****/public/pannello-utente/elenco-animali
But I get this:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url=http://localhost:8888/*****/public/login" />
<title>Redirecting to http://localhost:8888/*****/public/login</title>
</head>
<body>
Redirecting to http://localhost:8888/****/public/login.
</body>
</html>
How can I access to that controller?

The --user flag for curl triggers HTTP Basic Authentication. Laravel supports this, but not with the auth filter - it needs the auth.basic filter.
You can write a custom filter that checks both auth and auth.basic, or you can provide a separate set of routes (maybe prefixed with api) that uses the alternate filter.
http://laravel.com/docs/4.2/security#http-basic-authentication

Related

Difference between GET/POST express Response.redirect

I am trying to redirect a user after authentication from a login service to the resource service. There for, when someone tries to access the main page of my app, I check for the auth token inside a cookie and based on that validation, I serve the html file or redirect to the auth service where I am greeting them with a login/register form.
if(cookie?.auth){
return res.status( 301 ).redirect( `${ protocol }://${ process.env.REDIRECT_AUTH }/login?redirect=${ protocol }://${ hostname }:${ PORT }&session=${ req.sessionID }` );
}
This part works as expected. I get redirected to the endpoint. The question mark appears here. After I enter the credentials, I make a post request to the auth service and if everything goes right, I call the res.redirect(location), the location being the redirect query listed in the link above with some parameters as well.
Here is the snippit:
return res.status( 301 ).redirect( `${ location }?auth=${ token }` as string );
Of course, I am checking if the request query contain the credentials I need. The request actually returns 200, but instead of being redirected to the page, I get the file as a response payload.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
HAASDASD
</body>
</html>
My immediate conclusion was that is about the difference between the GET vs POST method and therefor I get a different result. Is there anyone who stumbled into something similar?

Using Google Analytics on a 503 page

I'm using varnish to cache our pages. When we get a 503 -- which happens a little too often -- I'd like to put some sort of page tracking on there. I'd like to place the GA code in there. I can't seem to find any instance of anyone else doing this. Has anyone done this? Is there some sort of T&C violation in doing this?
For Varnish you can use vcl_error to include your own responses (that have the Google Analytics code).
Edit: I have not tested any of these. They are just examples.
An example:
sub vcl_error {
set obj.http.Content-Type = "text/html; charset=utf-8";
if (obj.status == 503) {
synthetic {"
<html>
<head>
<title></title>
</head>
<body>
<h1>Error</h1>
<p>Something</p>
<!-- ANALYTICS CODE -->
</body>
</html>
"};
return(deliver);
}
}
Alternatively you can add your own pages from the file system by using vmod (which is included as standard with version 3.*+).
# Add this to the top of your config
import std;
# vcl_error
sub vcl_error {
set obj.http.Content-Type = "text/html; charset=utf-8";
if (obj.status == 503) {
set obj.http.error503 = std.fileread("/path/to/errors/503.html");
synthetic obj.http.error503;
return(deliver);
}
}

Google Analytics API v3 authorization to allow access to my data

I am developing an app that allows users to see my own Google Analytics Data using Google API v3.
Everything I researched seems to indicate that users need to login into their Google accounts and grant my app the access before I can start querying the API; however, that's not what I want, I just need my users to see my own Analytics data. How can authorize the API to access my data.
I have the client ID and Client Secret, but the OAuth that's implemented by Google's API v3 is asking for an authorization token, which can only be obtained by getting the user to login into their google account (is that right?)
Is there a way to just login into my own Google Analytics account and display that information to the users?
I believe what you want to do is set up a Service Account:
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtAuthorization
"Useful for automated/offline/scheduled access to Google Analytics data for your own account. For example, to build a live dashboard of your own Google Analytics data and share it with other users.
There are a few steps you need to follow to configure service accounts to work with Google Analytics:
Register a project in the APIs Console.
In the Google APIs Console, under the API Access pane, create a
client ID with the Application Type set to Service Account.
Sign-in to Google Analytics and navigate to the Admin section.
Select the account for which you want the application to have access
to.
Add the email address, from the Client ID created in the APIs
Console from step #2, as a user of the selected Google Analytics
account.
Follow the instructions for Service Accounts to access Google Analytics data: https://developers.google.com/accounts/docs/OAuth2ServiceAccount"
You can use a refresh token for offline access. Once you get the refresh token, you can save it to a file or database and use that to access the data without an authorization redirect.
See Using a Refresh Token in the docs.
Also see: How can we access specific Google Analytics account data using API?
Here is a full Google Analytics reporting example implementation with service account including setup notes. Just wrote it after reading your question, I had the same problem.
<?php
// Service account code from http://stackoverflow.com/questions/18258593/using-a-service-account-getaccesstoken-is-returning-null
// Analytics code from https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/analytics/simple.php?r=474
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
// Set your client id, service account name (AKA "EMAIL ADDRESS"), and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'CLIENT ID';
const SERVICE_ACCOUNT_NAME = 'SERVICE ACCOUNT NAME (IS "EMAIL ADDRESS")';
const KEY_FILE = 'KEY FILE';
const SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
// OPEN GOOGLE ANALYTICS AND GRANT ACCESS TO YOUR PROFILE, THEN PASTE IN YOUR SERVICE_ACCOUNT_NAME
$key = file_get_contents(KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array(SCOPE),
$key
);
$client = new Google_Client();
$client->setScopes(array(SCOPE));
$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$accessToken = $client->getAccessToken();
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
?>
<!DOCTYPE html>
<html>
<head>
<title>Google Experiments Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body class="container">
<h1>Your experiments</h1>
<table class="table"><tr><th><th>Experiment<th>Page<th>Started<th>Status
<?php
$progressClasses = array('progress-bar progress-bar-success','progress-bar progress-bar-info','progress-bar progress-bar-warning', 'progress-bar progress-bar-danger');
$profiles = $service->management_profiles->listManagementProfiles("~all", "~all");
foreach ($profiles['items'] as $profile) {
$experiments = $service->management_experiments->listManagementExperiments($profile['accountId'], $profile['webPropertyId'], $profile['id']);
foreach ($experiments['items'] as $experiment) {
echo "<tr>";
if ($experiment['status'] == 'RUNNING')
echo '<td><a class="btn btn-xs btn-success"><i class="glyphicon glyphicon-ok"></i></a>';
else
echo '<td><a class="btn btn-xs btn-danger"><i class="glyphicon glyphicon-remove"></i></a>';
$expHref = "https://www.google.com/analytics/web/?pli=1#siteopt-experiment/siteopt-detail/a{$profile['accountId']}w{$experiment['internalWebPropertyId']}p{$experiment['profileId']}/%3F_r.drilldown%3Danalytics.gwoExperimentId%3A{$experiment['id']}/";
echo "<td><a href='$expHref' target='_blank'>{$experiment['name']}</a>";
echo "<td>{$experiment['variations'][0]['url']}";
echo "<td>".date('Y-m-d',strtotime($experiment['startTime']));
echo "<td>";
echo '<div class="progress" style="width:400px">';
foreach ($experiment['variations'] as $i => $variation) {
echo '<div class="'.$progressClasses[$i].'" role="progressbar" style="width: '.(100*$variation['weight']).'%">'.$variation['name'].'</div>';
}
echo '</div>';
}
}
?>
Code with more documentation at https://gist.github.com/fulldecent/6728257

sfFacebookConnectPlugin: Authentication problem

I try to get the sfFacebookConnectPlugin to run by following the tutorial on the symfony homepage.
Everything seems well configured. But when I try to login with sfFacebookConnectAuth/signin.
I get the form error "The username and/or password is invalid.".
I even don't know where to start with the debugging.
First Step could be to find out the right Application-Settings on the Facebook-Side (e.g. Post-Authorize Callback URL, Connect-URL or Canvas Callback URL)
I use symfony 1.4.5 doctrine with sfGuardDoctrinePlugin (on a live host with subdomain.)
Thx for your help.
I found that page: http://burgiblog.com/2009/09/18/developing-facebook-applications-with-symfony/ now it works, I changed three things after reading the tutorial:
modules/sfFacebookConnectAuth/config/security.yml: Use "false" instead of "off"
I added "callback_url" in apps/frontend/config/app.yml
And I used the facebook action in the tutorial
I need to find out, what the problem exactly was. And I need to enhance some things to the plugin. E.g. saving the user data to my profile class etc. (Now I saves a cryptic username instead of the right FB username.)
It says on the plugin page that this plugin is only supported/stable up to Symfony 1.2. Might make sense to email the plugin author directly regarding 1.4 compatibility.
I'm having some problems with sfFacebookConnectPlugin. I tried replicating the simple example from http://burgiblog.com/2009/09/18/developing-facebook-applications-with-symfony/ . And calling the index page, I get redirected to the facebook authentication page but after logging in, I do not get redirected back. I stay logged into facebook only. What am I doing wrong?
Thanks.
This is my code:
[/frontend/config/app.yml]
# default values
all:
facebook:
api_key: xxx
api_secret: xxx
api_id: xxx
callback_url: 'http://localhost'
redirect_after_connect: false
redirect_after_connect_url: ''
connect_signin_url: 'sfFacebookConnectAuth/signin'
app_url: '/my-app'
guard_adapter: ~
js_framework: none # none, jQuery or prototype.
# It is highly recommended to use a js framework if you want a correct experience in IE
sf_guard_plugin:
profile_class: sfGuardUserProfile
profile_field_name: user_id
profile_facebook_uid_name: facebook_uid # WARNING this column must be of type bigint ! 100000398093902 is a valid uid for example !
profile_email_name: email
profile_email_hash_name: email_hash
facebook_connect:
load_routing: true
user_permissions: []
[layout.php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<?php use_helper('sfFacebookConnect') ?>
<?php include_http_metas() ?>
<?php include_metas() ?>
<?php include_title() ?>
<link rel="shortcut icon" href="/favicon.ico" />
</head>
<body>
<?php echo $sf_content ?>
<?php include_bottom_facebook_connect_script(); ?>
</body>
</html>
[actions.class.php]
<?php
/**
* facebook actions.
*
* #package
* #subpackage facebook
* #author Your name here
* #version SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
*/
class homeActions extends sfActions
{
/**
* Executes index action
*
* #param sfRequest $request A request object
*/
public function executeIndex(sfWebRequest $request)
{
sfFacebook::requireLogin();
//get the user object
$user = $this->getUser();
// facebook user id
$this->fb_uid = $user->getCurrentFacebookUid();
// get or create user based on fb_uid
$fb_user = sfFacebook::getOrCreateUserByFacebookUid($this->fb_uid);
}
}
[indexSuccess.php]
<?php if ($sf_user->isFacebookConnected()): ?>
<fb:serverfbml style="width: 740px;">
<script type="text/fbml">
<fb:fbml>
<fb:request-form target="_top" action="[where to redirect after invite]" method="post" type="[name of your app]" content="[text the user will receive]<fb:req-choice url="http://apps.facebook.com/[your app]/" label="Accept!" " image="" invite="true">
<fb:multi-friend-selector cols="4" actiontext="[some text above the invite form]" />
</fb:request-form>
</fb:fbml>
</script>
</fb:serverfbml>
<?php else: ?>
<p>Ooops?</p>
<br />
<?php endif; ?>

Using Google's ClientLogin Interface via XMLHttpRequest in Javascript

I am trying to learn the ClientLogin Interface detailed on the Account Authentication APIs on Google code website.
I am using Firefox 3.5pre (Shiretoko) and XMLHttpRequest object in Javascript to follow the process. Here's a stripped down version of what I have:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
//<![CDATA[
function update() {
var auth_params = "accountType=HOSTED_OR_GOOGLE&Email=val"
+"&passwd=val&service=cl&source=MMA-Learning";
var request = new XMLHttpRequest();
request.open('POST', 'https://www.google.com/accounts/ClientLogin', true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", auth_params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert ("Request done");
}
};
try {
request.send( auth_params );
} catch (e) {
alert ("Send Exception:\n"+e);
}
}
//]]>
</script>
</head>
<body>
Authenticate
</body>
</html>
When I click on the Authenticate link, all I get back is a Bad Request response. Examining the request headers, I don't see Content-Type set to application/x-www-form-urlencoded.
I am using Firebug 1.5X to examine the traffic.
For now, all I want to do is generate request mentioned in the Sample Request section and get a response mentioned in the Sample Responses section. If I get there, I want to get some account specific data like, unread Google Reader feeds etc.
I suspect that you've been bitten by Javascript's "same origin" policy. It prevents Javascript, including XmlHttpRequest, from accessing one domain from another. More information is available from Mozilla.
There are hacks to get around this, but I have no idea if they'll work with Google's API.
the 'p' in 'passwd' is a small 'p' instead of a capital 'P'
you probably figured that out tho. When you post and you find the answer, it is always polite if you post the answer as well. This helps the people in the future who will look at your post for information
That 'p' took me two hours to find because i persummed that the code google gave was copied correctely and there was no case mistakes
no point in Internet being full of questions with no answers