1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 """OAuth 2.0 utilities for Django.
16
17 Utilities for using OAuth 2.0 in conjunction with
18 the Django datastore.
19 """
20
21 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
22
23 import oauth2client
24 import base64
25 import pickle
26
27 from django.db import models
28 from oauth2client.client import Storage as BaseStorage
29
31
32 __metaclass__ = models.SubfieldBase
33
36
43
45 return base64.b64encode(pickle.dumps(value))
46
47
49
50 __metaclass__ = models.SubfieldBase
51
54
56 if value is None:
57 return None
58 if isinstance(value, oauth2client.client.Flow):
59 return value
60 return pickle.loads(base64.b64decode(value))
61
63 return base64.b64encode(pickle.dumps(value))
64
65
67 """Store and retrieve a single credential to and from
68 the datastore.
69
70 This Storage helper presumes the Credentials
71 have been stored as a CredenialsField
72 on a db model class.
73 """
74
75 - def __init__(self, model_class, key_name, key_value, property_name):
76 """Constructor for Storage.
77
78 Args:
79 model: db.Model, model class
80 key_name: string, key name for the entity that has the credentials
81 key_value: string, key value for the entity that has the credentials
82 property_name: string, name of the property that is an CredentialsProperty
83 """
84 self.model_class = model_class
85 self.key_name = key_name
86 self.key_value = key_value
87 self.property_name = property_name
88
90 """Retrieve Credential from datastore.
91
92 Returns:
93 oauth2client.Credentials
94 """
95 credential = None
96
97 query = {self.key_name: self.key_value}
98 entities = self.model_class.objects.filter(**query)
99 if len(entities) > 0:
100 credential = getattr(entities[0], self.property_name)
101 if credential and hasattr(credential, 'set_store'):
102 credential.set_store(self)
103 return credential
104
106 """Write a Credentials to the datastore.
107
108 Args:
109 credentials: Credentials, the credentials to store.
110 """
111 args = {self.key_name: self.key_value}
112 entity = self.model_class(**args)
113 setattr(entity, self.property_name, credentials)
114 entity.save()
115
117 """Delete Credentials from the datastore."""
118
119 query = {self.key_name: self.key_value}
120 entities = self.model_class.objects.filter(**query).delete()
121