Move util_ files into utils directory, move main.cpp into src
[gssweb.git] / json_gssapi / src / cache / GSSContextCache.cpp
1 /*
2  * Copyright (c) 2014 <copyright holder> <email>
3  *
4  * For license details, see the LICENSE file in the root of this project.
5  *
6  */
7
8 #include <stdexcept>
9 #include "utils/util_random.h"
10 #include "utils/util_base64.h"
11
12 #include "GSSContextCache.h"
13
14 #define KEYLEN 128
15
16 GSSContextCache* GSSContextCache::_instance = 0;
17
18 GSSContextCache::GSSContextCache()
19 {
20
21 }
22
23 GSSContextCache::~GSSContextCache()
24 {
25
26 }
27
28 GSSContextCache* GSSContextCache::instance()
29 {
30     if (_instance == 0)
31       _instance = new GSSContextCache;
32     
33     return _instance;
34 }
35
36
37 std::string GSSContextCache::store ( GSSContext& data, std::string inKey )
38 {
39   /* Variables      */
40   std::string key;
41   
42   /* Error checking */
43   /* Setup          */
44   /* Main           */
45   // Generate a key
46   if ( inKey.length() > 0 )
47   {
48     key = inKey;
49   }
50   else if ( !generateKey(key) )
51   {
52     // Key generation failed.  Eeek!
53     throw std::runtime_error("Could not generate random data for an ID");
54   }
55   
56   // Store the key/value pair in the map
57   // Store the key in the context for convenience
58   contexts[key] = data;
59   
60   /* Cleanup        */
61   /* Return         */
62   // Return the key for future reference
63   return(key);
64 }
65
66 /*************************************
67  * Generate random bytes, and base64 *
68  * encode them to be JSONable keys   *
69  *************************************/
70 bool GSSContextCache::generateKey(std::string &key)
71 {
72   /* Variables      */
73   unsigned char theKey[KEYLEN];
74
75   if (!randGenPseudoRandom(theKey, KEYLEN))
76       return false;
77
78   // Encode the binary string
79   base64EncodeStr(theKey, KEYLEN, key);
80
81   /* Cleanup        */
82   /* Return         */
83   return(true);
84 }
85
86 GSSContext& GSSContextCache::retrieve ( std::string key )
87 {
88   /* Variables      */
89   //GSSContext data;
90   
91   /* Error checking */
92   /* Setup          */
93   /* Main           */
94   // Maybe do something about data entries that are expired?
95   
96   /* Cleanup        */
97   /* Return         */
98   return contexts[key];
99 }
100
101   /* Variables      */
102   /* Error checking */
103   /* Setup          */
104   /* Main           */
105   /* Cleanup        */
106   /* Return         */