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 if value is None:
46 return None
47 return base64.b64encode(pickle.dumps(value))
48
49
51
52 __metaclass__ = models.SubfieldBase
53
56
58 if value is None:
59 return None
60 if isinstance(value, oauth2client.client.Flow):
61 return value
62 return pickle.loads(base64.b64decode(value))
63
65 if value is None:
66 return None
67 return base64.b64encode(pickle.dumps(value))
68
69
71 """Store and retrieve a single credential to and from
72 the datastore.
73
74 This Storage helper presumes the Credentials
75 have been stored as a CredenialsField
76 on a db model class.
77 """
78
79 - def __init__(self, model_class, key_name, key_value, property_name):
80 """Constructor for Storage.
81
82 Args:
83 model: db.Model, model class
84 key_name: string, key name for the entity that has the credentials
85 key_value: string, key value for the entity that has the credentials
86 property_name: string, name of the property that is an CredentialsProperty
87 """
88 self.model_class = model_class
89 self.key_name = key_name
90 self.key_value = key_value
91 self.property_name = property_name
92
94 """Retrieve Credential from datastore.
95
96 Returns:
97 oauth2client.Credentials
98 """
99 credential = None
100
101 query = {self.key_name: self.key_value}
102 entities = self.model_class.objects.filter(**query)
103 if len(entities) > 0:
104 credential = getattr(entities[0], self.property_name)
105 if credential and hasattr(credential, 'set_store'):
106 credential.set_store(self)
107 return credential
108
110 """Write a Credentials to the datastore.
111
112 Args:
113 credentials: Credentials, the credentials to store.
114 """
115 args = {self.key_name: self.key_value}
116 entity = self.model_class(**args)
117 setattr(entity, self.property_name, credentials)
118 entity.save()
119
121 """Delete Credentials from the datastore."""
122
123 query = {self.key_name: self.key_value}
124 entities = self.model_class.objects.filter(**query).delete()
125