~devcamcar/horizon/trunk

« back to all changes in this revision

Viewing changes to django-openstack/src/django_openstack/models.py

  • Committer: Devin Carlen
  • Date: 2011-06-18 05:59:37 UTC
  • Revision ID: devin.carlen@gmail.com-20110618055937-aobwm0buvviijz3o
Moved codebase to GitHub

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# vim: tabstop=4 shiftwidth=4 softtabstop=4
2
 
 
3
 
# Copyright 2010 United States Government as represented by the
4
 
# Administrator of the National Aeronautics and Space Administration.
5
 
# All Rights Reserved.
6
 
#
7
 
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
8
 
#    not use this file except in compliance with the License. You may obtain
9
 
#    a copy of the License at
10
 
#
11
 
#         http://www.apache.org/licenses/LICENSE-2.0
12
 
#
13
 
#    Unless required by applicable law or agreed to in writing, software
14
 
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
 
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16
 
#    License for the specific language governing permissions and limitations
17
 
#    under the License.
18
 
"""
19
 
Database models for authorization credentials and synchronizing Nova users.
20
 
"""
21
 
 
22
 
import datetime
23
 
import random
24
 
import re
25
 
import sha
26
 
from django.conf import settings
27
 
from django.contrib.auth import models as auth_models
28
 
from django.contrib.sites import models as site_models
29
 
from django.core import mail
30
 
from django.db import models
31
 
from django.db.models.signals import post_save
32
 
from django.template.loader import render_to_string
33
 
from django_openstack import log as logging
34
 
from django_openstack.core import connection
35
 
from django_openstack import utils
36
 
 
37
 
 
38
 
LOG = logging.getLogger('django_openstack')
39
 
 
40
 
 
41
 
SHA1_RE = re.compile('^[a-f0-9]{40}$')
42
 
 
43
 
 
44
 
class CredentialsAuthorization(models.Model):
45
 
    username = models.CharField(max_length=128)
46
 
    project = models.CharField(max_length=128)
47
 
    auth_token = models.CharField(max_length=40)
48
 
    auth_date = models.DateTimeField(auto_now_add=True)
49
 
 
50
 
    def __str__(self):
51
 
        return '%s/%s:%s' % (self.username, self.project, self.auth_token)
52
 
 
53
 
    @classmethod
54
 
    def get_by_token(cls, token):
55
 
        if SHA1_RE.search(token):
56
 
            try:
57
 
                credentials = cls.objects.get(auth_token=token)
58
 
            except cls.DoesNotExist:
59
 
                return None
60
 
            if not credentials.auth_token_expired():
61
 
                return credentials
62
 
        return None
63
 
 
64
 
    @classmethod
65
 
    def authorize(cls, username, project):
66
 
        return cls.objects.create(username=username,
67
 
                                  project=project,
68
 
                                  auth_token=cls.create_auth_token(username))
69
 
 
70
 
    @staticmethod
71
 
    def create_auth_token(username):
72
 
        salt = sha.new(str(random.random())).hexdigest()[:5]
73
 
        return sha.new(salt + username).hexdigest()
74
 
 
75
 
    def auth_token_expired(self):
76
 
        expiration_date = datetime.timedelta(
77
 
                days=int(settings.CREDENTIAL_AUTHORIZATION_DAYS))
78
 
 
79
 
        return self.auth_date + expiration_date <= utils.utcnow()
80
 
 
81
 
    def get_download_url(self):
82
 
        return settings.CREDENTIAL_DOWNLOAD_URL + self.auth_token
83
 
 
84
 
    def get_zip(self):
85
 
        nova = connection.get_nova_admin_connection()
86
 
        self.delete()
87
 
        return nova.get_zip(self.username, self.project)
88
 
 
89
 
 
90
 
def credentials_post_save(sender, instance, created, *args, **kwargs):
91
 
    """
92
 
    Creates a Nova User when a new Django User is created.
93
 
    """
94
 
    if created:
95
 
        site = site_models.Site.objects.get_current()
96
 
        user = auth_models.User.objects.get(username=instance.username)
97
 
        context = {
98
 
            'user': user,
99
 
            'download_url': instance.get_download_url(),
100
 
            'dashboard_url': 'http://%s/' % site.domain
101
 
        }
102
 
        subject = render_to_string('credentials/credentials_email_subject.txt')
103
 
        body = render_to_string('credentials/credentials_email.txt', context)
104
 
 
105
 
        message = mail.EmailMessage(subject=subject.strip(),
106
 
                                    body=body,
107
 
                                    to=[user.email])
108
 
        message.send(fail_silently=False)
109
 
        LOG.info('Credentials sent to user "%s" at "%s"' %
110
 
                 (instance.name, user.email))
111
 
post_save.connect(credentials_post_save,
112
 
                  CredentialsAuthorization,
113
 
                  dispatch_uid='django_openstack.CredentialsAuthorization.post_save')
114
 
 
115
 
 
116
 
def user_post_save(sender, instance, created, *args, **kwargs):
117
 
    """
118
 
    Creates a Nova User when a new Django User is created.
119
 
    """
120
 
 
121
 
    # NOTE(devcamcar): If running unit tests, don't use a real endpoint.
122
 
    if settings.NOVA_DEFAULT_ENDPOINT is None:
123
 
        return
124
 
 
125
 
    if created:
126
 
        nova = connection.get_nova_admin_connection()
127
 
        if not nova.has_user(instance.username):
128
 
            nova.create_user(instance.username)
129
 
            LOG.info('User "%s" created in Nova' % instance.username)
130
 
post_save.connect(user_post_save,
131
 
                  auth_models.User,
132
 
                  dispatch_uid='django_openstack.User.post_save')