feat(oauth2): add default role assignment for new OAuth2 users (#688)

- Add default role assignment logic in OAuth2 login flow
- Import getStringValue and getUserRoles utilities
- Validate default role exists in system before assignment
- Use ON CONFLICT DO NOTHING to preserve existing user roles
- Add proper error handling for role assignment failures
This commit is contained in:
Dream Hunter
2025-07-14 23:55:36 +08:00
committed by GitHub
parent 1303b0f2a9
commit c96d180591
2 changed files with 17 additions and 1 deletions

View File

@@ -4,6 +4,7 @@
## main(v1.0.1)
- feat: |UI| 增加极简模式主页, 可在 `外观` 中切换
- fix: 修复 oauth2 登录时default role 不生效的问题
## v1.0.0

View File

@@ -2,7 +2,7 @@ import { Context } from 'hono';
import { Jwt } from 'hono/utils/jwt'
import i18n from '../i18n';
import { getJsonSetting } from '../utils';
import { getJsonSetting, getStringValue, getUserRoles } from '../utils';
import { UserOauth2Settings } from '../models';
import { CONSTANTS } from '../constants';
@@ -110,6 +110,21 @@ export default {
if (!user_id) {
return c.text(msgs.UserNotFoundMsg, 400)
}
const defaultRole = getStringValue(c.env.USER_DEFAULT_ROLE);
if (!defaultRole) return c.json({ success: true })
const user_roles = getUserRoles(c);
if (!user_roles.find((r) => r.role === defaultRole)) {
return c.text(msgs.InvalidUserDefaultRoleMsg, 500);
}
// update user roles
const { success: success2 } = await c.env.DB.prepare(
`INSERT INTO user_roles (user_id, role_text)`
+ ` VALUES (?, ?)`
+ ` ON CONFLICT(user_id) DO NOTHING`
).bind(user_id, defaultRole).run();
if (!success2) {
return c.text(msgs.FailedUpdateUserDefaultRoleMsg, 500);
}
// create jwt
const jwt = await Jwt.sign({
user_email: email,