我正在尝试创建一个带有简单仪表板的网络应用程序,其中包含使用 Google 登录的帐户的分析数据。我正在使用带有 Socialite 包的 Laravel,目前我可以使用 Google 登录用户。我有我的开发者客户端 key 和客户端 key 。我为 Analytics 设置了只读和离线访问的范围,并将客户名称、电子邮件、Google ID、访问 token 和刷新 token 存储在我的数据库中。我可以毫无问题地让用户登录。
我现在想做的是,只访问 Analytics 帐户当前拥有的配置文件。我遵循了 Analytics API 文档示例,但无法使其正常工作。由于我存储了一个访问 token 和一个刷新 token ,我想我应该能够验证当前用户并获取他们的分析数据,但我无法从客户端和分析库中找到任何简单的方法。我将需要离线访问他们的 Analytics 数据,这就是为什么我认为我应该能够使用访问 token 和刷新 token 授权我的请求,但我没有从用户登录过程中获得任何特定于 Analytics 的数据。我现在完全迷路了,如何授权我对 Anayltics API 的请求?我使用 AdWords API 已经超过 8 个月了,AdWords API 文档中的所有内容都非常清楚,但我无法使用 Analytics API 进行任何操作。
这些是我的用户登录方法:
public function redirectToProvider()
{
$parameters = ['access_type' => 'offline'];
return Socialite::driver('google')
->scopes(['https://www.googleapis.com/auth/analytics.readonly'])
->with($parameters)
->redirect();
}
/**
* Obtain the user information from Google.
*
* @return Response
*/
public function handleProviderCallback()
{
$outsiderLogin = Socialite::driver('google')->stateless()->user();
$user = User::where('googleID', $outsiderLogin->id)->first();
// Register the user if there is no user with that id.
if (!$user) {
$user = new User;
$user->name = $outsiderLogin->name;
$user->googleID = $outsiderLogin->id;
$user->email = $outsiderLogin->email;
$user->token = $outsiderLogin->token;
$user->refreshToken = $outsiderLogin->refreshToken;
$user->save();
}
// Log the user in.
Auth::login($user);
return redirect('/home');
}
非常感谢。
最佳答案
我现在已经找到了解决方案。起初,我认为我需要从 Google 返回带有身份验证 URL 的代码,当我检查 Socialite 包时,我在 \vendor\laravel 中找到了一个 protected 方法 ,它从 URL 返回代码。我编辑了包的源文件并将方法类型从 getCode()\socialite\src\Two\AbstractProvider.phpprotected 更改为 public,这使得在类之外使用该方法成为可能,这让我能够从 URL 访问代码,然后将其存储在数据库中以用于进一步的身份验证要求。但是此设置存在问题,首先,我应该找到一种方法来保留该包而不进行任何更新,因为任何更新都会回滚我对源文件所做的更改。我面临的第二个问题是我存储 token 的方式。默认情况下,Google 客户端 API 返回一个数组,其中包含字段 access_token、refresh_token、expires_in、id 和 created,并使用这些字段验证对 Analytics 服务器的请求。在我的场景中,基本的 Socialite 登录过程没有返回标准数组。有 access_token、refresh_token 和 expires 变量,我也将它们都存储在我的数据库中。这导致 Google 库出现问题,它要求结构化数组,而我什至没有变量 expires_in 和 created,这就是为什么我设置了一个假数组,它告诉Google 会在每次请求时刷新 token ,这也不是一个好的做法。
最后,我看不懂网上有什么包怎么用,自己写了一个简单的认证,不知道有没有漏洞,但是对我有用,可能对需要的人也有用
这是我的路线:
Route::get('auth/google', [
'as' => 'googleLogin',
'uses' => 'Auth\AuthController@redirectToProvider'
]);
Route::get('auth/google/callback', [
'as' => 'googleLoginCallback',
'uses' => 'Auth\AuthController@handleProviderCallback'
]);
这些是 AuthController 方法:
/**
* Redirect the user to the Google authentication
*/
public function redirectToProvider()
{
// Create the client object and set the authorization configuration from JSON file.
$client = new Google_Client();
$client->setAuthConfig('/home/vagrant/Analytics/client_secret.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/auth/google/callback');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->addScope("email");
$client->addScope("profile");
$client->setAccessType("offline");
$auth_url = $client->createAuthUrl();
return redirect($auth_url);
}
/**
* Obtain the user information from Google.
*
* @return redirect to the app.
*/
public function handleProviderCallback()
{
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
return redirect('auth/google');
} else {
// Authenticate the client, and get required informations.
$client = new Google_Client();
$client->setAuthConfig('/home/vagrant/Analytics/client_secret.json');
$client->authenticate($_GET['code']);
// Store the tokens in the session.
Session::put('token', $client->getAccessToken());
$service = new Google_Service_Oauth2($client);
$userInfo = $service->userinfo->get();
$user = User::where('googleID', $userInfo->id)->first();
// If no match, register the user.
if(!$user) {
$user = new User;
$user->name = $userInfo->name;
$user->googleID = $userInfo->id;
$user->email = $userInfo->email;
$user->refreshToken = $client->getRefreshToken();
$user->code = $_GET['code'];
$user->save();
}
Auth::login($user);
return redirect('/home');
}
}
我已经将从 Google API 控制台下载的 client_secret.json 文件放在指定的文件夹中,这对您来说可能有所不同。我还修改了迁移文件以匹配所需的段。在这些步骤之后,我可以将该用户视为注册了基本 Laravel 身份验证的简单用户。
现在我可以像这样查询用户的 Google Analytics 帐户中的帐户:
/**
* @var $client to be authorized by Google.
*/
private $client;
/**
* @var $analytics Analytics object to be used.
*/
private $analytics;
public function __construct()
{
$this->client = $this->AuthenticateCurrentClient();
$this->analytics = new Google_Service_Analytics($this->client);
}
private function AuthenticateCurrentClient(){
$user = Auth::user();
$token = Session::get('token');
// Authenticate the client.
$client = new Google_Client();
$client->setAccessToken($token);
$client->authenticate($user->code);
return $client;
}
public function GetAccounts(){
try {
$accountsObject = $this->analytics->management_accounts->listManagementAccounts();
$accounts = $accountsObject->getItems();
return $accounts;
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
}
Stack Overflow 已经帮助了我数千次,我希望这能帮助别人解决问题。
关于php - laravel - 谷歌分析 API 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38276827/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt