Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to change username #21152

Merged
merged 2 commits into from
Jun 24, 2024
Merged

Allow to change username #21152

merged 2 commits into from
Jun 24, 2024

Conversation

bramkragten
Copy link
Member

@bramkragten bramkragten commented Jun 24, 2024

Proposed change

For: home-assistant/core#109057

Also saved the userid on the person when the user is created, to avoid weird UX.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (thank you!)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Example configuration

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue or discussion:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • There is no commented out code in this PR.
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

Summary by CodeRabbit

  • New Features

    • Added functionality for administrators to change usernames in Home Assistant.
  • UI Enhancements

    • Updated the user detail dialogs to include options for changing usernames, with appropriate prompts and error handling.
    • Improved secondary action buttons to support username changes.
  • Translations

    • Added new messages and keys to support username change notifications and errors.

Copy link
Contributor

coderabbitai bot commented Jun 24, 2024

Walkthrough

Walkthrough

The core enhancement is the addition of an admin functionality to change user usernames within Home Assistant. This allows administrators to modify usernames directly via the UI, ensuring better user management. Key updates include introducing a new method, adminChangeUsername, and integrating it across multiple components, handling UI prompts, and ensuring error management for a seamless user experience.

Changes

Files/Paths Change Summary
src/data/auth.ts Added adminChangeUsername function to enable admin changes to usernames.
src/panels/config/person/dialog-person-detail.ts Integrated adminChangeUsername import; updated import statements for consistency; added _changeUsername method; adjusted UI and state handling for both username and password changes.
src/panels/config/users/dialog-user-detail.ts Added adminChangeUsername import; modified _changeUsername and _changePassword methods to handle username changes with prompts and backend calls.
src/panels/config/users/ha-config-users.ts Introduced replaceEntry method in the HaConfigUsers class to update user entries in the array.
src/panels/config/users/show-dialog-user-detail.ts Added replaceEntry method in UserDetailDialogParams interface to update user entries.
src/translations/en.json Added translation keys and messages related to username change functionalities such as change_username, new_username, and error/success messages.

Sequence Diagrams

sequenceDiagram
    participant Admin as Administrator
    participant UI as User Interface
    participant Auth as Authentication Module
    participant Backend as Backend System

    Admin->>UI: Initiate username change
    UI->>Auth: Call `adminChangeUsername` with userId and new username
    Auth->>Backend: Verify admin privileges
    Backend-->>Auth: Return verification status
    Auth-->>UI: Success/Failure result of username change
    UI-->>Admin: Display success/error message through UI
Loading
sequenceDiagram
    participant Admin as Administrator
    participant UI as User Interface
    participant Dialog as Dialog Module
    participant Auth as Authentication Module
    participant Backend as Backend System
 
    Admin->>UI: Trigger user detail dialog
    UI->>Dialog: Open dialog for user details
    Admin->>UI: Select change username option
    UI->>Admin: Prompt for new username
    Admin->>UI: Enter new username
    UI->>Auth: Invoke `adminChangeUsername` with new username
    Auth->>Backend: Process username change
    Backend-->>Auth: Return result of change
    Auth-->>UI: Notify UI of change status
    UI-->>Admin: Display success/error message
Loading

Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

Commits

Files that changed from the base of the PR and between a2fac7c and 3edcb0b.

Files selected for processing (1)
  • src/panels/config/person/dialog-person-detail.ts (7 hunks)
Additional context used
Biome
src/panels/config/person/dialog-person-detail.ts

[error] 115-115: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 125-125: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 126-126: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 141-141: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 204-204: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 217-217: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 227-227: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 242-242: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 245-245: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 273-273: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 274-274: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 100-100: Excessive complexity detected. (lint/complexity/noExcessiveCognitiveComplexity)

Please refactor this function to reduce its complexity score from 17 to the max allowed complexity 15.


[error] 305-305: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 306-306: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 320-320: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 324-324: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 327-327: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 392-392: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 404-404: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.


[error] 419-419: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

Additional comments not posted (2)
src/panels/config/person/dialog-person-detail.ts (2)

11-11: Addition of new imports for username change functionality

