1// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/signin/signin_oauth_helper.h"
6
7#include "base/message_loop/message_loop.h"
8#include "chrome/browser/profiles/profile.h"
9#include "chrome/browser/signin/profile_oauth2_token_service.h"
10#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
11#include "google_apis/gaia/gaia_auth_fetcher.h"
12#include "google_apis/gaia/gaia_constants.h"
13
14// TODO(guohui): needs to figure out the UI for error cases.
15
16SigninOAuthHelper::SigninOAuthHelper(Profile* profile)
17    : profile_(profile) {}
18
19SigninOAuthHelper::~SigninOAuthHelper() {}
20
21void SigninOAuthHelper::StartAddingAccount(const std::string& oauth_code) {
22  gaia_auth_fetcher_.reset(new GaiaAuthFetcher(
23      this, GaiaConstants::kChromeSource, profile_->GetRequestContext()));
24  gaia_auth_fetcher_->StartAuthCodeForOAuth2TokenExchange(oauth_code);
25}
26
27void SigninOAuthHelper::OnClientOAuthSuccess(const ClientOAuthResult& result) {
28  DVLOG(1) << "SigninOAuthHelper::OnClientOAuthSuccess";
29
30  refresh_token_ = result.refresh_token;
31  gaia_auth_fetcher_->StartOAuthLogin(result.access_token,
32                                      GaiaConstants::kGaiaService);
33}
34
35void SigninOAuthHelper::OnClientOAuthFailure(
36      const GoogleServiceAuthError& error) {
37  VLOG(1) << "SigninOAuthHelper::OnClientOAuthFailure : " << error.ToString();
38  base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
39}
40
41void SigninOAuthHelper::OnClientLoginSuccess(const ClientLoginResult& result) {
42  DVLOG(1) << "SigninOAuthHelper::OnClientLoginSuccess";
43  gaia_auth_fetcher_->StartGetUserInfo(result.lsid);
44}
45
46void SigninOAuthHelper::OnClientLoginFailure(
47    const GoogleServiceAuthError& error) {
48  VLOG(1) << "SigninOAuthHelper::OnClientLoginFailure : " << error.ToString();
49  base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
50}
51
52void SigninOAuthHelper::OnGetUserInfoSuccess(const UserInfoMap& data) {
53  DVLOG(1) << "SigninOAuthHelper::OnGetUserInfoSuccess";
54
55  UserInfoMap::const_iterator email_iter = data.find("email");
56  if (email_iter == data.end()) {
57    VLOG(1) << "SigninOAuthHelper::OnGetUserInfoSuccess : no email found ";
58  } else {
59    ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
60        ->UpdateCredentials(email_iter->second, refresh_token_);
61  }
62  base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
63}
64
65void SigninOAuthHelper::OnGetUserInfoFailure(
66    const GoogleServiceAuthError& error) {
67  VLOG(1) << "SigninOAuthHelper::OnGetUserInfoFailure : " << error.ToString();
68  base::MessageLoop::current()->DeleteSoon(FROM_HERE, this);
69}
70