- add sources.
[platform/framework/web/crosswalk.git] / src / cloud_print / gcp20 / prototype / x_privet_token.cc
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 "cloud_print/gcp20/prototype/x_privet_token.h"
6
7 #include "base/base64.h"
8 #include "base/format_macros.h"
9 #include "base/guid.h"
10 #include "base/logging.h"
11 #include "base/sha1.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/stringprintf.h"
14
15 namespace {
16
17 const char kXPrivetTokenDelimeter = ':';
18 const uint64 kTimeExpiration = 24*60*60;  // in seconds
19 const uint64 kTimeSecretRefresh = 24*60*60;  // in seconds
20
21 }  // namespace
22
23 using base::Time;
24 using base::TimeDelta;
25
26 XPrivetToken::XPrivetToken() {
27   UpdateSecret();
28 }
29
30 XPrivetToken::XPrivetToken(const std::string& secret,
31                            const base::Time& gen_time)
32     : secret_(secret),
33       last_gen_time_(gen_time) {
34 }
35
36 std::string XPrivetToken::GenerateXToken() {
37   if (Time::Now() > last_gen_time_ + TimeDelta::FromSeconds(kTimeSecretRefresh))
38     UpdateSecret();
39
40   return GenerateXTokenWithTime(static_cast<uint64>(Time::Now().ToTimeT()));
41 }
42
43 bool XPrivetToken::CheckValidXToken(const std::string& token) const {
44   size_t delimeter_pos = token.find(kXPrivetTokenDelimeter);
45   if (delimeter_pos == std::string::npos)
46     return false;
47
48   std::string issue_time_str = token.substr(delimeter_pos + 1);
49   uint64 issue_time;
50   if (!base::StringToUint64(issue_time_str, &issue_time))
51     return false;
52
53   if (GenerateXTokenWithTime(issue_time) != token)
54     return false;
55
56   return Time::FromTimeT(issue_time) - last_gen_time_ <
57       TimeDelta::FromSeconds(kTimeExpiration);
58 }
59
60 std::string XPrivetToken::GenerateXTokenWithTime(uint64 issue_time) const {
61   std::string result;
62   std::string issue_time_str = base::StringPrintf("%"PRIu64, issue_time);
63   std::string hash = base::SHA1HashString(secret_ +
64                                           kXPrivetTokenDelimeter +
65                                           issue_time_str);
66   base::Base64Encode(hash, &result);
67   return result + kXPrivetTokenDelimeter + issue_time_str;
68 }
69
70 void XPrivetToken::UpdateSecret() {
71   secret_ = base::GenerateGUID();
72   last_gen_time_ = base::Time::Now();
73   VLOG(1) << "New Secret is Generated.";
74 }
75