The addition of adminChangeUsername and showPromptDialog imports are crucial for the new functionality allowing username changes. This aligns with the PR's objective to enhance user management capabilities.

Also applies to: 23-23


249-263: New UI elements for changing username and password

The addition of buttons for changing username and password is a direct implementation of the new feature. This is a crucial part of the user interface that allows users to interact with the new functionality.
[APROVED]


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Outside diff range comments (2)
src/data/auth.ts (1)

Line range hint 89-89: Refactor to avoid reassigning function parameters.

Reassigning function parameters can lead to confusing and hard-to-maintain code. It's recommended to use local variables instead.

- url += "?";
+ let modifiedUrl = url;
+ modifiedUrl += "?";
- url += "&";
+ modifiedUrl += "&";
- url += `code=${encodeURIComponent(authCode)}`;
+ modifiedUrl += `code=${encodeURIComponent(authCode)}`;

Also applies to: 91-91, 94-94, 97-97, 100-100

src/panels/config/person/dialog-person-detail.ts (1)

Line range hint 305-336: Handle user login status changes.

This segment of code handles changes to a user's login status, including the creation of new user IDs and the deletion of existing ones. The use of non-null assertions (!) should be avoided where possible as they can lead to runtime errors if not handled properly.

- await this._params!.updateEntry({ user_id: user.id });
+ await this._params?.updateEntry({ user_id: user.id });
Tools
Biome

[error] 305-305: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Outside diff range comments (1)
src/panels/config/person/dialog-person-detail.ts (1)

Line range hint 305-338: Handling of user linkage and un-linkage in _allowLoginChanged method

This method handles the linking and unlinking of users to a person which is a sensitive operation. It's crucial to ensure that all null assertions are safely handled to prevent runtime errors.

- if (this._params!.entry) {
-   await this._params!.updateEntry({ user_id: user.id });
- }
- this._params?.refreshUsers();
- this._user = user;
- this._userId = user.id;
- this._isAdmin = user.group_ids.includes(SYSTEM_GROUP_ID_ADMIN);
- this._localOnly = user.local_only;
+ if (this._params?.entry) {
+   await this._params.updateEntry({ user_id: user.id });
+ }
+ this._params?.refreshUsers();
+ this._user = user;
+ this._userId = user.id;
+ this._isAdmin = user.group_ids.includes(SYSTEM_GROUP_ID_ADMIN);
+ this._localOnly = user.local_only;
Tools
Biome

[error] 305-305: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator


[error] 306-306: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

Comment on lines +141 to +143
.label=${`${this.hass!.localize(
"ui.panel.config.person.detail.allow_login"
)}
)}${this._user ? ` (${this._user.username})` : ""}`}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper sanitization of this._user.username in UI contexts.

The current implementation directly uses this._user.username in the UI without any sanitization, which could lead to XSS vulnerabilities. Review and implement proper sanitization methods to handle the username safely.

- .label=${`${this.hass!.localize(
-   "ui.panel.config.person.detail.allow_login"
- )}${this._user ? ` (${this._user.username})` : ""}`}
+ .label=${`${this.hass!.localize(
+   "ui.panel.config.person.detail.allow_login"
+ )}${this._user ? ` (${this.hass.localize(this._user.username)})` : ""}`}

Committable suggestion was skipped due to low confidence.

Tools
Biome

[error] 141-141: Forbidden non-null assertion. (lint/style/noNonNullAssertion)

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

