models.py 9.36 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

18 19
from __future__ import absolute_import

20
from itertools import chain
21
from hashlib import md5
22 23
from logging import getLogger

24
from django.conf import settings
25
from django.contrib.auth.models import User, Group
26
from django.contrib.auth.signals import user_logged_in
27
from django.core.urlresolvers import reverse
28
from django.db.models import (
29
    Model, ForeignKey, OneToOneField, CharField, IntegerField, TextField,
30
    DateTimeField, permalink, BooleanField
31
)
32
from django.db.models.signals import post_save, pre_delete
33
from django.template.loader import render_to_string
34
from django.templatetags.static import static
35
from django.utils.translation import ugettext_lazy as _, override, ugettext
36
from django_sshkey.models import UserKey
37 38 39 40

from model_utils.models import TimeStampedModel
from model_utils.fields import StatusField
from model_utils import Choices
41

42
from acl.models import AclBase
43

44 45
from vm.tasks.agent_tasks import add_keys, del_keys

46 47
logger = getLogger(__name__)

48 49
pwgen = User.objects.make_random_password

50

51
class Favourite(Model):
52
    instance = ForeignKey("vm.Instance")
53
    user = ForeignKey(User)
54 55


56 57 58 59 60 61 62 63 64
class Notification(TimeStampedModel):
    STATUS = Choices(('new', _('new')),
                     ('delivered', _('delivered')),
                     ('read', _('read')))

    status = StatusField()
    to = ForeignKey(User)
    subject = CharField(max_length=128)
    message = TextField()
65
    valid_until = DateTimeField(null=True, default=None)
66 67 68 69 70

    class Meta:
        ordering = ['-created']

    @classmethod
71
    def send(cls, user, subject, template, context={}, valid_until=None):
72 73 74 75 76 77 78
        try:
            language = user.profile.preferred_language
        except:
            language = None
        with override(language):
            context['user'] = user
            rendered = render_to_string(template, context)
79
            subject = ugettext(unicode(subject))
80 81
        return cls.objects.create(to=user, subject=subject, message=rendered,
                                  valid_until=valid_until)
82 83


84 85 86 87 88 89 90 91 92
class Profile(Model):
    user = OneToOneField(User)
    preferred_language = CharField(verbose_name=_('preferred language'),
                                   choices=settings.LANGUAGES,
                                   max_length=32,
                                   default=settings.LANGUAGE_CODE, blank=False)
    org_id = CharField(  # may be populated from eduPersonOrgId field
        unique=True, blank=True, null=True, max_length=64,
        help_text=_('Unique identifier of the person, e.g. a student number.'))
93
    instance_limit = IntegerField(default=5)
94
    use_gravatar = BooleanField(
95
        verbose_name=_("Use Gravatar"), default=True,
96
        help_text=_("Whether to use email address as Gravatar profile image"))
97 98
    email_notifications = BooleanField(
        verbose_name=_("Email notifications"), default=True,
99
        help_text=_('Whether user wants to get digested email notifications.'))
100 101 102 103 104
    smb_password = CharField(
        max_length=20,
        verbose_name=_('Samba password'),
        help_text=_(
            'Generated password for accessing store from '
105 106 107
            'Windows.'),
        default=pwgen,
    )
108 109 110 111
    disk_quota = IntegerField(
        verbose_name=_('disk quota'),
        default=2048,
        help_text=_('Disk quota in mebibytes.'))
112

113 114 115
    def notify(self, subject, template, context={}, valid_until=None):
        return Notification.send(self.user, subject, template, context,
                                 valid_until)
116

117
    def get_absolute_url(self):
Kálmán Viktor committed
118 119
        return reverse("dashboard.views.profile",
                       kwargs={'username': self.user.username})
120

121 122 123 124 125 126 127 128
    def get_avatar_url(self):
        if self.use_gravatar:
            gravatar_hash = md5(self.user.email).hexdigest()
            return ("https://secure.gravatar.com/avatar/%s"
                    "?s=200" % gravatar_hash)
        else:
            return static("dashboard/img/avatar.png")

129 130 131 132 133 134 135 136 137 138 139 140 141
    def get_display_name(self):
        if self.user.get_full_name():
            name = self.user.get_full_name()
        else:
            name = self.user.username

        if self.org_id:
            name = "%s (%s)" % (name, self.org_id)
        return name

    def __unicode__(self):
        return self.get_display_name()

Őry Máté committed
142

143 144 145 146 147 148 149 150 151 152
class GroupProfile(AclBase):
    ACL_LEVELS = (
        ('operator', _('operator')),
        ('owner', _('owner')),
    )

    group = OneToOneField(Group)
    org_id = CharField(
        unique=True, blank=True, null=True, max_length=64,
        help_text=_('Unique identifier of the group at the organization.'))
153 154 155 156 157 158
    description = TextField(blank=True)

    def save(self, *args, **kwargs):
        if not self.org_id:
            self.org_id = None
        super(GroupProfile, self).save(*args, **kwargs)
159 160 161 162 163 164 165 166

    @classmethod
    def search(cls, name):
        try:
            return cls.objects.get(org_id=name).group
        except cls.DoesNotExist:
            return Group.objects.get(name=name)

167 168 169 170 171
    @permalink
    def get_absolute_url(self):
        return ('dashboard.views.group-detail', None,
                {'pk': self.group.pk})

172 173

def get_or_create_profile(self):
174
    obj, created = GroupProfile.objects.get_or_create(group_id=self.pk)
175 176 177 178 179
    return obj

Group.profile = property(get_or_create_profile)


180
def create_profile(sender, user, request, **kwargs):
181 182
    if not user.pk:
        return False
183 184 185 186 187
    profile, created = Profile.objects.get_or_create(user=user)
    return created

user_logged_in.connect(create_profile)

188
if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'):
189
    logger.debug("Register save_org_id to djangosaml2 pre_user_save")
190 191
    from djangosaml2.signals import pre_user_save

192
    def save_org_id(sender, **kwargs):
193
        logger.debug("save_org_id called by %s", sender.username)
194
        attributes = kwargs.pop('attributes')
195
        atr = settings.SAML_ORG_ID_ATTRIBUTE
196 197 198 199 200 201
        try:
            value = attributes[atr][0]
        except Exception as e:
            value = None
            logger.info("save_org_id couldn't find attribute. %s", unicode(e))

202 203 204 205
        if sender.pk is None:
            sender.save()
            logger.debug("save_org_id saved user %s", unicode(sender))

206 207
        profile, created = Profile.objects.get_or_create(user=sender)
        if created or profile.org_id != value:
208 209
            logger.info("org_id of %s added to user %s's profile",
                        value, sender.username)
210 211
            profile.org_id = value
            profile.save()
212 213 214
        else:
            logger.debug("org_id of %s already added to user %s's profile",
                         value, sender.username)
215
        memberatrs = getattr(settings, 'SAML_GROUP_ATTRIBUTES', [])
216 217
        for group in chain(*[attributes[i]
                             for i in memberatrs if i in attributes]):
218 219 220 221 222 223 224 225 226 227
            try:
                g = GroupProfile.search(group)
            except Group.DoesNotExist:
                logger.debug('cant find membergroup %s', group)
            else:
                logger.debug('could find membergroup %s (%s)',
                             group, unicode(g))
                g.user_set.add(sender)

        owneratrs = getattr(settings, 'SAML_GROUP_OWNER_ATTRIBUTES', [])
228 229
        for group in chain(*[attributes[i]
                             for i in owneratrs if i in attributes]):
230 231 232 233 234 235 236 237 238 239
            try:
                g = GroupProfile.search(group)
            except Group.DoesNotExist:
                logger.debug('cant find ownergroup %s', group)
            else:
                logger.debug('could find ownergroup %s (%s)',
                             group, unicode(g))
                g.profile.set_level(sender, 'owner')

        return False  # User did not change
240

241 242
    pre_user_save.connect(save_org_id)

243 244
else:
    logger.debug("Do not register save_org_id to djangosaml2 pre_user_save")
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274


def add_ssh_keys(sender, **kwargs):
    from vm.models import Instance

    userkey = kwargs.get('instance')
    instances = Instance.get_objects_with_level(
        'user', userkey.user).filter(status='RUNNING')
    for i in instances:
        logger.info('called add_keys(%s, %s)', i, userkey)
        queue = i.get_remote_queue_name("agent")
        add_keys.apply_async(args=(i.vm_name, [userkey.key]),
                             queue=queue)


def del_ssh_keys(sender, **kwargs):
    from vm.models import Instance

    userkey = kwargs.get('instance')
    instances = Instance.get_objects_with_level(
        'user', userkey.user).filter(status='RUNNING')
    for i in instances:
        logger.info('called del_keys(%s, %s)', i, userkey)
        queue = i.get_remote_queue_name("agent")
        del_keys.apply_async(args=(i.vm_name, [userkey.key]),
                             queue=queue)


post_save.connect(add_ssh_keys, sender=UserKey)
pre_delete.connect(del_ssh_keys, sender=UserKey)