Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / extensions / token_cache / token_cache_service.cc
1 // Copyright (c) 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/extensions/token_cache/token_cache_service.h"
6
7 #include "base/logging.h"
8 #include "chrome/browser/signin/signin_manager_factory.h"
9 #include "components/signin/core/browser/signin_manager.h"
10
11 using base::Time;
12 using base::TimeDelta;
13
14 namespace extensions {
15
16 TokenCacheService::TokenCacheService(Profile* profile) : profile_(profile) {
17   SigninManagerFactory::GetForProfile(profile)->AddObserver(this);
18 }
19
20 TokenCacheService::~TokenCacheService() {
21 }
22
23 void TokenCacheService::StoreToken(const std::string& token_name,
24                                    const std::string& token_value,
25                                    base::TimeDelta time_to_live) {
26   TokenCacheData token_data;
27
28   // Get the current time, and make sure that the token has not already expired.
29   Time expiration_time;
30   TimeDelta zero_delta;
31
32   // Negative time deltas are meaningless to this function.
33   DCHECK(time_to_live >= zero_delta);
34
35   if (zero_delta < time_to_live) {
36     expiration_time = Time::Now();
37     expiration_time += time_to_live;
38   }
39
40   token_data.token = token_value;
41   token_data.expiration_time = expiration_time;
42
43   // Add the token to our cache, overwriting any existing token with this name.
44   token_cache_[token_name] = token_data;
45 }
46
47 // Retrieve a token for the currently logged in user.  This returns an empty
48 // string if the token was not found or timed out.
49 std::string TokenCacheService::RetrieveToken(const std::string& token_name) {
50   std::map<std::string, TokenCacheData>::iterator it =
51       token_cache_.find(token_name);
52
53   if (it != token_cache_.end()) {
54     Time now = Time::Now();
55     if (it->second.expiration_time.is_null() ||
56         now < it->second.expiration_time) {
57       return it->second.token;
58     } else {
59       // Remove this entry if it is expired.
60       token_cache_.erase(it);
61       return std::string();
62     }
63   }
64
65   return std::string();
66 }
67
68 void TokenCacheService::Shutdown() {
69   SigninManagerFactory::GetForProfile(const_cast<Profile*>(profile_))
70       ->RemoveObserver(this);
71 }
72
73 void TokenCacheService::GoogleSignedOut(const std::string& account_id,
74                                         const std::string& username) {
75   token_cache_.clear();
76 }
77
78 }  // namespace extensions