IdHub/idhub_auth/models.py

89 lines
2.5 KiB
Python
Raw Normal View History

2023-10-25 15:49:17 +00:00
from django.db import models
2023-12-14 16:59:40 +00:00
from django.utils.translation import gettext_lazy as _
2023-10-25 15:49:17 +00:00
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError("Users must have an email address")
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
2023-12-14 16:59:40 +00:00
_('Email address'),
2023-10-25 15:49:17 +00:00
max_length=255,
unique=True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
2023-12-14 16:59:40 +00:00
first_name = models.CharField(_("First name"), max_length=255, blank=True, null=True)
last_name = models.CharField(_("Last name"), max_length=255, blank=True, null=True)
2023-10-25 15:49:17 +00:00
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = []
def __str__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
@property
def username(self):
"Is the email of the user"
return self.email
2023-11-13 17:09:37 +00:00
def get_memberships(self):
members = set(
str(dict(x.Types.choices)[x.type]) for x in self.memberships.all()
)
return ", ".join(members)
def get_roles(self):
roles = []
for s in self.roles.all():
for r in s.service.rol.all():
roles.append(r.name)
return ", ".join(set(roles))