user_settings_posix.cc revision c407dc5cd9bdc5668497f21b26b09d988ab439de
1// Copyright (c) 2009 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// Implement the storage of service tokens in memory.
6
7#include "chrome/browser/sync/util/user_settings.h"
8
9#include "chrome/browser/password_manager/encryptor.h"
10#include "chrome/common/sqlite_utils.h"
11
12namespace browser_sync {
13
14void UserSettings::SetAuthTokenForService(
15    const std::string& email,
16    const std::string& service_name,
17    const std::string& long_lived_service_token) {
18
19  LOG(INFO) << "Saving auth token " << long_lived_service_token << " for "
20      << email << "for service " << service_name;
21
22  std::string encrypted_service_token;
23  if (!Encryptor::EncryptString(long_lived_service_token,
24                                &encrypted_service_token)) {
25    LOG(ERROR) << "Encrytion failed: " << long_lived_service_token;
26    return;
27  }
28  ScopedDBHandle dbhandle(this);
29  SQLStatement statement;
30  statement.prepare(dbhandle.get(),
31                    "INSERT INTO cookies "
32                    "(email, service_name, service_token) "
33                    "values (?, ?, ?)");
34  statement.bind_string(0, email);
35  statement.bind_string(1, service_name);
36  statement.bind_blob(2, encrypted_service_token.data(),
37                         encrypted_service_token.size());
38  if (SQLITE_DONE != statement.step()) {
39    LOG(FATAL) << sqlite3_errmsg(dbhandle.get());
40  }
41}
42
43bool UserSettings::GetLastUserAndServiceToken(const std::string& service_name,
44                                              std::string* username,
45                                              std::string* service_token) {
46  ScopedDBHandle dbhandle(this);
47  SQLStatement query;
48  query.prepare(dbhandle.get(),
49                "SELECT email, service_token FROM cookies"
50                " WHERE service_name = ?");
51  query.bind_string(0, service_name.c_str());
52
53  if (SQLITE_ROW == query.step()) {
54    std::string encrypted_service_token;
55    query.column_blob_as_string(1, &encrypted_service_token);
56    if (!Encryptor::DecryptString(encrypted_service_token, service_token)) {
57      LOG(ERROR) << "Decryption failed: " << encrypted_service_token;
58      return false;
59    }
60    *username = query.column_string(0);
61
62    LOG(INFO) << "Found service token for:" << *username
63      << " @ " << service_name << " returning: " << *service_token;
64
65    return true;
66  }
67
68  LOG(INFO) << "Couldn't find service token for " << service_name;
69
70  return false;
71}
72
73}  // namespace browser_sync
74