Skip to content

Commit

Permalink
add validation like logic in rpc definitions instead of underlying fu…
Browse files Browse the repository at this point in the history
…nctions
  • Loading branch information
Anish9901 committed Nov 15, 2024
1 parent 1718ccf commit a65d47f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
22 changes: 12 additions & 10 deletions mathesar/rpc/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
)

from mathesar.rpc.exceptions.handlers import handle_rpc_exceptions
from modernrpc.exceptions import AuthenticationFailed
from mathesar.utils.auth import (
http_basic_auth_is_self_or_superuser,
http_basic_auth_is_self
)
from mathesar.utils.users import (
get_user,
list_users,
Expand Down Expand Up @@ -94,7 +97,7 @@ def list_() -> list[UserInfo]:


@rpc_method(name='users.patch')
@http_basic_auth_login_required
@http_basic_auth_is_self_or_superuser
@handle_rpc_exceptions
def patch(
*,
Expand All @@ -103,18 +106,17 @@ def patch(
**kwargs
) -> UserInfo:
user = kwargs.get(REQUEST_KEY).user
if not (user.id == user_id or user.is_superuser):
raise AuthenticationFailed('users.patch')
if not user.is_superuser:
user_info.pop("is_superuser", None)
updated_user_info = update_user_info(
user_id,
user_info,
requesting_user=user
user_info
)
return UserInfo.from_model(updated_user_info)


@rpc_method(name='users.password.replace_own')
@http_basic_auth_login_required
@http_basic_auth_is_self
@handle_rpc_exceptions
def replace_own(
*,
Expand All @@ -124,9 +126,9 @@ def replace_own(
**kwargs
) -> None:
user = kwargs.get(REQUEST_KEY).user
if not user.id == user_id:
raise AuthenticationFailed('users.password.replace_own')
change_password(user_id, old_password, new_password)
if not user.check_password(old_password):
raise Exception('Old password is not correct')
change_password(user_id, new_password)


@rpc_method(name='users.password.revoke')
Expand Down
8 changes: 2 additions & 6 deletions mathesar/utils/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ def add_user(user_def):
return user


def update_user_info(user_id, user_info, requesting_user):
if not requesting_user.is_superuser:
user_info.pop("is_superuser", None)
def update_user_info(user_id, user_info):
User.objects.filter(id=user_id).update(
username=user_info.get("username", F("username")),
is_superuser=user_info.get("is_superuser", F("is_superuser")),
Expand All @@ -46,10 +44,8 @@ def delete_user(user_id):
User.objects.get(id=user_id).delete()


def change_password(user_id, old_password, new_password):
def change_password(user_id, new_password):
user = get_user(user_id)
if not user.check_password(old_password):
raise Exception('Old password is not correct')
user.set_password(new_password)
user.password_change_needed = False
user.save()
Expand Down

0 comments on commit a65d47f

Please sign in to comment.