Comment on lines +368 to +413
private async _changeUsername() {
if (!this._user) {
return;
}
const credential = this._user.credentials.find(
(cred) => cred.type === "homeassistant"
);
if (!credential) {
showAlertDialog(this, {
title: "No Home Assistant credentials found.",
});
return;
}

const newUsername = await showPromptDialog(this, {
inputLabel: this.hass.localize(
"ui.panel.config.users.change_username.new_username"
),
confirmText: this.hass.localize(
"ui.panel.config.users.change_username.change"
),
title: this.hass.localize(
"ui.panel.config.users.change_username.caption"
),
defaultValue: this._user.username!,
});
if (newUsername) {
try {
await adminChangeUsername(this.hass, this._user.id, newUsername);
this._params?.refreshUsers();
this._user = { ...this._user, username: newUsername };
showAlertDialog(this, {
text: this.hass.localize(
"ui.panel.config.users.change_username.username_changed"
),
});
} catch (err: any) {
showAlertDialog(this, {
title: this.hass.localize(
"ui.panel.config.users.change_username.failed"
),
text: err.message,
});
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implementation of the _changeUsername method

This method is well-implemented with error handling and user prompts. However, the use of a non-null assertion on this._user.username is potentially unsafe and should be replaced with optional chaining.

- const newUsername = await showPromptDialog(this, {
-   inputLabel: this.hass.localize(
-     "ui.panel.config.users.change_username.new_username"
-   ),
-   confirmText: this.hass.localize(
-     "ui.panel.config.users.change_username.change"
-   ),
-   title: this.hass.localize(
-     "ui.panel.config.users.change_username.caption"
-   ),
-   defaultValue: this._user.username!,
- });
+ const newUsername = await showPromptDialog(this, {
+   inputLabel: this.hass.localize(
+     "ui.panel.config.users.change_username.new_username"
+   ),
+   confirmText: this.hass.localize(
+     "ui.panel.config.users.change_username.change"
+   ),
+   title: this.hass.localize(
+     "ui.panel.config.users.change_username.caption"
+   ),
+   defaultValue: this._user?.username,
+ });
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private async _changeUsername() {
if (!this._user) {
return;
}
const credential = this._user.credentials.find(
(cred) => cred.type === "homeassistant"
);
if (!credential) {
showAlertDialog(this, {
title: "No Home Assistant credentials found.",
});
return;
}
const newUsername = await showPromptDialog(this, {
inputLabel: this.hass.localize(
"ui.panel.config.users.change_username.new_username"
),
confirmText: this.hass.localize(
"ui.panel.config.users.change_username.change"
),
title: this.hass.localize(
"ui.panel.config.users.change_username.caption"
),
defaultValue: this._user.username!,
});
if (newUsername) {
try {
await adminChangeUsername(this.hass, this._user.id, newUsername);
this._params?.refreshUsers();
this._user = { ...this._user, username: newUsername };
showAlertDialog(this, {
text: this.hass.localize(
"ui.panel.config.users.change_username.username_changed"
),
});
} catch (err: any) {
showAlertDialog(this, {
title: this.hass.localize(
"ui.panel.config.users.change_username.failed"
),
text: err.message,
});
}
}
}
private async _changeUsername() {
if (!this._user) {
return;
}
const credential = this._user.credentials.find(
(cred) => cred.type === "homeassistant"
);
if (!credential) {
showAlertDialog(this, {
title: "No Home Assistant credentials found.",
});
return;
}
const newUsername = await showPromptDialog(this, {
inputLabel: this.hass.localize(
"ui.panel.config.users.change_username.new_username"
),
confirmText: this.hass.localize(
"ui.panel.config.users.change_username.change"
),
title: this.hass.localize(
"ui.panel.config.users.change_username.caption"
),
defaultValue: this._user?.username,
});
if (newUsername) {
try {
await adminChangeUsername(this.hass, this._user.id, newUsername);
this._params?.refreshUsers();
this._user = { ...this._user, username: newUsername };
showAlertDialog(this, {
text: this.hass.localize(
"ui.panel.config.users.change_username.username_changed"
),
});
} catch (err: any) {
showAlertDialog(this, {
title: this.hass.localize(
"ui.panel.config.users.change_username.failed"
),
text: err.message,
});
}
}
}
Tools
Biome

[error] 392-392: Forbidden non-null assertion. (lint/style/noNonNullAssertion)


[error] 404-404: Unexpected any. Specify a different type. (lint/suspicious/noExplicitAny)

any disables many type checking rules. Its use should be avoided.

Copy link
Member

@piitaya piitaya left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The UI needs some love but we can improve it in another PR.

@frenck
Copy link
Member

frenck commented Jun 24, 2024

Merging, as the parent PR has been merged.

@frenck frenck merged commit 6a30419 into dev Jun 24, 2024
13 checks passed
@frenck frenck deleted the change-username branch June 24, 2024 16:51
@piitaya piitaya mentioned this pull request Jun 25, 2024
9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants