Behave properly on empty search.
[wolnelektury.git] / apps / piston / managers.py
1 from django.db import models
2 from django.contrib.auth.models import User
3
4 KEY_SIZE = 18
5 SECRET_SIZE = 32
6
7 class KeyManager(models.Manager):
8     '''Add support for random key/secret generation
9     '''
10     def generate_random_codes(self):
11         key = User.objects.make_random_password(length=KEY_SIZE)
12         secret = User.objects.make_random_password(length=SECRET_SIZE)
13
14         while self.filter(key__exact=key, secret__exact=secret).count():
15             secret = User.objects.make_random_password(length=SECRET_SIZE)
16
17         return key, secret
18
19
20 class ConsumerManager(KeyManager):
21     def create_consumer(self, name, description=None, user=None):
22         """
23         Shortcut to create a consumer with random key/secret.
24         """
25         consumer, created = self.get_or_create(name=name)
26
27         if user:
28             consumer.user = user
29
30         if description:
31             consumer.description = description
32
33         if created:
34             consumer.key, consumer.secret = self.generate_random_codes()
35             consumer.save()
36
37         return consumer
38
39     _default_consumer = None
40
41 class ResourceManager(models.Manager):
42     _default_resource = None
43
44     def get_default_resource(self, name):
45         """
46         Add cache if you use a default resource.
47         """
48         if not self._default_resource:
49             self._default_resource = self.get(name=name)
50
51         return self._default_resource        
52
53 class TokenManager(KeyManager):
54     def create_token(self, consumer, token_type, timestamp, user=None):
55         """
56         Shortcut to create a token with random key/secret.
57         """
58         token, created = self.get_or_create(consumer=consumer, 
59                                             token_type=token_type, 
60                                             timestamp=timestamp,
61                                             user=user)
62
63         if created:
64             token.key, token.secret = self.generate_random_codes()
65             token.save()
66
67         return token
68