def change_email(self, request): """ Change the current logged user email change. --- serializer: ChangeEmailSerializer """ serializer = ChangeEmailSerializer(data=request.data, many=False) if not serializer.is_valid(): raise WrongArguments( _("Invalid, are you sure the token is correct and you didn't use it before?" )) try: user = User.objects.get(email_token=serializer.data["email_token"]) except User.DoesNotExist: raise WrongArguments( _("Invalid, are you sure the token is correct and you didn't use it before?" )) user.email = user.new_email user.new_email = None user.email_token = None user.save(update_fields=["email", "new_email", "email_token"]) return Response({ "success": _("Email Changed successfully!"), }, status=status.HTTP_200_OK)
def cancel(self, request, pk=None): """ Cancel an account via token. --- serializer: CancelAccountSerializer """ serializer = CancelAccountSerializer(data=request.DATA, many=False) if not serializer.is_valid(): raise WrongArguments(_("Missing arguments")) try: max_age_cancel_account = getattr(settings, "MAX_AGE_CANCEL_ACCOUNT", None) user = get_user_for_token(serializer.data["cancel_token"], "cancel_account", max_age=max_age_cancel_account) except NotAuthenticated: raise WrongArguments( _("Invalid, are you sure the token is correct?")) if not user.is_active: raise WrongArguments( _("Invalid, are you sure the token is correct?")) # user.delete() TODO Decide if account is cleared or disactivated only user.is_active = False user.save(update_fields=[ "is_active", ]) return Response({ "success": _("Your Accound has been cancelled!"), }, status=status.HTTP_200_OK)
def password_recovery(self, request): """ Get a token to email for change password via token. --- serializer: AccountRecoverySerializer """ username_or_email = request.data.get('username', None) if not username_or_email: raise WrongArguments(_("Invalid username or email")) try: queryset = User.objects.all() user = queryset.get( Q(username=username_or_email) | Q(email=username_or_email)) except User.DoesNotExist: raise WrongArguments(_("Invalid username or email")) user.token = str(uuid.uuid1()) user.save(update_fields=["token"]) mbuilder = MagicMailBuilder() email = mbuilder.password_recovery( user.email, { "user": user, "base_url": settings.WEBSITE_BASE_URL, }) email.send() return Response( { "success": _("Mail sended successful!"), "email": user.email, }, status=status.HTTP_200_OK)
def register(username, password, email, first_name, last_name): """ Given a parsed parameters, try register a new user knowing that it follows a public register flow. This can raise `exc.IntegrityError` exceptions in case of conflics found. :returns: User """ is_registered, reason = is_user_already_registered(username=username, email=email) if is_registered: raise WrongArguments(reason) user_model = apps.get_model("users", "User") user = user_model( username=username, email=email, first_name=first_name, last_name=last_name, ) user.set_password(password) try: user.is_active = False user.is_staff = False user.token = str(uuid.uuid1()) user.save() except IntegrityError: raise WrongArguments("User is already register.") send_register_email(user) user_registered_signal.send(sender=user.__class__, user=user) return user
def get_and_validate_user(username, password): """ Check if user with username/email exists and specified password matchs well with existing user password. if user is valid, user is returned else, corresponding exception is raised. """ user_model = apps.get_model("users", "User") qs = user_model.objects.filter(Q(username=username) | Q(email=username)) if len(qs) == 0: raise WrongArguments("Username or password does not matches user.") user = qs[0] if not user.check_password(password): raise WrongArguments("Username or password does not matches user.") return user
def confirm_register(self, request): """ Comfirmation account register. >>> register step required <<< --- parameters: - name: token description: this token is sended to user email, after user registration. required: true type: string paramType: form """ serializer = ConfirmRegisterSerializer(data=request.data) if not serializer.is_valid(): raise WrongArguments(_("Missing arguments")) try: user = User.objects.get(token=serializer.data["token"]) except User.DoesNotExist: raise WrongArguments(_("Token is invalid")) user.is_active = True mbuilder = MagicMailBuilder() cancel_token = get_token_for_user(user, "cancel_account") email = mbuilder.registered_user_confirmation( user.email, { "user": user, "cancel_token": cancel_token, "base_url": settings.WEBSITE_BASE_URL, }) email.send() user.token = None user.save(update_fields=["is_active", "token"]) return Response({ "success": _("Welcome your account has been activated!"), }, status=status.HTTP_200_OK)
def password_from_recovery(self, request): """ Change password with token >>> requiere password recovery step.<<< --- serializer: PasswordRecoverySerializer """ serializer = PasswordRecoverySerializer(data=request.data) if not serializer.is_valid(): raise WrongArguments(_("Missing arguments")) try: user = User.objects.get(token=serializer.data["token"]) except User.DoesNotExist: raise WrongArguments(_("Token is invalid")) user.set_password(serializer.data["password"]) user.token = None user.save(update_fields=["password", "token"]) return Response({ "success": _("Password Changed successfully!"), }, status=status.HTTP_200_OK)
class UsersViewSet(ModelCrudViewSet): permission_classes = [ UserPermissionSet, ] serializer_class = UserSerializer queryset = User.objects.all() paginate_by = 25 page_size = 25 def list(self, request, *args, **kwargs): """ List of all users """ page = self.paginate_queryset(self.queryset) if page is not None: serializer = self.get_pagination_serializer(page) else: serializer = self.get_serializer(self.queryset, many=True) return Response(serializer.data) def partial_update(self, request, *args, **kwargs): """ Save the user partial updates. We must detect if the user is trying to change his email so we can save that value and generate a token that allows him to validate it in the new email account """ try: current_user = User.objects.get(id=kwargs["pk"]) except Exception, e: raise RequestValidationError(_("User not found")) if current_user != request.user: raise RequestValidationError( _("You cann't change of other users information")) old_email = request.user.email new_email = request.data.get('email', None) if new_email is not None and new_email != old_email: valid_new_email = True duplicated_email = User.objects.filter(email=new_email).exists() try: validate_email(new_email) except ValidationError: valid_new_email = False if duplicated_email: raise WrongArguments( _("This mail is being used by another user")) elif not valid_new_email: raise WrongArguments(_("Not valid email")) # We need to generate a token for the email request.user.email_token = str(uuid.uuid1()) request.user.new_email = new_email request.user.email = old_email request.data["email"] = old_email request.user.save( update_fields=["email_token", "new_email", "email"]) mbuilder = MagicMailBuilder() email = mbuilder.change_email( request.user.email, { "user": request.user, "base_url": settings.WEBSITE_BASE_URL, }) email.send() return super(UsersViewSet, self).partial_update(request, *args, **kwargs)