def forgot_password_email(request): if request.method == 'POST': try: u = User.objects.get(username=request.POST['username']) userProfile = UserProfile.objects.get(user = u) except ObjectDoesNotExist: u = None if u is not None: bum = BaseUserManager() tempPass = bum.make_random_password() u.set_password(tempPass) userProfile.hasTempPassword = True userProfile.save() u.save() subject = 'AC3 Forgotten Password Request' message = 'User: {0}\n You have requested to reset your password\nYour temporary password is: {1}' \ ''.format(u.username, tempPass) EmailMessage(subject, message, to=[u.email]).send(fail_silently=True) messages.add_message(request, messages.SUCCESS, 'An email has been sent!') return HttpResponseRedirect('/ac3app/') else: messages.add_message(request, messages.ERROR, 'The user {0} could not be found' .format(request.POST['username'])) return HttpResponseRedirect('/ac3app/')
def post(self, request, *args, **kwargs): email = request.POST.get("email", "0") firstname = request.POST.get("firstname", "0") lastname = request.POST.get("lastname", "0") site = request.POST.get("site", "0") # see if it already exists user = User.objects.filter( email=BaseUserManager.normalize_email(email)) if (user): user = user[0] if user.is_active: # force a new email to be sent user.is_registering = True user.save() return HttpResponse(json.dumps({"error": "already_approved"}), content_type='application/javascript') else: return HttpResponse(json.dumps({"error": "already_pending"}), content_type='application/javascript') user = User.deleted_objects.filter( email=BaseUserManager.normalize_email(email)) if (user): return HttpResponse(json.dumps({"error": "is_deleted"}), content_type='application/javascript') user = User(email=BaseUserManager.normalize_email(email), firstname=firstname, lastname=lastname, is_active=False, is_admin=False, is_registering=True) user.save() user.site = Site.objects.get(name=site) user.save(update_fields=['site']) sitePriv = SitePrivilege.objects.filter(site=user.site) userId = user.id userUrl = "http://" + request.get_host() + "/admin/core/user/" + str( userId) for sp in sitePriv: subject, from_email, to = 'Authorize OpenCloud User Account', '*****@*****.**', str( sp.user) text_content = 'This is an important message.' html_content = """<p>Please authorize the following user on site """ + site + """: <br><br>User: """ + firstname + """ """ + lastname + """<br>Email: """ + email + """<br><br> Check the checkbox next to Is Active property at <a href=""" + userUrl + """> this link</a> to authorize the user, and then click the Save button. If you do not recognize this individual, or otherwise do not want to approve this account, please ignore this email. If you do not approve this request in 48 hours, the account will automatically be deleted.</p>""" msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return HttpResponse(serializers.serialize("json", [ user, ]), content_type='application/javascript')
def create(self, validated_data): abc = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789' user = super(UserSerializer, self).create(validated_data) user.email = self.validated_data['email'] password = BaseUserManager().make_random_password(length=5, allowed_chars=abc) user.password = BaseUserManager(). \ make_random_password(length=5, allowed_chars=abc) user.set_password(password) if user.role == 'moderator': user.is_staff = True elif user.role == 'admin': user.is_admin = True user.save() return user
class StoreItem(models.Model): """Represents an item of a Store""" store_user = models.ForeignKey(StoreUserProfile, on_delete=models.SET_NULL, null=True, related_name='store_items') item_id = models.CharField(max_length=255, primary_key=True, default=uuid.uuid4()) item_name = models.CharField(max_length=30, blank=False, default="") price = models.IntegerField(null=False, default=0) popularity = models.IntegerField(null=False, default=0) created_on = models.DateTimeField(auto_now_add=True, null=True) objects = BaseUserManager() def ___str___(self): """Returns the model as a string""" return self.item_name def get(self): """Returns the model as a json object""" object = { 'item_name': self.item_name, 'price': self.price, 'popularity': self.popularity, 'created_on': self.created_on.strftime('%m%d%H') } return object
class User(AbstractUser): # history = HistoricalRecords() # done in translation.py username_validator = UsernameValidator() username = models.CharField( _("username"), primary_key=True, # max_length=150, max_length=20, unique=True, # help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), help_text=_("Required. 20 characters or fewer. Letters, digits and _ only."), validators=[username_validator], error_messages={"unique": _("A user with that username already exists.")}, ) # MANAGERS objects = BaseUserManager() public_objects = PublicUserManager() class Meta(AbstractUser.Meta): ordering = ["-date_joined"] def get_absolute_url(self): return reverse("accounts:profile") def get_avatar_url(self): try: return self.socialaccount_set.all()[0].get_avatar_url() except: return None
def save(self, commit=True): print(" === save === ") user = super(RegisterForm, self).save(commit=False) user.email = BaseUserManager.normalize_email(self.cleaned_data["email"]) if commit: user.save() return user
def create_user(self, email, password, first_name, last_name, has_set_password=True, **extra_fields): """Creates and saves a User with the given email and password. Arguments: email {str} -- username password {str} -- forreals **extra_fields {dict} -- Other user model fields that can be passed in to set the user Keyword Arguments: Returns: User -- user instance """ now = timezone.now() email = BaseUserManager.normalize_email(email.lower()) user = self.model(email=email, first_name=first_name, last_name=last_name, is_staff=False, is_active=True, is_superuser=False, is_new=True, has_set_password=has_set_password, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save() return user
def register(self, request, **cleaned_data): User = compat.get_user_model() if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) user_fields = {} # keep non password fields for field in compat.get_registration_fields(): if not field.startswith('password'): user_fields[field] = cleaned_data[field] if field == 'email': user_fields[field] = BaseUserManager.normalize_email(user_fields[field]) new_user = User(is_active=False, **user_fields) new_user.clean() new_user.set_password(cleaned_data['password1']) new_user.save() attributes = models.Attribute.objects.filter( asked_on_registration=True) if attributes: for attribute in attributes: attribute.set_value(new_user, cleaned_data[attribute.name]) registration_profile = RegistrationProfile.objects.create_profile(new_user) registration_profile.send_activation_email(site) signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
class BaseUser(AbstractBaseUser): user_id = models.AutoField(primary_key=True) # Displayed as Institution Name for Administrators username = models.CharField(max_length=255, unique=True, null=False) email = models.EmailField(max_length=255, unique=True, null=False) mobile_number = models.CharField(max_length=40, unique=True, null=True) landline_number = models.CharField(max_length=40, unique=True, null=True) is_admin = models.BooleanField(default=False) slug = models.SlugField(unique=True) objects = BaseUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def get_full_name(self): return self.email def get_short_name(self): return self.username def get_profile(self): return reverse('users:detail', kwargs={'slug': self.slug}) def __str__(self): return self.email
def login(request): if request.method == 'GET': user = request.user if user.is_authenticated(): if user.is_superuser: return HttpResponseRedirect(reverse('basketball:commissioner-dashboard')) else: return HttpResponseRedirect(reverse('basketball:edit-player-info', args=[user.player.pk])) redirect_next = request.GET.get('next', reverse('basketball:leagues')) context = {'error': False, 'next': redirect_next} elif request.method == 'POST': username = request.POST.get('username', '') password = request.POST.get('password', '') try: username = User.objects.get(email=BaseUserManager.normalize_email(username)).get_username except User.DoesNotExist: pass user = authenticate(username=username, password=password) if user is not None: auth_login(request, user) redirect_next = request.POST.get('next') if not redirect_next: redirect_next = reverse('basketball:leagues') return HttpResponseRedirect(redirect_next) else: context = {'error': True} return render(request, 'basketball/login.html', context)
class Customer(AbstractBaseUser): USERNAME_FIELD = 'email' id = models.TextField( primary_key=True, default=_default_id ) email = models.EmailField(unique=True) first_name = models.TextField() last_name = models.TextField() gender = models.CharField(max_length=1) country_code = models.CharField(max_length=3) objects = BaseUserManager() def as_dict(self): return { 'id': self.id, 'email': self.email, 'first_name': self.first_name, 'last_name': self.last_name, 'gender': self.gender, 'country_code': self.country_code }
def create_user(self, email, password=None): now = timezone.now() email = BaseUserManager.normalize_email(email) user = self.model(email=email, last_login=now) user.set_password(password) user.save(using=self._db) return user
class User(AbstractBaseUser): username = models.SlugField(primary_key=True) name = models.CharField(max_length=255) email = models.EmailField( verbose_name="email address", max_length=255, unique=True, ) organisation = models.ForeignKey("Organisation", on_delete=models.CASCADE, related_name="users") is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = BaseUserManager() USERNAME_FIELD = "username" def save(self, *args, **kwargs): self.username = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.username @property def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True
class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True, error_messages={ 'unique': _("A user with that email already exists."), }) USERNAME_FIELD = 'email' objects = BaseUserManager() def __str__(self): return self.email is_staff = models.BooleanField( _('staff status'), default=True, help_text=_( 'Designates whether the user can log into this admin site.')) def get_full_name(self): return self.email def get_short_name(self): return self.email
class User(AbstractBaseUser, PermissionsMixin): USERNAME_FIELD = 'username' account = m.ForeignKey('Account', related_name="users", null=False) username = CharField255(unique=True, db_index=True) email = m.EmailField(max_length=255, unique=True, db_index=True) unread_events_count = m.IntegerField(null=False, default=0) # indicates if user has complete signup process # and can be logged into the app. is_signup_complete = m.BooleanField(null=False, default=False) # admin related fields is_staff = m.BooleanField(default=False) is_active = m.BooleanField(default=True) objects = BaseUserManager() def get_full_name(self): return self.username # for admin site purposes def get_short_name(self): return self.username
class BaseUser(AbstractUser): email = models.EmailField(max_length=255, unique=True, null=False) objects = BaseUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS def get_full_name(self): return '{}, {}'.format(self.last_name, self.first_name) def get_short_name(self): return self.username def set_username(self): instances = BaseUser.objects.filter(first_name=self.first_name, last_name=self.last_name).count() # print("There are {} instances of '{} {}'".format(instances, self.first_name, self.last_name)) if instances: # print("Appending '-{}' to new_user's username".format(instances+1)) self.username = '******'.format(self.first_name, self.last_name, instances + 1) else: self.username = '******'.format(self.first_name, self.last_name) # print('Username of {} {}: {}'.format(self.first_name, self.last_name, self.username)) self.save() def __str__(self): return self.email
class Profile(AbstractUser): user_role = models.SmallIntegerField(choices=MAP_ROLES, null=True, blank=True) slug = AutoSlugField(unique=True, populate_from='full_name') about_me = models.TextField(blank=True) created_datetime = models.DateTimeField(auto_now_add=True) updated_datetime = models.DateTimeField(auto_now=True) objects = BaseUserManager() shortcuts = ProfileManager() @property def is_author(self): return self.user_role == 1 @property def is_editor(self): return self.user_role == 2 @property def is_administrator(self): return self.user_role == 3 @property def full_name(self): return self.get_full_name() @models.permalink def get_absolute_url(self): return ('author_detail', [str(self.slug)]) def __unicode__(self): return self.full_name
def validate_email(self, value): if not value: raise CustomValidation('-1', "이메일주소를 입력하세요.") user = get_user_model().objects.filter(email=value) if user: raise CustomValidation('-5', "이미 등록된 이메일주소입니다.") return BaseUserManager.normalize_email(value)
class User(AbstractBaseUser): """ User object for our app """ email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) date_of_birth = models.DateField() reliability = models.FloatField(default=0.0) country = models.CharField(max_length=255) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) display_name = models.CharField(max_length=255) avatar = models.ImageField(upload_to="avatars", null=True) bookmarks = models.ManyToManyField(Content) upvotes = models.ManyToManyField(Rating, related_name="upvote_users") downvotes = models.ManyToManyField(Rating, related_name="downvote_users") objects = BaseUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'date_of_birth', 'first_name', 'last_name', 'display_name' ]
def signup(request): if request.method == "POST": logger.info("Processing signup request...") uform = UserForm(request.POST, instance=User()) pform = UserprofileForm(request.POST, instance=Userprofile()) logger.info("New signup request.") if uform.is_valid() and pform.is_valid(): email = BaseUserManager.normalize_email(uform.cleaned_data['email']) djangouser = User.objects.create_user(uform.cleaned_data['username'], email, uform.cleaned_data['password']) logger.debug("User created in database as " + djangouser.username) djangouser.last_name = uform.cleaned_data['last_name'] djangouser.first_name = uform.cleaned_data['first_name'] djangouser._dateofbirth = pform.cleaned_data['dateofbirth'] djangouser._gender = pform.cleaned_data['gender'] djangouser._height = pform.cleaned_data['height'] djangouser._weight = pform.cleaned_data['weight'] if pform.cleaned_data['notes']: djangouser._notes = pform.cleaned_data['notes'] else: djangouser._notes = '' logger.debug("Signup request processed with the following info:" + "\n\t Username: "******"\n\t Email: " + djangouser.email + "\n\t First Name: " + djangouser.first_name + "\n\t Last Name: " + djangouser.last_name + "\n\t Date of Birth: " + str(djangouser._dateofbirth) + "\n\t Gender: " + djangouser._gender + "\n\t Height: " + str(djangouser._height) + "\n\t Weight: " + str(djangouser._weight) + "\n\t Notes: " + djangouser._notes ) logger.debug("Sending 'user_initiated' signal...") signals.user_initiated.send(sender=None, instance=djangouser, dateofbirth=djangouser._dateofbirth, gender=djangouser._gender, height=djangouser._height, weight=djangouser._weight, notes=djangouser._notes) djangouser.save() logger.debug("User creation successful.") return HttpResponseRedirect('..') else: logger.info("Loading signup page...") uform = UserForm(instance=User()) pform = UserprofileForm(instance=Userprofile()) return render(request, 'healthtracker/signup.html', {'user_form':uform, 'userprofile_form':pform} )
class UserManager(BaseUserManager.from_queryset(UsersQuerySet)): use_for_related_fields = True def _create_user(self, username: str, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() email = self.normalize_email(email) user = self.model(username=username, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username: str, email=None, password=None, **extra_fields): return self._create_user(username, email, password, False, False, **extra_fields) def create_superuser(self, username: str, email, password, **extra_fields): return self._create_user(username, email, password, True, True, **extra_fields)
class UserManager(BaseUserManager.from_queryset(UserQuerySet)): def create_user(self, serial, password=None, **extra): if not serial: raise ValueError('Users must have a serial') user = self.model(serial=serial, **extra) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, serial, password, **extra): user = self.create_user(serial=serial, password=password, **extra) user.is_staff = True user.save(using=self._db) return user def get_queryset(self): return super().get_queryset().exclude(serial='__system__') def get_queryset_unfiltered(self): # Use the parent's queryset, as it is not filtered return super().get_queryset() def get_system_user(self): return self.get_queryset_unfiltered().get(serial='__system__')
def signup(self, request): serializer = SignUpSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) email = serializer.data['email'] password = serializer.data['password'] username = serializer.data['username'] department_id = serializer.data['department'] email = BaseUserManager.normalize_email(email) user = UserService.get_user_by_username_or_email(email) if user: return Response({'error': "Email has been used"}, status=status.HTTP_401_UNAUTHORIZED) now = timezone.now() user = User.objects.create(email=email, username=username, is_staff=False, is_superuser=False, is_active=True, last_login=now, date_joined=now) user.set_password(password) profile = UserProfile.objects.create(user=user) if department_id: depart = Department.objects.get(id=department_id) profile.department = depart user.save() profile.save() return Response({'message': 'Create user successfully'}, status=status.HTTP_200_OK)
def validate_email(self, value): value = value.lower().strip() value = BaseUserManager.normalize_email(value) if User.objects.filter(email=value).exists(): raise serializers.ValidationError( {'detail': "Email already exists."}) return value
def create_superuser(self, username, email, password, **extra_fields): email = BaseUserManager.normalize_email(email) user = self.model(username=username, email=email, is_staff=True, is_active=True, is_superuser=True) user.set_password(password) user.save(using=self._db) return user
class CustomUser(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, default='user') active = models.BooleanField(default=True) quiz_creator = models.BooleanField(default=False) USERNAME_FIELD = 'username' objects = BaseUserManager() def create_user(username, password): user = CustomUser(username=username, password=password) user.set_password(password) try: user.save() return user except (ValueError, IntegrityError): return None def __str__(self): return f'Username: {self.username};\n Is_quiz_creator: {self.quiz_creator};' @property def get_username(self): return self.username @property def is_quiz_creator(self): return self.quiz_creator @property def is_active(self): return self.active
def create_user(self, email, password): user = User(email=BaseUserManager.normalize_email(email), ) user.set_password(password) user.save(using=self._db) Token.objects.create(user=user) return user
class UserManager(BaseUserManager.from_queryset(UserQueryset)): """Custom manager for User. """ def _create_user(self, email, password, **extra_fields): """Create and save an EmailUser with the given email and password. :param str email: user email :param str password: user password :param bool is_staff: whether user staff or not :param bool is_superuser: whether user admin or not :return custom_user.models.EmailUser user: user :raise ValueError: email is not set """ now = timezone.now() if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) last_login = extra_fields.pop('last_login', now) date_joined = extra_fields.pop('date_joined', now) user = self.model( email=email, last_login=last_login, date_joined=date_joined, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save an EmailUser with the given email and password. :param str email: user email :param str password: user password :return custom_user.models.EmailUser user: regular user """ return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save an EmailUser with the given email and password. :param str email: user email :param str password: user password :return custom_user.models.EmailUser user: admin user """ return self._create_user( email, password, verified=True, is_staff=True, is_superuser=True, **extra_fields ) def get_with_verification_key(self, verification_key): """Get a user from verification key. """ try: username = signing.loads( verification_key, salt=settings.SECRET_KEY, ) except signing.BadSignature: raise self.model.DoesNotExist return self.get(**{self.model.USERNAME_FIELD: username})
def create_user(self, email=None, password=None, **extra_fields): if not email: raise ValueError('No email!') email = BaseUserManager.normalize_email(email) user = self.model(email=email, is_superuser=False, **extra_fields) user.set_password(password) user.save(using=self._db) return user
class MyUser(AbstractBaseUser): USERNAME_FIELD = 'my_username' my_username = models.CharField(max_length=30) objects = BaseUserManager() class Meta: abstract = False
def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model(email=BaseUserManager.normalize_email(email), username=username, date_of_birth=datetime.date(1981,12,29)) user.set_password(password) user.save(using=self._db) return user
class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) custom_objects = BaseUserManager() USERNAME_FIELD = 'email' class Meta: app_label = 'test_client_regress'
def validate_email(self, value): email = BaseUserManager.normalize_email(value) if UserModel.objects.filter(email=email).exists(): raise serializers.ValidationError( "A user with that email already exists.") return email
def create_user(self, email, password=None): if not email: raise ValueError('メールアドレスの登録が必須です') user = self.model(email=BaseUserManager.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user
class AppUser(AbstractBaseUser): email = models.EmailField(unique=True) password = models.CharField(max_length=15) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [email, password] objects = BaseUserManager()
def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model(email=BaseUserManager.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user
def create_user(self, email, is_admin=False): """Creates a new user based on the hash of the email address.""" email = BaseUserManager.normalize_email() user_id = email_hash(email) user = self.model(user=user_id, is_admin=is_admin) user.password_notify(new=True) user.save(using=self._db) return user
def post(self, request, *args, **kwargs): email = request.POST.get("email", "0") firstname = request.POST.get("firstname", "0") lastname = request.POST.get("lastname", "0") site = request.POST.get("site","0") # see if it already exists user=User.objects.filter(email=BaseUserManager.normalize_email(email)) if (user): user = user[0] if user.is_active: # force a new email to be sent user.is_registering=True user.save() return HttpResponse(json.dumps({"error": "already_approved"}), content_type='application/javascript') else: return HttpResponse(json.dumps({"error": "already_pending"}), content_type='application/javascript') user=User.deleted_objects.filter(email=BaseUserManager.normalize_email(email)) if (user): return HttpResponse(json.dumps({"error": "is_deleted"}), content_type='application/javascript') user = User( email=BaseUserManager.normalize_email(email), firstname=firstname, lastname=lastname, is_active=False, is_admin=False, is_registering=True ) user.save() user.site=Site.objects.get(name=site) user.save(update_fields=['site']) sitePriv = SitePrivilege.objects.filter(site=user.site) userId = user.id userUrl = "http://"+request.get_host()+"/admin/core/user/"+str(userId) for sp in sitePriv: subject, from_email, to = 'Authorize OpenCloud User Account', '*****@*****.**', str(sp.user) text_content = 'This is an important message.' html_content = """<p>Please authorize the following user on site """+site+""": <br><br>User: """+firstname+""" """+lastname+"""<br>Email: """+email+"""<br><br> Check the checkbox next to Is Active property at <a href="""+userUrl+"""> this link</a> to authorize the user, and then click the Save button. If you do not recognize this individual, or otherwise do not want to approve this account, please ignore this email. If you do not approve this request in 48 hours, the account will automatically be deleted.</p>""" msg = EmailMultiAlternatives(subject,text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return HttpResponse(serializers.serialize("json",[user,]), content_type='application/javascript')
def create_account(self, email, password=None, **extra_fields): now = timezone.now() if not email: raise ValueError('The given email must be set') email = BaseUserManager.normalize_email(email) account = self.model(email=email, last_login=now, **extra_fields) account.set_password(password) account.save(using=self._db) return account
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError("El email es obligatorio") email = BaseUserManager.normalize_email(email) user = self.model(username=username, email=email, is_active=True, is_staff=is_staff,is_superuser=is_superuser, **extra_fields) user.set_password(password) user.save(using=self._db) return user
def create_user(self, username, email=None, password=None, **extra_fields): """ Creates and saves a User with the given username, email and password. """ email = BaseUserManager.normalize_email(email) user = self.model(username=username, email=email, is_staff=False, is_active=True, is_superuser=False) user.set_password(password) user.save(using=self._db) return user
def create_user(self, email, password=None, **extra_fields): now = timezone.now() if not email: raise ValueError('The given email must be set') email = BaseUserManager.normalize_email(email) validate_email(email) user = self.model(email=email, is_staff=False, is_active=True, is_superuser=False, joined=now, updated=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user
def create_user(self, username, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( username=username, email=BaseUserManager.normalize_email(email), ) user.set_password(password) user.save() return user
def process_request(self, request): django_user = get_user(request) google_user = users.get_current_user() # Check to see if the user is authenticated with a different backend, if so, just set # request.user and bail if django_user.is_authenticated(): backend_str = request.session.get(BACKEND_SESSION_KEY) if (not backend_str) or not isinstance(load_backend(backend_str), BaseAppEngineUserAPIBackend): request.user = django_user return if django_user.is_anonymous() and google_user: # If there is a google user, but we are anonymous, log in! # Note that if DJANGAE_FORCE_USER_PRE_CREATION is True then this may not authenticate django_user = authenticate(google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) if django_user.is_authenticated(): if not google_user: # If we are logged in with django, but not longer logged in with Google # then log out logout(request) django_user = AnonymousUser() elif django_user.username != google_user.user_id(): # If the Google user changed, we need to log in with the new one logout(request) django_user = authenticate(google_user=google_user) or AnonymousUser() if django_user.is_authenticated(): login(request, django_user) # Note that the logic above may have logged us out, hence new `if` statement if django_user.is_authenticated(): # Now make sure we update is_superuser and is_staff appropriately is_superuser = users.is_current_user_admin() google_email = BaseUserManager.normalize_email(google_user.email()) resave = False if is_superuser != django_user.is_superuser: django_user.is_superuser = django_user.is_staff = is_superuser resave = True # for users which already exist, we want to verify that their email is still correct if django_user.email != google_email: django_user.email = google_email resave = True if resave: django_user.save() request.user = django_user
def clean_email(self): if self.cleaned_data.get('email'): email = self.cleaned_data['email'] if app_settings.A2_REGISTRATION_EMAIL_IS_UNIQUE: User = get_user_model() try: User.get(email__iexact=email) except User.DoesNotExist: pass else: raise ValidationError(_('This email address is already in ' 'use. Please supply a different email address.')) return BaseUserManager.normalize_email(email)
def create_user(self, email, password=None, **extra_fields): """ Creates and saves a User with the given email and password. """ now = timezone.now() if not email: raise ValueError('Users must have an email address') email = BaseUserManager.normalize_email(email) user = self.model(email=email, is_staff=False, is_active=True, is_superuser=False, last_login=now, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user
def authenticate(self, **credentials): """ Handles authentication of a user from the given credentials. Credentials must be a combination of 'request' and 'google_user'. If any other combination of credentials are given then we raise a TypeError, see authenticate() in django.contrib.auth.__init__.py. """ User = get_user_model() if not issubclass(User, GaeAbstractBaseUser): raise ImproperlyConfigured( "djangae.contrib.auth.backends.AppEngineUserAPI requires AUTH_USER_MODEL to be a " " subclass of djangae.contrib.auth.base.GaeAbstractBaseUser." ) if len(credentials) != 1: # Django expects a TypeError if this backend cannot handle the given credentials raise TypeError() google_user = credentials.get('google_user', None) if google_user: user_id = google_user.user_id() email = google_user.email().lower() try: user = User.objects.get(username=user_id) except User.DoesNotExist: if ( getattr(settings, 'DJANGAE_ALLOW_USER_PRE_CREATION', False) or # Backwards compatibility, remove before 1.0 getattr(settings, 'ALLOW_USER_PRE_CREATION', False) ): # Check to see if a User object for this email address has been pre-created. try: # Convert the pre-created User object so that the user can now login via # Google Accounts, and ONLY via Google Accounts. user = User.objects.get(email=BaseUserManager.normalize_email(email), username=None) user.username = user_id user.last_login = timezone.now() user.save() return user except User.DoesNotExist: pass user = User.objects.create_user(user_id, email) return user else: raise TypeError() # Django expects to be able to pass in whatever credentials it has, and for you to raise a TypeError if they mean nothing to you
def process_request(self, request): django_user = get_user(request) google_user = users.get_current_user() if django_user.is_anonymous() and google_user: # If there is a google user, but we are anonymous, log in! django_user = authenticate(google_user=google_user) if django_user: login(request, django_user) elif not django_user.is_anonymous() and not google_user: # If we are logged in with django, but not longer logged in with Google # then log out logout(request) django_user = None elif not django_user.is_anonymous() and django_user.username != google_user.user_id(): # If the Google user changed, we need to log in with the new one logout(request) django_user = authenticate(google_user=google_user) if django_user: login(request, django_user) request.user = django_user or AnonymousUser() backend_str = request.session.get(BACKEND_SESSION_KEY) if backend_str and google_user: backend = load_backend(backend_str) # We only do this next bit if the user was authenticated with the AppEngineUserAPI # backend, or one of its subclasses if isinstance(backend, AppEngineUserAPI): # Now make sure we update is_superuser and is_staff appropriately is_superuser = users.is_current_user_admin() google_email = BaseUserManager.normalize_email(google_user.email()) resave = False if is_superuser != django_user.is_superuser: django_user.is_superuser = django_user.is_staff = is_superuser resave = True # for users which already exist, we want to verify that their email is still correct if django_user.email != google_email: django_user.email = google_email resave = True if resave: django_user.save()
def custom_create_user(username, email=None, password=None, **extra_fields): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() if not username: raise ValueError('The given username must be set') email = BaseUserManager.normalize_email(email) user_fields = dict( username=username, email=email, is_staff=False, is_active=True, is_superuser=False, date_joined=now, ) user_fields.update(extra_fields) user = User(**user_fields) user.set_password(password) user.save() return user
def create_user(self, email, first_name, password=None): """ Creates and saves a User with the given email, first name and password. """ now = timezone.now() if not email: raise ValueError('Email must be supplied.') if not first_name: raise ValueError('First name must be set.') email = BaseUserManager.normalize_email(email) user = self.model(email=email, first_name=first_name, is_active=False, is_admin=False, last_login=now, date_joined=now) user.set_password(password) user.save(using=self._db) return user
def sync_user_data(self, django_user, google_user): # Now make sure we update is_superuser and is_staff appropriately changed_fields = [] is_superuser = users.is_current_user_admin() if is_superuser != django_user.is_superuser: django_user.is_superuser = django_user.is_staff = is_superuser changed_fields += ['is_superuser', 'is_staff'] email = BaseUserManager.normalize_email(google_user.email()) # Normalizes the domain only. if email != django_user.email: django_user.email = email changed_fields += ['email', 'email_lower'] if changed_fields: django_user.save(update_fields=changed_fields)
def create_user(self, email, name, password=None): # validación: if not email: raise ValueError('Users must have an email address') if not name: raise ValueError('Users must have a name') try: User.objects.get(email=email) raise forms.ValidationError(self.error_messages['duplicate_email']) except User.DoesNotExist: pass user = User() user.email_wtc = BaseUserManager.normalize_email(email), user.name = name if password is None: user.set_password(self.make_random_password()) else: user.set_password(password) user.is_superuser = False user.save(using=self._db)
def create_user( self, email, first_name, last_name, organization = None, job_title = None, bio = None, password = None ): """ Creates a standard user with no administrative privledges """ if not email: raise ValueError('Users must provide an email') if not first_name: raise ValueError('Users must provide a first name') if not last_name: raise ValueError('Users must provide a last name') if not organization: raise ValueError('Users must provide an email address') # Note: a biography and job_title are not required user = self.model( email=BaseUserManager.normalize_email(email), first_name=first_name, last_name=last_name, organization=organization, job_title=job_title, bio=bio ) user.set_password(password) user.save(using=self._db) return user
def process_request(self, request): django_user = get_user(request) google_user = users.get_current_user() if django_user.is_anonymous() and google_user: #If there is a google user, but we are anonymous, log in! django_user = authenticate(google_user=google_user) if django_user: login(request, django_user) elif not django_user.is_anonymous() and not google_user: #If we are logged in with django, but not longer logged in with Google #then log out logout(request) django_user = request.user request.user = django_user backend_str = request.session.get(BACKEND_SESSION_KEY) #Now make sure we update is_superuser and is_staff appropriately if backend_str == 'djangae.contrib.gauth.backends.AppEngineUserAPI': is_superuser = users.is_current_user_admin() google_email = BaseUserManager.normalize_email(users.get_current_user().email()) resave = False if is_superuser != django_user.is_superuser: django_user.is_superuser = django_user.is_staff = is_superuser resave = True #for users which already exist, we want to verify that their email is still correct if django_user.email != google_email: django_user.email = google_email resave = True if resave: django_user.save()
def handle(self, *args, **options): fail_list = [] success_list = [] user_manager = BaseUserManager() data = pd.read_csv(options['csv']) for index, line in data.iterrows(): # pylint: disable=no-member,unused-variable try: received_offer = line['Fellow'] == 'Yes' jacs = line["Research Classification"][1:3] applicants_dict = { "application_year": 2017, "fellow": False, "received_offer": received_offer, "forenames": line["First name"], "surname": line["Surname"], "affiliation": line["Home institution"], "department": line["Department"] if pd.notnull(line["Department"]) else "", "group": line["Group within Department (if any)"] if pd.notnull(line["Group within Department (if any)"]) else "", "career_stage_when_apply": line["Career stage"][6], "job_title_when_apply": line["Job Title"], "research_area": line["Area of work"], "research_area_code": jacs, "email": line["Email Address"], "phone": line["Telephone number"], "gender": line["Gender"][0] if pd.notnull(line["Gender"]) else 'R', "home_country": "GB", "home_city": "Unknow", "funding": line["Which primary funding body/charity/organisation would you normally turn to if seeking financial support for your research/work?"], "funding_notes": line["Any additional funders?"] if pd.notnull(line["Any additional funders?"]) else "", "claimantship_grant": 3000 if received_offer else 0, "institutional_website": line["Institutional web page"] if pd.notnull(line["Institutional web page"]) else "", "website": line["Personal web page"] if pd.notnull(line["Personal web page"]) else "", "orcid": line["ORCID"] if pd.notnull(line["ORCID"]) else "", "google_scholar": line["Google Scholar"] if pd.notnull(line["Google Scholar"]) else "", "github": line["GitHub"] if pd.notnull(line["GitHub"]) else "", "gitlab": line["GitLab"] if pd.notnull(line["GitLab"]) else "", "twitter": line["Twitter handle"] if pd.notnull(line["Twitter handle"]) else "", "is_into_training": line["Have training in plans - added by AN"] == "Yes", "carpentries_instructor": line["Carpentry instructor - added by AN"] == "Yes", "research_software_engineer": line["RSE - added by AN"] == "Yes", "screencast_url": line["Application Screencast URL"] if pd.notnull(line["Application Screencast URL"]) else "", "example_of_writing_url": line["Example of writing"] if pd.notnull(line["Example of writing"]) else "", } applicant = Claimant(**applicants_dict) applicant.save() success_list.append(index) if received_offer: new_user = User.objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"] ) applicant.user = new_user applicant.save() except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) print(80 * "-") print("Success: {}".format(success_list)) print("Fail: {}".format(fail_list))
def authenticate(self, google_user=None): """ Handles authentication of a user from the given credentials. Credentials must be a 'google_user' as returned by the App Engine Users API. """ if google_user is None: return None User = get_user_model() if not issubclass(User, GaeAbstractBaseUser): raise ImproperlyConfigured( "AppEngineUserAPIBackend requires AUTH_USER_MODEL to be a " " subclass of djangae.contrib.auth.base.GaeAbstractBaseUser." ) user_id = google_user.user_id() email = BaseUserManager.normalize_email(google_user.email()) # Normalizes the domain only. try: # User exists and we can bail immediately. With one caveat. user = User.objects.get(username=user_id) # Ensure that the user has got both the `email` and `email_lower` fields populated if not user.email_lower: # The user existed before the introduction of the `email_lower` field. Update it. user.email = email # The save will also update the email_lower field user.save(update_fields=['email', 'email_lower']) return user except User.DoesNotExist: pass auto_create = should_create_unknown_user() user_is_admin = users.is_current_user_admin() try: # Users that existed before the introduction of the `email_lower` field will not have # that field, but will mostly likely have a lower case email address because we used to # lower case the email field existing_user = User.objects.get(Q(email_lower=email.lower()) | Q(email=email.lower())) except User.DoesNotExist: if not (auto_create or user_is_admin): # User doesn't exist and we aren't going to create one. return None existing_user = None # OK. We will grant access. We may need to update an existing user, or # create a new one, or both. # Those 3 scenarios are: # 1. A User object has been created for this user, but that they have not logged in yet. # In this case we fetch the User object by email, and then update it with the Google User ID # 2. A User object exists for this email address but belonging to a different Google account. # This generally only happens when the email address of a Google Apps account has been # signed up as a Google account and then the apps account itself has actually become a # Google account. This is possible but very unlikely. # 3. There is no User object realting to this user whatsoever. if existing_user: if existing_user.username is None: # We can use the existing user for this new login. existing_user.username = user_id existing_user.email = email existing_user.last_login = timezone.now() existing_user.save() return existing_user else: # We need to update the existing user and create a new one. with self.atomic(**self.atomic_kwargs): existing_user = User.objects.get(pk=existing_user.pk) existing_user.email = "" existing_user.save() return User.objects.create_user(user_id, email=email) else: # Create a new user, but account for another thread having created it already in a race # condition scenario. Our logic cannot be in a transaction, so we have to just catch this. try: return User.objects.create_user(user_id, email=email) except IntegrityError: return User.objects.get(username=user_id)
def handle(self, *args, **options): fail_list = [] success_list = [] user_manager = BaseUserManager() data = pd.read_csv(options['csv']) for index, line in data.iterrows(): # pylint: disable=no-member,unused-variable received_offer = line['Invited'] == 'YES' if line["Research Classification"] == "N/A - I do not do research": jacs = "Y0" else: jacs = line["Research Classification"][1:3] applicants_dict = { "application_year": 2018, "fellow": False, "received_offer": received_offer, "forenames": line["First name"], "surname": line["Surname"], "affiliation": line["Home Institution"], "department": line["Department"] if pd.notnull(line["Department"]) else "", "group": line["Group within Department"] if pd.notnull(line["Group within Department"]) else "", "career_stage_when_apply": line["Career stage"][6], "job_title_when_apply": line["Job Title"], "research_area": line["Area of work"], "research_area_code": jacs, "email": line["Email Address"], "phone": line["Telephone number"], "gender": line["Gender"][0] if pd.notnull(line["Gender"]) else 'R', "home_country": "GB", "home_city": "Unknow", "funding": line["Which primary funding body/charity/organisation would you normally turn to if seeking financial support for your research/work"], "funding_notes": line["Which additional funding body/charity/organisation would you probably turn to if seeking financial support for your research/work"] if pd.notnull(line["Which additional funding body/charity/organisation would you probably turn to if seeking financial support for your research/work"]) else "", "claimantship_grant": 3000 if received_offer else 0, "institutional_website": line["Please specify your Institutional webpage"] if pd.notnull(line["Please specify your Institutional webpage"]) else "", "website": line["Please specify your blog"] if pd.notnull(line["Please specify your blog"]) else "", "orcid": line["Please specify your ORCID"] if pd.notnull(line["Please specify your ORCID"]) else "", "google_scholar": line["Please specify your Google Scholar"] if pd.notnull(line["Please specify your Google Scholar"]) else "", "twitter": line["Please specify your Twitter handle"] if pd.notnull(line["Please specify your Twitter handle"]) else "", "screencast_url": line["Application Screencast URL"] if pd.notnull(line["Application Screencast URL"]) else "", "example_of_writing_url": line["Example of writing"] if pd.notnull(line["Example of writing"]) else "", } try: applicant = Claimant(**applicants_dict) applicant.save() success_list.append(index) if received_offer: new_user = User.objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"] ) applicant.user = new_user applicant.save() except IntegrityError as exception: try: applicant = Claimant.objects.get( email=applicants_dict["email"] ) for key, value in applicants_dict.items(): applicant[key] = value applicant.save() success_list.append(index) if received_offer: new_user = User.objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"] ) applicant.user = new_user applicant.save() except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) print(80 * "-") print("Success: {}".format(success_list)) print("Fail: {}".format(fail_list))
def __init__(self, **kwargs): FilteringMixin.__init__(self, **kwargs) BaseUserManager.__init__(self)