XnLemon commented on code in PR #1087: URL: https://github.com/apache/dubbo-go-pixiu/pull/1087#discussion_r4556162148
########## admin/web/src/features/profile/AccountPage.tsx: ########## @@ -0,0 +1,421 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import React, { useEffect, useState } from 'react' +import { profileApi, type UserInfo } from '../../services/profile-api' + +type Language = 'zh' | 'en' +type Feedback = Readonly<{ kind: 'error' | 'success'; text: string }> +type AccountCopy = Readonly<{ + eyebrow: string + title: string + description: string + accountInformation: string + signedInUser: string + username: string + role: string + administrator: string + user: string + loadError: string + registerAdministrator: string + registerDescription: string + password: string + confirmPassword: string + accountFieldsRequired: string + accountPasswordLength: string + accountPasswordsMismatch: string + accountCreated: string + accountCreateError: string + creatingAccount: string + createAccount: string + changePassword: string + changePasswordDescription: string + currentPassword: string + newPassword: string + confirmNewPassword: string + passwordFieldsRequired: string + newPasswordLength: string + newPasswordsMismatch: string + passwordMustChange: string + passwordUpdated: string + passwordUpdateError: string + updatingPassword: string + updatePassword: string +}> + +const accountCopy: Record<Language, AccountCopy> = { + zh: { + eyebrow: 'ACCOUNT CENTER', + title: '个人中心', + description: '查看账号信息并修改登录密码。', + accountInformation: '账号信息', + signedInUser: '当前登录账号', + username: '用户名', + role: '角色', + administrator: '管理员', + user: '用户', + loadError: '无法加载账号信息', + registerAdministrator: '注册管理员账号', + registerDescription: '仅管理员可以创建账号;新账号也将获得管理员角色。', + password: '密码', + confirmPassword: '确认密码', + accountFieldsRequired: '请填写所有新账号字段', + accountPasswordLength: '密码长度需要为 8 到 128 个字符', + accountPasswordsMismatch: '两次输入的密码不一致', // NOSONAR -- localized validation message. + accountCreated: '管理员账号已创建', + accountCreateError: '无法创建账号', + creatingAccount: '创建中…', + createAccount: '创建账号', + changePassword: '修改密码', + changePasswordDescription: '输入当前密码后即可设置新密码。', // NOSONAR -- localized help text. + currentPassword: '当前密码', + newPassword: '新密码', + confirmNewPassword: '确认新密码', + passwordFieldsRequired: '请填写所有密码字段', // NOSONAR -- localized validation message. + newPasswordLength: '新密码长度需要为 8 到 128 个字符', + newPasswordsMismatch: '两次输入的新密码不一致', // NOSONAR -- localized validation message. + passwordMustChange: '新密码不能与当前密码相同', // NOSONAR -- localized validation message. + passwordUpdated: '密码已更新', + passwordUpdateError: '无法修改密码', + updatingPassword: '修改中…', + updatePassword: '更新密码', + }, + en: { + eyebrow: 'ACCOUNT', + title: 'Account', + description: 'View your account and update your password.', + accountInformation: 'Account information', + signedInUser: 'Signed-in user', + username: 'Username', + role: 'Role', + administrator: 'Administrator', + user: 'User', + loadError: 'Unable to load account information', + registerAdministrator: 'Register administrator', + registerDescription: + 'Only administrators can create accounts. New accounts also receive the administrator role.', + password: 'Password', + confirmPassword: 'Confirm password', + accountFieldsRequired: 'Complete all account fields', + accountPasswordLength: 'Use a password between 8 and 128 characters', + accountPasswordsMismatch: 'The passwords do not match', + accountCreated: 'Administrator account created', + accountCreateError: 'Unable to create account', + creatingAccount: 'Creating…', + createAccount: 'Create account', + changePassword: 'Change password', + changePasswordDescription: 'Enter your current password to save a new one.', + currentPassword: 'Current password', + newPassword: 'New password', + confirmNewPassword: 'Confirm new password', + passwordFieldsRequired: 'Complete all password fields', + newPasswordLength: 'Use a new password between 8 and 128 characters', + newPasswordsMismatch: 'The new passwords do not match', + passwordMustChange: 'Choose a password different from the current one', + passwordUpdated: 'Password updated', + passwordUpdateError: 'Unable to update password', + updatingPassword: 'Updating…', // NOSONAR -- localized button label. + updatePassword: 'Update password', + }, +} + +type AccountPageProps = Readonly<{ language: Language }> + +export function AccountPage({ language }: AccountPageProps) { + const copy = accountCopy[language] + const { user, loadError, loading } = useAccountSession(language) + const gridClassName = user?.role === 1 ? 'account-grid account-grid-admin' : 'account-grid' + + return ( + <div className="account-page"> + <div className="page-head"> + <div> + <p className="eyebrow">{copy.eyebrow}</p> + <h1>{copy.title}</h1> + <p className="muted">{copy.description}</p> + </div> + </div> + + <div className={gridClassName}> + <div className="account-column account-overview-column"> + <AccountInfoCard copy={copy} user={user} loadError={loadError} loading={loading} /> + {user?.role === 1 && <RegistrationForm copy={copy} />} + </div> + <div className="account-column account-password-column"> + <PasswordForm copy={copy} /> + </div> + </div> + </div> + ) +} + +function useAccountSession(language: Language) { + const [user, setUser] = useState<UserInfo | null>(null) + const [loadError, setLoadError] = useState('') + const [loading, setLoading] = useState(true) + + useEffect(() => { + let active = true + profileApi + .session() + .then((info) => { + if (active) setUser(info) + }) + .catch((error: unknown) => { + if (active) setLoadError(errorMessage(error, accountCopy[language].loadError)) + }) + .finally(() => { + if (active) setLoading(false) + }) + return () => { + active = false + } + }, [language]) + + return { user, loadError, loading } +} + +type AccountInfoCardProps = Readonly<{ + copy: AccountCopy + user: UserInfo | null + loadError: string + loading: boolean +}> + +function AccountInfoCard({ copy, user, loadError, loading }: AccountInfoCardProps) { + const roleLabel = user?.role === 1 ? copy.administrator : copy.user + + return ( + <section className="panel account-card account-info-card"> + <div className="panel-head"> + <div> + <h2>{copy.accountInformation}</h2> + <span>{copy.signedInUser}</span> + </div> + </div> + {loading && <div className="loading-skeleton" />} + {!loading && loadError && <div className="account-feedback error">{loadError}</div>} + {!loading && !loadError && ( + <dl className="account-details"> + <div> + <dt>{copy.username}</dt> + <dd>{user?.username || '—'}</dd> + </div> + <div> + <dt>{copy.role}</dt> + <dd>{roleLabel}</dd> + </div> + </dl> + )} + </section> + ) +} + +type AccountFormProps = Readonly<{ copy: AccountCopy }> + +function RegistrationForm({ copy }: AccountFormProps) { + const [username, setUsername] = useState('') + const [password, setPassword] = useState('') + const [confirmation, setConfirmation] = useState('') + const [feedback, setFeedback] = useState<Feedback | null>(null) + const [registering, setRegistering] = useState(false) + + const submit = async (event: React.FormEvent) => { + event.preventDefault() + setFeedback(null) + const validationMessage = validateRegistration(username, password, confirmation, copy) + if (validationMessage) { + setFeedback({ kind: 'error', text: validationMessage }) + return + } + + setRegistering(true) + try { + await profileApi.register({ username: username.trim(), password }) + setUsername('') + setPassword('') + setConfirmation('') + setFeedback({ kind: 'success', text: copy.accountCreated }) + } catch (error: unknown) { + setFeedback({ kind: 'error', text: errorMessage(error, copy.accountCreateError) }) + } finally { + setRegistering(false) + } + } Review Comment: Fixed in `01990e7` (`fix(admin-ui): omit username request header`). The shared HTTP client no longer sends the session username in a request header; authenticated identity comes from the JWT. I added a regression test using a non-ASCII username, and the frontend test suite passes. <details><summary>中文</summary> 已在 `01990e7` 修复。共享 HTTP 客户端不再把 session 用户名放入请求头,身份由 JWT 提供。新增了中文用户名回归测试,前端测试套件已通过。 </details> ########## admin/dao/impl/guest_mysql_test.go: ########## @@ -0,0 +1,174 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package impl + +import ( + "database/sql" + "fmt" + "os" + "strings" + "sync" + "testing" + "time" +) + +import ( + "github.com/go-sql-driver/mysql" +) + +func TestRegisterConcurrentUsernameIsUnique(t *testing.T) { + db := newGuestMySQLTestDB(t) + createGuestTestTables(t, db) + + dao := &GuestDao{db: db} + if err := dao.EnsureUsernameUniqueIndex(); err != nil { + t.Fatalf("EnsureUsernameUniqueIndex() error = %v", err) + } + + const attempts = 8 + start := make(chan struct{}) + results := make(chan error, attempts) + var workers sync.WaitGroup + workers.Add(attempts) + for i := 0; i < attempts; i++ { + go func() { + defer workers.Done() + <-start + results <- dao.Register("same-user", "hashed-password") + }() + } + close(start) + workers.Wait() + close(results) + + successes, duplicates := 0, 0 + for err := range results { + switch { + case err == nil: + successes++ + case err.Error() == "user already exists": + duplicates++ + default: + t.Errorf("Register() error = %v", err) + } + } + if successes != 1 || duplicates != attempts-1 { + t.Fatalf("registration results: successes = %d, duplicates = %d; want 1 and %d", successes, duplicates, attempts-1) + } + + var userCount, roleCount int + if err := db.QueryRow("SELECT COUNT(*) FROM pixiu_user WHERE username = ?", "same-user").Scan(&userCount); err != nil { + t.Fatal(err) + } + if err := db.QueryRow("SELECT COUNT(*) FROM pixiu_user_role").Scan(&roleCount); err != nil { + t.Fatal(err) + } + if userCount != 1 || roleCount != 1 { + t.Fatalf("persisted rows: users = %d, roles = %d; want 1 each", userCount, roleCount) + } +} + +func TestEnsureUsernameUniqueIndexLeavesExistingDuplicatesUntouched(t *testing.T) { + db := newGuestMySQLTestDB(t) + createGuestTestTables(t, db) + if _, err := db.Exec("INSERT INTO pixiu_user (username, password) VALUES (?, ?), (?, ?)", "duplicate", "one", "duplicate", "two"); err != nil { + t.Fatal(err) + } + + err := (&GuestDao{db: db}).EnsureUsernameUniqueIndex() + if err == nil || !strings.Contains(err.Error(), `duplicate username "duplicate" exists`) { + t.Fatalf("EnsureUsernameUniqueIndex() error = %v, want duplicate username error", err) + } + + var count int + if err := db.QueryRow("SELECT COUNT(*) FROM pixiu_user WHERE username = ?", "duplicate").Scan(&count); err != nil { + t.Fatal(err) + } + if count != 2 { + t.Fatalf("duplicate rows after failed migration = %d, want 2 untouched rows", count) + } +} + +func newGuestMySQLTestDB(t *testing.T) *sql.DB { + t.Helper() + dsn := os.Getenv("PIXIU_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("set PIXIU_TEST_MYSQL_DSN to a MySQL account allowed to create and drop databases") Review Comment: Agreed that the MySQL integration tests need to run in CI for these SQL paths to have execution evidence. Per the agreed scope, I am deferring the CI wiring until PR #1085's Admin CI changes are completed. After that, I will add a MySQL service and `PIXIU_TEST_MYSQL_DSN` configuration, then verify the tests run rather than skip. Until that follow-up lands, this finding remains open and the tests are not claimed as CI-validated. <details><summary>中文</summary> 同意这些 SQL 路径需要在 CI 中实际执行,才能有有效的运行证据。按此前约定,等 PR #1085 的 Admin CI 改动完成后再接入 MySQL service 和 `PIXIU_TEST_MYSQL_DSN`,并确认测试实际运行而非跳过。在后续改动完成前,这条问题仍未解决,也不会把这些测试描述为已通过 CI 验证。 </details> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
