blob: 60fd2902265ad0aa3ed33ce512e4bd894e6fcb59 [file] [log] [blame]
Siobhan Tully53437282013-04-26 19:30:27 -04001import os
2import datetime
Scott Baker7ca05ab2014-12-19 13:02:31 -08003import sys
Tony Mack2f5be422015-01-03 14:26:15 -05004import hashlib
Tony Mackc14de8f2013-05-09 21:44:17 -04005from collections import defaultdict
Scott Baker301eee32014-12-19 12:22:51 -08006from django.forms.models import model_to_dict
Siobhan Tully53437282013-04-26 19:30:27 -04007from django.db import models
Tony Mack5b061472014-02-04 07:57:10 -05008from django.db.models import F, Q
Scott Bakerdaca8162015-02-02 14:28:35 -08009from django.utils import timezone
Scott Bakercbfb6002014-10-03 00:32:37 -070010from core.models import PlCoreBase,Site, DashboardView, DiffModelMixIn
Siobhan Tully30fd4292013-05-10 08:59:56 -040011from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
Scott Baker9266e6b2013-05-19 15:54:48 -070012from timezones.fields import TimeZoneField
Scott Baker2c3cb642014-05-19 17:55:56 -070013from operator import itemgetter, attrgetter
Scott Bakera36d77e2014-08-29 11:43:23 -070014from django.core.mail import EmailMultiAlternatives
15from core.middleware import get_request
Sapan Bhatiabad67742014-09-04 00:39:19 -040016import model_policy
Scott Bakercbfb6002014-10-03 00:32:37 -070017from django.core.exceptions import PermissionDenied
Siobhan Tully53437282013-04-26 19:30:27 -040018
Scott Bakerfd8c7c42014-10-09 16:16:02 -070019# ------ from plcorebase.py ------
20try:
21 # This is a no-op if observer_disabled is set to 1 in the config file
22 from observer import *
23except:
24 print >> sys.stderr, "import of observer failed! printing traceback and disabling observer:"
25 import traceback
26 traceback.print_exc()
27
28 # guard against something failing
29 def notify_observer(*args, **kwargs):
30 pass
31# ------ ------
32
Siobhan Tully53437282013-04-26 19:30:27 -040033# Create your models here.
Siobhan Tully30fd4292013-05-10 08:59:56 -040034class UserManager(BaseUserManager):
Siobhan Tully53437282013-04-26 19:30:27 -040035 def create_user(self, email, firstname, lastname, password=None):
36 """
37 Creates and saves a User with the given email, date of
38 birth and password.
39 """
40 if not email:
41 raise ValueError('Users must have an email address')
42
43 user = self.model(
Siobhan Tully30fd4292013-05-10 08:59:56 -040044 email=UserManager.normalize_email(email),
Siobhan Tully53437282013-04-26 19:30:27 -040045 firstname=firstname,
Siobhan Tully30fd4292013-05-10 08:59:56 -040046 lastname=lastname,
47 password=password
Siobhan Tully53437282013-04-26 19:30:27 -040048 )
Siobhan Tully30fd4292013-05-10 08:59:56 -040049 #user.set_password(password)
Siobhan Tully53437282013-04-26 19:30:27 -040050 user.is_admin = True
51 user.save(using=self._db)
52 return user
53
54 def create_superuser(self, email, firstname, lastname, password):
55 """
56 Creates and saves a superuser with the given email, date of
57 birth and password.
58 """
59 user = self.create_user(email,
60 password=password,
61 firstname=firstname,
62 lastname=lastname
63 )
64 user.is_admin = True
65 user.save(using=self._db)
66 return user
67
Scott Baker6c684842014-10-17 18:45:00 -070068 def get_queryset(self):
69 parent=super(UserManager, self)
70 if hasattr(parent, "get_queryset"):
71 return parent.get_queryset().filter(deleted=False)
72 else:
73 return parent.get_query_set().filter(deleted=False)
74
75 # deprecated in django 1.7 in favor of get_queryset().
76 def get_query_set(self):
77 return self.get_queryset()
78
Sapan Bhatia5d605ff2014-07-21 20:08:04 -040079class DeletedUserManager(UserManager):
Scott Bakerb08d6562014-09-12 12:57:27 -070080 def get_queryset(self):
Sapan Bhatia5d605ff2014-07-21 20:08:04 -040081 return super(UserManager, self).get_query_set().filter(deleted=True)
Siobhan Tully53437282013-04-26 19:30:27 -040082
Scott Bakerb08d6562014-09-12 12:57:27 -070083 # deprecated in django 1.7 in favor of get_queryset()
84 def get_query_set(self):
85 return self.get_queryset()
86
Scott Baker301eee32014-12-19 12:22:51 -080087class User(AbstractBaseUser): #, DiffModelMixIn):
88
89 # ---- copy stuff from DiffModelMixin ----
90
91 @property
92 def _dict(self):
93 return model_to_dict(self, fields=[field.name for field in
94 self._meta.fields])
95
Scott Bakerdaca8162015-02-02 14:28:35 -080096 def fields_differ(self,f1,f2):
97 if isinstance(f1,datetime.datetime) and isinstance(f2,datetime.datetime) and (timezone.is_aware(f1) != timezone.is_aware(f2)):
98 return True
99 else:
100 return (f1 != f2)
101
Scott Baker301eee32014-12-19 12:22:51 -0800102 @property
103 def diff(self):
104 d1 = self._initial
105 d2 = self._dict
Scott Bakerdaca8162015-02-02 14:28:35 -0800106 diffs = [(k, (v, d2[k])) for k, v in d1.items() if self.fields_differ(v,d2[k])]
Scott Baker301eee32014-12-19 12:22:51 -0800107 return dict(diffs)
108
109 @property
110 def has_changed(self):
111 return bool(self.diff)
112
113 @property
114 def changed_fields(self):
115 return self.diff.keys()
116
117 def has_field_changed(self, field_name):
118 return field_name in self.diff.keys()
119
120 def get_field_diff(self, field_name):
121 return self.diff.get(field_name, None)
Scott Baker9d896232015-01-05 17:26:36 -0800122
123 #classmethod
124 def getValidators(cls):
125 """ primarily for REST API, return a dictionary of field names mapped
126 to lists of the type of validations that need to be applied to
127 those fields.
128 """
129 validators = {}
130 for field in cls._meta.fields:
131 l = []
132 if field.blank==False:
133 l.append("notBlank")
134 if field.__class__.__name__=="URLField":
135 l.append("url")
136 validators[field.name] = l
137 return validators
Scott Baker301eee32014-12-19 12:22:51 -0800138 # ---- end copy stuff from DiffModelMixin ----
Siobhan Tully53437282013-04-26 19:30:27 -0400139
Tony Mack2f5be422015-01-03 14:26:15 -0500140 @property
141 def remote_password(self):
142 return hashlib.md5(self.password).hexdigest()[:12]
143
Siobhan Tully53437282013-04-26 19:30:27 -0400144 class Meta:
145 app_label = "core"
146
147 email = models.EmailField(
148 verbose_name='email address',
149 max_length=255,
150 unique=True,
151 db_index=True,
152 )
Siobhan Tullyfece0d52013-09-06 12:57:05 -0400153
154 username = models.CharField(max_length=255, default="Something" )
155
Siobhan Tully53437282013-04-26 19:30:27 -0400156 firstname = models.CharField(help_text="person's given name", max_length=200)
157 lastname = models.CharField(help_text="person's surname", max_length=200)
158
159 phone = models.CharField(null=True, blank=True, help_text="phone number contact", max_length=100)
160 user_url = models.URLField(null=True, blank=True)
Siobhan Tullybfd11dc2013-09-03 12:59:24 -0400161 site = models.ForeignKey(Site, related_name='users', help_text="Site this user will be homed too", null=True)
Tony Mack5cbadf82013-06-10 13:56:07 -0400162 public_key = models.TextField(null=True, blank=True, max_length=1024, help_text="Public key string")
Siobhan Tully53437282013-04-26 19:30:27 -0400163
164 is_active = models.BooleanField(default=True)
Tony Mack4bfcdc82015-01-28 12:03:39 -0500165 is_admin = models.BooleanField(default=False)
Siobhan Tully53437282013-04-26 19:30:27 -0400166 is_staff = models.BooleanField(default=True)
Siobhan Tullycf04fb62014-01-11 11:25:57 -0500167 is_readonly = models.BooleanField(default=False)
Scott Baker28e2e3a2015-01-28 16:03:40 -0800168 is_registering = models.BooleanField(default=False)
Siobhan Tully53437282013-04-26 19:30:27 -0400169
Tony Mack0553f282013-06-10 22:54:50 -0400170 created = models.DateTimeField(auto_now_add=True)
171 updated = models.DateTimeField(auto_now=True)
172 enacted = models.DateTimeField(null=True, default=None)
Sapan Bhatia103465d2015-01-23 16:02:09 +0000173 policed = models.DateTimeField(null=True, default=None)
Scott Baker85b98e72015-02-06 00:11:10 -0800174 backend_status = models.CharField(max_length=1024,
Sapan Bhatiad507f432014-04-29 00:41:39 -0400175 default="Provisioning in progress")
Sapan Bhatiabcc18992014-04-29 10:32:14 -0400176 deleted = models.BooleanField(default=False)
Tony Mack0553f282013-06-10 22:54:50 -0400177
Scott Baker9266e6b2013-05-19 15:54:48 -0700178 timezone = TimeZoneField()
179
Scott Baker2c3cb642014-05-19 17:55:56 -0700180 dashboards = models.ManyToManyField('DashboardView', through='UserDashboardView', blank=True)
181
Siobhan Tully30fd4292013-05-10 08:59:56 -0400182 objects = UserManager()
Sapan Bhatia5d605ff2014-07-21 20:08:04 -0400183 deleted_objects = DeletedUserManager()
Siobhan Tully53437282013-04-26 19:30:27 -0400184
185 USERNAME_FIELD = 'email'
186 REQUIRED_FIELDS = ['firstname', 'lastname']
187
Scott Baker0119c152014-10-06 22:58:48 -0700188 PI_FORBIDDEN_FIELDS = ["is_admin", "site", "is_staff"]
189 USER_FORBIDDEN_FIELDS = ["is_admin", "is_active", "site", "is_staff", "is_readonly"]
190
Scott Bakercbfb6002014-10-03 00:32:37 -0700191 def __init__(self, *args, **kwargs):
192 super(User, self).__init__(*args, **kwargs)
193 self._initial = self._dict # for DiffModelMixIn
194
Siobhan Tullycf04fb62014-01-11 11:25:57 -0500195 def isReadOnlyUser(self):
196 return self.is_readonly
197
Siobhan Tully53437282013-04-26 19:30:27 -0400198 def get_full_name(self):
199 # The user is identified by their email address
200 return self.email
201
202 def get_short_name(self):
203 # The user is identified by their email address
204 return self.email
205
Sapan Bhatia5d605ff2014-07-21 20:08:04 -0400206 def delete(self, *args, **kwds):
207 # so we have something to give the observer
208 purge = kwds.get('purge',False)
Scott Bakerc5b50602014-10-09 16:22:00 -0700209 if purge:
210 del kwds['purge']
Sapan Bhatia5d605ff2014-07-21 20:08:04 -0400211 try:
212 purge = purge or observer_disabled
213 except NameError:
214 pass
215
216 if (purge):
217 super(User, self).delete(*args, **kwds)
218 else:
219 self.deleted = True
220 self.enacted=None
221 self.save(update_fields=['enacted','deleted'])
222
Tony Mackb0d97422013-06-10 09:57:45 -0400223 @property
224 def keyname(self):
225 return self.email[:self.email.find('@')]
226
Siobhan Tully53437282013-04-26 19:30:27 -0400227 def __unicode__(self):
228 return self.email
229
230 def has_perm(self, perm, obj=None):
231 "Does the user have a specific permission?"
232 # Simplest possible answer: Yes, always
233 return True
234
235 def has_module_perms(self, app_label):
236 "Does the user have permissions to view the app `app_label`?"
237 # Simplest possible answer: Yes, always
238 return True
239
Siobhan Tullybfd11dc2013-09-03 12:59:24 -0400240 def is_superuser(self):
241 return False
Siobhan Tully53437282013-04-26 19:30:27 -0400242
Scott Baker2c3cb642014-05-19 17:55:56 -0700243 def get_dashboards(self):
244 DEFAULT_DASHBOARDS=["Tenant"]
245
Sapan Bhatia13d2db92014-11-11 21:47:45 -0500246 dashboards = sorted(list(self.userdashboardviews.all()), key=attrgetter('order'))
Scott Baker2c3cb642014-05-19 17:55:56 -0700247 dashboards = [x.dashboardView for x in dashboards]
248
249 if not dashboards:
250 for dashboardName in DEFAULT_DASHBOARDS:
251 dbv = DashboardView.objects.filter(name=dashboardName)
252 if dbv:
253 dashboards.append(dbv[0])
254
255 return dashboards
256
Siobhan Tullybfd11dc2013-09-03 12:59:24 -0400257# def get_roles(self):
258# from core.models.site import SitePrivilege
259# from core.models.slice import SliceMembership
260#
261# site_privileges = SitePrivilege.objects.filter(user=self)
262# slice_memberships = SliceMembership.objects.filter(user=self)
263# roles = defaultdict(list)
264# for site_privilege in site_privileges:
265# roles[site_privilege.role.role_type].append(site_privilege.site.login_base)
266# for slice_membership in slice_memberships:
267# roles[slice_membership.role.role_type].append(slice_membership.slice.name)
268# return roles
Siobhan Tully53437282013-04-26 19:30:27 -0400269
Tony Mack53106f32013-04-27 16:43:01 -0400270 def save(self, *args, **kwds):
Siobhan Tully30fd4292013-05-10 08:59:56 -0400271 if not self.id:
Scott Bakera36d77e2014-08-29 11:43:23 -0700272 self.set_password(self.password)
Scott Baker28e2e3a2015-01-28 16:03:40 -0800273 print "XXX", self, self.is_active, self.is_registering
274 if self.is_active and self.is_registering:
275 self.send_temporary_password()
276 self.is_registering=False
Scott Bakera36d77e2014-08-29 11:43:23 -0700277
Siobhan Tullyfece0d52013-09-06 12:57:05 -0400278 self.username = self.email
Scott Bakera36d77e2014-08-29 11:43:23 -0700279 super(User, self).save(*args, **kwds)
280
Scott Bakercbfb6002014-10-03 00:32:37 -0700281 self._initial = self._dict
282
Scott Bakera36d77e2014-08-29 11:43:23 -0700283 def send_temporary_password(self):
284 password = User.objects.make_random_password()
285 self.set_password(password)
286 subject, from_email, to = 'OpenCloud Account Credentials', 'support@opencloud.us', str(self.email)
287 text_content = 'This is an important message.'
Scott Baker51e7d402014-08-29 12:32:46 -0700288 userUrl="http://%s/" % get_request().get_host()
Scott Bakera36d77e2014-08-29 11:43:23 -0700289 html_content = """<p>Your account has been created on OpenCloud. Please log in <a href="""+userUrl+""">here</a> to activate your account<br><br>Username: """+self.email+"""<br>Temporary Password: """+password+"""<br>Please change your password once you successully login into the site.</p>"""
290 msg = EmailMultiAlternatives(subject,text_content, from_email, [to])
291 msg.attach_alternative(html_content, "text/html")
292 msg.send()
Tony Mack5b061472014-02-04 07:57:10 -0500293
Scott Bakercbfb6002014-10-03 00:32:37 -0700294 def can_update(self, user):
295 from core.models import SitePrivilege
Scott Baker0119c152014-10-06 22:58:48 -0700296 _cant_update_fieldName = None
Scott Bakercbfb6002014-10-03 00:32:37 -0700297 if user.is_readonly:
298 return False
299 if user.is_admin:
300 return True
Scott Bakercbfb6002014-10-03 00:32:37 -0700301 # site pis can update
302 site_privs = SitePrivilege.objects.filter(user=user, site=self.site)
303 for site_priv in site_privs:
304 if site_priv.role.role == 'pi':
Scott Baker0119c152014-10-06 22:58:48 -0700305 for fieldName in self.diff.keys():
306 if fieldName in self.PI_FORBIDDEN_FIELDS:
307 _cant_update_fieldName = fieldName
308 return False
Scott Bakercbfb6002014-10-03 00:32:37 -0700309 return True
Scott Baker0119c152014-10-06 22:58:48 -0700310 if (user.id == self.id):
311 for fieldName in self.diff.keys():
312 if fieldName in self.USER_FORBIDDEN_FIELDS:
313 _cant_update_fieldName = fieldName
314 return False
315 return True
Scott Bakercbfb6002014-10-03 00:32:37 -0700316
317 return False
318
Tony Mack5b061472014-02-04 07:57:10 -0500319 @staticmethod
320 def select_by_user(user):
321 if user.is_admin:
322 qs = User.objects.all()
323 else:
324 # can see all users at any site where this user has pi role
325 from core.models.site import SitePrivilege
326 site_privs = SitePrivilege.objects.filter(user=user)
327 sites = [sp.site for sp in site_privs if sp.role.role == 'pi']
328 # get site privs of users at these sites
329 site_privs = SitePrivilege.objects.filter(site__in=sites)
Scott Bakera36d77e2014-08-29 11:43:23 -0700330 user_ids = [sp.user.id for sp in site_privs] + [user.id]
Tony Mack5b061472014-02-04 07:57:10 -0500331 qs = User.objects.filter(Q(site__in=sites) | Q(id__in=user_ids))
Scott Bakera36d77e2014-08-29 11:43:23 -0700332 return qs
Tony Mack5b061472014-02-04 07:57:10 -0500333
Scott Bakercbfb6002014-10-03 00:32:37 -0700334 def save_by_user(self, user, *args, **kwds):
335 if not self.can_update(user):
Scott Baker0119c152014-10-06 22:58:48 -0700336 if getattr(self, "_cant_update_fieldName", None) is not None:
337 raise PermissionDenied("You do not have permission to update field %s on object %s" % (self._cant_update_fieldName, self.__class__.__name__))
338 else:
339 raise PermissionDenied("You do not have permission to update %s objects" % self.__class__.__name__)
Scott Bakercbfb6002014-10-03 00:32:37 -0700340
341 self.save(*args, **kwds)
342
343 def delete_by_user(self, user, *args, **kwds):
344 if not self.can_update(user):
345 raise PermissionDenied("You do not have permission to delete %s objects" % self.__class__.__name__)
346 self.delete(*args, **kwds)
347
Scott Baker2c3cb642014-05-19 17:55:56 -0700348class UserDashboardView(PlCoreBase):
Sapan Bhatia13d2db92014-11-11 21:47:45 -0500349 user = models.ForeignKey(User, related_name='userdashboardviews')
350 dashboardView = models.ForeignKey(DashboardView, related_name='userdashboardviews')
Scott Baker2c3cb642014-05-19 17:55:56 -0700351 order = models.IntegerField(default=0)