1# Copyright 2015 Google Inc. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Contains a storage module that stores credentials using the Django ORM.""" 16 17from oauth2client import client 18 19 20class DjangoORMStorage(client.Storage): 21 """Store and retrieve a single credential to and from the Django datastore. 22 23 This Storage helper presumes the Credentials 24 have been stored as a CredentialsField 25 on a db model class. 26 """ 27 28 def __init__(self, model_class, key_name, key_value, property_name): 29 """Constructor for Storage. 30 31 Args: 32 model: string, fully qualified name of db.Model model class. 33 key_name: string, key name for the entity that has the credentials 34 key_value: string, key value for the entity that has the 35 credentials. 36 property_name: string, name of the property that is an 37 CredentialsProperty. 38 """ 39 super(DjangoORMStorage, self).__init__() 40 self.model_class = model_class 41 self.key_name = key_name 42 self.key_value = key_value 43 self.property_name = property_name 44 45 def locked_get(self): 46 """Retrieve stored credential from the Django ORM. 47 48 Returns: 49 oauth2client.Credentials retrieved from the Django ORM, associated 50 with the ``model``, ``key_value``->``key_name`` pair used to query 51 for the model, and ``property_name`` identifying the 52 ``CredentialsProperty`` field, all of which are defined in the 53 constructor for this Storage object. 54 55 """ 56 query = {self.key_name: self.key_value} 57 entities = self.model_class.objects.filter(**query) 58 if len(entities) > 0: 59 credential = getattr(entities[0], self.property_name) 60 if getattr(credential, 'set_store', None) is not None: 61 credential.set_store(self) 62 return credential 63 else: 64 return None 65 66 def locked_put(self, credentials): 67 """Write a Credentials to the Django datastore. 68 69 Args: 70 credentials: Credentials, the credentials to store. 71 """ 72 entity, _ = self.model_class.objects.get_or_create( 73 **{self.key_name: self.key_value}) 74 75 setattr(entity, self.property_name, credentials) 76 entity.save() 77 78 def locked_delete(self): 79 """Delete Credentials from the datastore.""" 80 query = {self.key_name: self.key_value} 81 self.model_class.objects.filter(**query).delete() 82