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 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
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)
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
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 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
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_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
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} )
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 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)
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 validate_email(self,value): """ Method for validating email id """ userAccount = User.objects.filter(email=value) if userAccount: raise serializers.ValidationError("Email is already taken") return BaseUserManager.normalize_email(value)
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
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
def create_user(self, email, user_name, last_name, first_name, password, **other_fields): if not email: raise ValueError(_('provide an email')) email = BaseUserManager.normalize_email(email=email) user = Register(email=email, user_name=user_name, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user
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
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, 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 register(request): user_model = get_user_model() try: email = BaseUserManager.normalize_email(request.data["email"]) if not is_email_valid(email): raise ValueError if settings.OPEN_REGISTRATION: preexisting_user, _ = user_model.objects.get_or_create(email=email) else: preexisting_user = user_model.objects.get(email__iexact=email) preexisting_user.register_preexisting_user(request.data.get("name")) LOGGER.info( log_filter( request, "registration succeded; " "email: '" + str(email) + "'", )) return Response({}, status=status.HTTP_201_CREATED) except IntegrityError: LOGGER.error( log_filter( request, "Registration failed: IntegrityError; " "email: '" + str(email) + "'", )) return Response({}, status=status.HTTP_201_CREATED) except user_model.DoesNotExist: LOGGER.error( log_filter( request, "Registration failed: Email or Researcher Id not found; " "email: '" + str(email) + "'", )) return Response( { "error_msg": ("Registration is closed." " Please contact an administrator.") }, status=status.HTTP_403_FORBIDDEN) except KeyError: LOGGER.error( log_filter(request, "Registration failed: KeyError; " + str(request.data))) return Response({}, status=status.HTTP_201_CREATED) except ValueError: LOGGER.error( log_filter( request, f"Registration failed: Invalid email; email: '{str(email)}'")) return Response( { "error_msg": ("Invalid email address entered." " Please use a valid email address.") }, status=status.HTTP_400_BAD_REQUEST)
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 normalize_email(cls, email): """ Whether to lowercase entire email based on ACCOUNT_LOWER_EMAIL setting. """ if app_settings.ACCOUNT_LOWER_EMAIL: email = email or '' # follow BaseUserManager's behavior return email.lower() else: return BaseUserManager.normalize_email(email)
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 validate_email(self, value): user = usr.objects.filter(email=value) social_user = SocialDocs.objects.filter(email=value) if not user: raise serializers.ValidationError("Email is not registered") if social_user: raise serializers.ValidationError( "The with this email is reqistered via google so s/he cannot have a password to change" ) return BaseUserManager.normalize_email(value)
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, 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 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 validate_email(self, value): """Validate email Validate the user's email address to ensure that the email address doesn't already exist in the database. An error will be raise if the email exists within the database """ user = UserProfile.objects.filter(email=value) if user: raise serializers.ValidationError('Email is already taken') return BaseUserManager.normalize_email(value)
def authenticate(self, **kwargs): email = kwargs.get('username') password = kwargs.get('password') try: if email: user = MyUser.objects.get( email=BaseUserManager.normalize_email(email)) if user.check_password(password): return user except MyUser.DoesNotExist: return None
def update(self, instance, validated_data): get_user_model() if 'email' in validated_data: validated_data['email'] = BaseUserManager.normalize_email(validated_data['email']) if 'username' in validated_data: validated_data['username'] = AbstractUser.normalize_username(validated_data['username']) user = super(CreateUpdateUserSerializer, self).update(instance, validated_data) if 'password' in validated_data: user.set_password(validated_data['password']) user.save() 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 validate(self, attrs): """token validation and authentication""" email = BaseUserManager.normalize_email(attrs.get('email')) user = authenticate( request=self.context.get('request'), username=email, # email as username for custom user password=attrs.get('password')) if not user: msg = "Unable to authenticate user with provided credentials" raise serializers.ValidationError(msg, code='authentication') attrs['user'] = user return attrs
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.models.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 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, BaseAppEngineUserAPIBackend): # 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 create_admin(apps, schema_editor): Learner = apps.get_model('learners', 'Learner') email = BaseUserManager.normalize_email('admin@localhost') admin = Learner(email=email, is_staff=True, is_superuser=True, name='Admin', need_active_update=True, minimum_delay=3, new_count=5) admin.password = make_password('MCTDH') admin.save() stderr.write( '\n*********************************************************************\nA user with email "admin@localhost" and password "MCTDH" was created.\nYou should update the password!\n*********************************************************************\n' )
def create_user(self, number, password, name="", email=None): if email is None: email = f"{number}@u-aizu.ac.jp" user = User( name=name, number=number, email=BaseUserManager.normalize_email(email), coin=0, ) user.set_password(password) user.save(using=self._db) # Create Auth Token Token.objects.create(user=user) 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 = 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 create_api_user(self, **extra_fields): """ used in the api. """ fields = copy.copy(extra_fields) # pop fields username = fields.pop('username', None) email = BaseUserManager.normalize_email(fields.pop('email', None)) password = make_password(fields.pop('password', None)) facebook_id = self._convert_int_or_none(fields.pop( 'facebook_id', None)) twitter_id = self._convert_int_or_none(fields.pop('twitter_id', None)) instagram_id = self._convert_int_or_none( fields.pop('instagram_id', None)) line_id = fields.pop('line_id', None) nickname = fields.pop('nickname', None) extra = fields.pop('extra', {'instagram_username': ''}) activity_settings = fields.pop('activity_settings', {'comments_public': True}) # validations if not username: raise AE104() if not any([facebook_id, twitter_id, instagram_id, line_id ]) and not password: raise AE103() # remove None values from the fields to prevent error. for k, v in list(fields.items()): if v is None: del fields[k] user = self.model(username=username, nickname=nickname or username, facebook_id=facebook_id, twitter_id=twitter_id, instagram_id=instagram_id, line_id=line_id, email=email, password=password, is_active=True, extra=extra, activity_settings=activity_settings, **fields) user.full_clean() user.save(using=self._db) # set temporal flag to let view know that the user is just created and return 201 response. user.is_new = True return user
def save(self, *args, **kwargs): """ Clean the data before saving to the database also generate api key if no key :param args: :param kwargs: :return: """ self.username = self.normalize_username(self.username) self.work_email = BaseUserManager.normalize_email(self.work_email) if self.reporting_manager: try: _reporting_manager = Employee.get_employee_by_email( self.reporting_manager) except err.NotFoundError: log.error(self.reporting_manager) raise err.ValidationError({ "reporting_manager": "Given reporting manager not available" }) if _reporting_manager.id == self.id: raise err.ValidationError({ "reporting_manager": "You cannot assign yourself as reporting manager" }) self.reporting_manager = _reporting_manager.id if not hasattr(self, "_api_key") or not getattr(self, "_api_key"): log.info("Creating a new api key") api_key, key = APIKey.objects.create_key(name=self.work_email) self._api_key = APIKey.objects.get_from_key(key) _fields = ("employee_id", ) for _field in _fields: val = getattr(self, _field) if val: setattr(self, _field, val.lower().strip()) if not self.graduated_year: self.graduated_year = None # TODO default array doesnt work - Hack if not getattr(self, "skills"): self.skills = list() return super(self.__class__, self).save(*args, **kwargs)
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, username, email, password=None): """ Creates and saves a User with the given email, date of birth and password. """ print "HERE DETECTION" 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(using=self._db) 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 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: return User.objects.get(username=user_id) except User.DoesNotExist: try: existing_user = User.objects.get(email=BaseUserManager.normalize_email(email)) except User.DoesNotExist: force_pre_creation = getattr(settings, "DJANGAE_FORCE_USER_PRE_CREATION", False) user_is_admin = users.is_current_user_admin() if force_pre_creation and not user_is_admin: # Indicate to Django that this user is not allowed return return User.objects.create_user(user_id, email) # If the existing user was precreated, update and reuse it if existing_user.username is None: if ( getattr(settings, "DJANGAE_ALLOW_USER_PRE_CREATION", False) or # Backwards compatibility, remove before 1.0 getattr(settings, "ALLOW_USER_PRE_CREATION", False) ): # Convert the pre-created User object so that the user can now login via # Google Accounts, and ONLY via Google Accounts. existing_user.username = user_id existing_user.last_login = timezone.now() existing_user.save() return existing_user # There's a precreated user but user precreation is disabled # This will fail with an integrity error from django.db import IntegrityError raise IntegrityError( "GAUTH: Found existing User with email=%s and username=None, " "but user precreation is disabled." % email ) # There is an existing user with this email address, but it is tied to a different # Google user id. As we treat the user id as the primary identifier, not the email # address, we leave the existing user in place and blank its email address (as the # email field is unique), then create a new user with the new user id. else: logging.info( "GAUTH: Creating a new user with an existing email address " "(User(email=%s, pk=%s))" % (email, existing_user.pk) ) with self.atomic(**self.atomic_kwargs): existing_user = User.objects.get(pk=existing_user.pk) existing_user.email = None existing_user.save() return User.objects.create_user(user_id, email) 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 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()) try: # User exists and we can bail immediately. return User.objects.get(username=user_id) except User.DoesNotExist: pass auto_create = should_create_unknown_user() user_is_admin = users.is_current_user_admin() if not (auto_create or user_is_admin): # User doesn't exist and we aren't going to create one. return 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 wefetch 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. try: existing_user = User.objects.get(email=email) except User.DoesNotExist: existing_user = None 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 = None existing_user.save() return User.objects.create_user(user_id, email=email) else: return User.objects.create_user(user_id, email=email)
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. """ 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." ) if google_user is None: # users.get_current_user() can return None. return None user_id = google_user.user_id() email = BaseUserManager.normalize_email(google_user.email()) try: return User.objects.get(username=user_id) except User.DoesNotExist: try: existing_user = User.objects.get(email=BaseUserManager.normalize_email(email)) except User.DoesNotExist: force_pre_creation = getattr(settings, 'DJANGAE_FORCE_USER_PRE_CREATION', False) user_is_admin = users.is_current_user_admin() if force_pre_creation and not user_is_admin: # Indicate to Django that this user is not allowed return return User.objects.create_user(user_id, email) # If the existing user was precreated, update and reuse it if existing_user.username is None: if ( getattr(settings, 'DJANGAE_ALLOW_USER_PRE_CREATION', False) or # Backwards compatibility, remove before 1.0 getattr(settings, 'ALLOW_USER_PRE_CREATION', False) ): # Convert the pre-created User object so that the user can now login via # Google Accounts, and ONLY via Google Accounts. existing_user.username = user_id existing_user.last_login = timezone.now() existing_user.save() return existing_user # There's a precreated user but user precreation is disabled # This will fail with an integrity error from django.db import IntegrityError raise IntegrityError( "GAUTH: Found existing User with email=%s and username=None, " "but user precreation is disabled." % email ) # There is an existing user with this email address, but it is tied to a different # Google user id. As we treat the user id as the primary identifier, not the email # address, we leave the existing user in place and blank its email address (as the # email field is unique), then create a new user with the new user id. else: logging.info( "GAUTH: Creating a new user with an existing email address " "(User(email=%r, existing pk=%r))", email, existing_user.pk ) with self.atomic(**self.atomic_kwargs): existing_user = User.objects.get(pk=existing_user.pk) existing_user.email = None existing_user.save() return User.objects.create_user(user_id, email)
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)