def cancel(self, request): """ # Init the Cancel account flow and send token for it. --- omit_serializer: true """ action_exist = UserAction.objects.filter( user=request.user, type=UserAction.ACTION_DISABLE_ACCOUNT).exists() if action_exist: action = UserAction.objects.get( user=request.user, type=UserAction.ACTION_DISABLE_ACCOUNT) else: action = UserAction(user=request.user, type=UserAction.ACTION_DISABLE_ACCOUNT) action.token = get_uuid() action.creation_date, action.expiration_date = get_lapse() action.save() messaging.send_cancel_account(request, action) return DoneResponse( detail= _("Se inicio el proceso de desactivación de tu cuenta revisa tu correo para finalizarlo." ), status=status.HTTP_201_CREATED, code=codes.CANCEL_ACCOUNT_SENT, )
def post(self, request, **kwargs): """Clear all application sessions.""" serializer = RefreshTokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) SessionService.drop_session(serializer.validated_data['refresh_token']) return DoneResponse(**response_codes.LOGGED_OUT)
def do_cancel_confirm(request, token=None, inner=False): action_exist = UserAction.objects.filter( token=token, type=UserAction.ACTION_DISABLE_ACCOUNT).exists() context = dict() context["title"] = _("Cancel account") if action_exist: action = UserAction.objects.get(token=token, type=UserAction.ACTION_DISABLE_ACCOUNT) action.user.is_active = False action.user.save() if not settings: action.user.delete() action.delete() message = _("Tu cuenta ha sido eliminada correctamente") if inner: context["message"] = message return render(request, 'credentials/message.html', context) else: return DoneResponse( detail=message, status=status.HTTP_201_CREATED, code=codes.ACCOUNT_DISABLED, ) else: message = _("Acción inválida") if inner: context["message"] = message context["error"] = True return render(request, 'credentials/message.html', context) else: raise ValidationError(detail=message, code=codes.INVALID_ACTION)
def do_change_email(request, token=None, inner=False): action_exist = UserAction.objects.filter( token=token, type=UserAction.ACTION_CHANGE_EMAIL).exists() context = dict() context["title"] = _("Change email") if action_exist: action = UserAction.objects.get(token=token, type=UserAction.ACTION_CHANGE_EMAIL) action.user.email = action.value action.user.save() action.delete() if inner: context["message"] = _("Tu correo ha sido actualizado con éxito") return render(request, 'credentials/message.html', context) else: return DoneResponse( detail=_("Correo actualizado con exito!"), status=status.HTTP_201_CREATED, code=codes.EMAIL_UPDATED, ) else: if inner: context["message"] = _("Acción Invalida!") context["error"] = True return render(request, 'credentials/message.html', context) else: raise ValidationError(detail=_("Token de transacción invalido"), code=codes.INVALID_TRANSACTION_TOKEN)
def email_confirmation_request(self, request): """Requests a confirmation email.""" serializer = UsernameOrEmailSerializer(data=request.data) serializer.is_valid(raise_exception=True) username_or_email = serializer.validated_data['user'] user = UserSelector.get_by_username_or_email(username_or_email) if user.is_active: return DoneResponse( **response_codes.EMAIL_VERIFIED, status=status.HTTP_400_BAD_REQUEST, ) else: AuthService.send_confirmation_email(user) return DoneResponse(**response_codes.CONFIRMATION_EMAIL_SENT)
def email_confirmation(self, request): """Confirms an email.""" serializer = TokenSerializer(data=request.data) serializer.is_valid(raise_exception=True) pending_action = PendingActionSelector.get_by_token( token=serializer.validated_data['token'], category=ActionCategory.CONFIRM_EMAIL.value, ) AuthService.confirm_email(pending_action) return DoneResponse(**response_codes.EMAIL_VERIFIED)
def clear_sessions(self, request): """ # Clear all application sessions. --- omit_serializer: true """ access_tokens = AccessToken.objects.filter(user=request.user) access_tokens.delete() return DoneResponse( detail=_("Sessions cleared.!"), code=codes.SESSIONS_CLEARED, )
def set_password(self, request): """Sets the user password.""" serializer = PasswordSetSerializer( data=request.data, context={'request': request}, ) serializer.is_valid(raise_exception=True) plain_password = serializer.validated_data['password'] PasswordService.set_pasword(request.user, plain_password) return DoneResponse(**response_codes.PASSWORD_ADDED)
def do_reset_password(request, token=None, password=None, inner=False): action_exist = UserAction.objects.filter( token=token, type=UserAction.ACTION_RESET_PASSWORD).exists() context = dict() context["title"] = _("Reset Password") if action_exist: action = UserAction.objects.get(token=token, type=UserAction.ACTION_RESET_PASSWORD) context["valid"] = True user = action.user if user.is_active: if inner: form = ResetPasswordForm(data=request.POST) if form.is_valid(): password = form.cleaned_data["password1"] _change_password(request, action, password) context["message"] = _( "Password has been reseted successfully!.") return render(request, 'credentials/message.html', context) else: context["has_error"] = True context["message"] = _("Passwords aren't match!") return render(request, 'credentials/password_reset.html', context) else: _change_password(request, action, password) return DoneResponse( detail=_("La Contraseña ha sido restaurada!."), code=codes.PASSWORD_RESTORED, status=status.HTTP_201_CREATED, ) else: if inner: context["has_error"] = True context["message"] = _("This an inactive account!") return render(request, 'credentials/password_reset.html', context) else: raise ValidationError(detail=_("Cuenta inactiva"), code=codes.INACTIVE_ACCOUNT) else: if inner: context["has_error"] = True context["message"] = _("Invalid action!") return render(request, 'credentials/password_reset.html', context) else: raise ValidationError(detail=_("Token de transacción invalido"), code=codes.INVALID_TRANSACTION_TOKEN)
def reset_password(self, request): """Request a password reset.""" serializer = PasswordResetSerializer(data=request.data) serializer.is_valid(raise_exception=True) username_or_email = serializer.validated_data['user'] user = UserSelector.get_by_username_or_email(username_or_email) pending_action = PasswordService.perform_reset_password(user) AuthEmailService.send_reset_password(pending_action) return DoneResponse(**response_codes.RESET_PASSWORD_SENT)
def update_password(self, request): """Updates the useer passwrod.""" serializer = PasswordUpdateSerializer( data=request.data, context={'request': request}, ) serializer.is_valid(raise_exception=True) new_plain_password = serializer.validated_data['new_password'] PasswordService.set_pasword(request.user, new_plain_password) update_session_auth_hash(request, request.user) return DoneResponse(**response_codes.PASSWORD_UPDATED)
def post(self, request): """Registers an user using the info.""" serializer = RegisterSerializer(data=request.data) serializer.is_valid(raise_exception=True) if config.REGISTER_REQUIRES_EMAIL_CONFIRMATION: user = UserService.register_new_user( user_data=serializer.validated_data) AuthService.send_confirmation_email(user) return DoneResponse(**CONFIRMATION_EMAIL_SENT) else: user = UserService.register_new_user( user_data=serializer.validated_data) return Response(SessionSerializer(user).data)
def reset_password_confirm(self, request): """Confirms a password reset.""" serializer = PasswordResetConfirmSerializer(data=request.data) serializer.is_valid(raise_exception=True) plain_password = serializer.validated_data['password'] action_token = serializer.validated_data['token'] pending_action = PendingActionSelector.get_by_token( action_token, category=ActionCategory.RESET_PASSWORD.value, ) PasswordService.confirm_reset_password(pending_action, plain_password) return DoneResponse(**response_codes.PASSWORD_UPDATED)
def do_confirm_register(request, token=None, inner=False): action_exist = UserAction.objects.filter( token=token, type=UserAction.ACTION_ENABLE_ACCOUNT).exists() context = dict() context["title"] = _("Confirmación de Cuenta") if action_exist: action = UserAction.objects.get(token=token, type=UserAction.ACTION_ENABLE_ACCOUNT) user = action.user user.is_active = True user.save() messaging.send_welcome(request, action) action.delete() if inner: context["message"] = _("Tu cuenta ha sido activada exitosamente.") return render(request, 'credentials/message.html', context) else: return DoneResponse( detail=_("La cuenta ha sido activada!"), code=codes.ACCOUNT_IS_ACTIVATED, status=status.HTTP_201_CREATED, ) else: if inner: context["message"] = _( "Esta Cuenta es inválida o ya fué activada.") context["error"] = True return render(request, 'credentials/message.html', context) else: raise ValidationError(detail=_("Token de transacción invalido"), code=codes.INVALID_TRANSACTION_TOKEN)
def change_password(self, request): """ # Change the password of the current user. --- serializer: PasswordChangeSerializer """ serializer = PasswordChangeSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = request.user user.set_password(serializer.data["new_password"]) user.save() if user.is_active: action_exist = UserAction.objects.filter( user=user, type=UserAction.ACTION_RESET_PASSWORD).exists() if action_exist: action = UserAction.objects.get( user=user, type=UserAction.ACTION_RESET_PASSWORD) else: action = UserAction(user=user, type=UserAction.ACTION_RESET_PASSWORD) action.token = get_uuid() action.creation_date, action.expiration_date = get_lapse() action.save() messaging.change_password_realized(request, action) return DoneResponse( detail=_("Password successfully changed"), status=status.HTTP_201_CREATED, code=codes.PASSWORD_CHANGED, )
def change_email(self, request): """ # Change the current user email change. --- serializer: EmailChangeSerializer """ serializer = EmailChangeSerializer(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = request.user user.email = serializer.data["email"] user.save() if user.is_active: action_exist = UserAction.objects.filter( user=user, type=UserAction.ACTION_RESET_PASSWORD).exists() if action_exist: action = UserAction.objects.get( user=user, type=UserAction.ACTION_RESET_PASSWORD) else: action = UserAction(user=user, type=UserAction.ACTION_RESET_PASSWORD) action.token = get_uuid() action.creation_date, action.expiration_date = get_lapse() action.save() messaging.change_email_realized(request, action) return DoneResponse( detail=_("Email successfully changed"), status=status.HTTP_201_CREATED, code=codes.EMAIL_UPDATED, )