fix: Deprecate the id field in group (#1987)

This commit is contained in:
Yaodong Yu 2023-06-18 23:33:13 +08:00 committed by GitHub
parent 3562c36817
commit d0ac265c91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 52 additions and 84 deletions

View File

@ -80,7 +80,7 @@ func (c *ApiController) GetGlobalUsers() {
// @router /get-users [get]
func (c *ApiController) GetUsers() {
owner := c.Input().Get("owner")
groupId := c.Input().Get("groupId")
groupName := c.Input().Get("groupName")
limit := c.Input().Get("pageSize")
page := c.Input().Get("p")
field := c.Input().Get("field")
@ -89,8 +89,8 @@ func (c *ApiController) GetUsers() {
sortOrder := c.Input().Get("sortOrder")
if limit == "" || page == "" {
if groupId != "" {
maskedUsers, err := object.GetMaskedUsers(object.GetGroupUsers(groupId))
if groupName != "" {
maskedUsers, err := object.GetMaskedUsers(object.GetGroupUsers(groupName))
if err != nil {
c.ResponseError(err.Error())
return
@ -108,14 +108,14 @@ func (c *ApiController) GetUsers() {
c.ServeJSON()
} else {
limit := util.ParseInt(limit)
count, err := object.GetUserCount(owner, field, value, groupId)
count, err := object.GetUserCount(owner, field, value, groupName)
if err != nil {
c.ResponseError(err.Error())
return
}
paginator := pagination.SetPaginator(c.Ctx, limit, count)
users, err := object.GetPaginationUsers(owner, paginator.Offset(), limit, field, value, sortField, sortOrder, groupId)
users, err := object.GetPaginationUsers(owner, paginator.Offset(), limit, field, value, sortField, sortOrder, groupName)
if err != nil {
c.ResponseError(err.Error())
return

View File

@ -24,11 +24,10 @@ import (
type Group struct {
Owner string `xorm:"varchar(100) notnull pk" json:"owner"`
Name string `xorm:"varchar(100) notnull pk unique" json:"name"`
Name string `xorm:"varchar(100) notnull pk unique index" json:"name"`
CreatedTime string `xorm:"varchar(100)" json:"createdTime"`
UpdatedTime string `xorm:"varchar(100)" json:"updatedTime"`
Id string `xorm:"varchar(100) not null index" json:"id"`
DisplayName string `xorm:"varchar(100)" json:"displayName"`
Manager string `xorm:"varchar(100)" json:"manager"`
ContactEmail string `xorm:"varchar(100)" json:"contactEmail"`
@ -95,12 +94,12 @@ func getGroup(owner string, name string) (*Group, error) {
}
}
func getGroupById(id string) (*Group, error) {
if id == "" {
func getGroupByName(name string) (*Group, error) {
if name == "" {
return nil, nil
}
group := Group{Id: id}
group := Group{Name: name}
existed, err := adapter.Engine.Get(&group)
if err != nil {
return nil, err
@ -135,10 +134,6 @@ func UpdateGroup(id string, group *Group) (bool, error) {
}
func AddGroup(group *Group) (bool, error) {
if group.Id == "" {
group.Id = util.GenerateId()
}
affected, err := adapter.Engine.Insert(group)
if err != nil {
return false, err
@ -164,7 +159,7 @@ func DeleteGroup(group *Group) (bool, error) {
return false, err
}
if count, err := adapter.Engine.Where("parent_id = ?", group.Id).Count(&Group{}); err != nil {
if count, err := adapter.Engine.Where("parent_id = ?", group.Name).Count(&Group{}); err != nil {
return false, err
} else if count > 0 {
return false, errors.New("group has children group")
@ -183,7 +178,7 @@ func DeleteGroup(group *Group) (bool, error) {
return false, err
}
if _, err := session.Delete(&UserGroupRelation{GroupId: group.Id}); err != nil {
if _, err := session.Delete(&UserGroupRelation{GroupName: group.Name}); err != nil {
session.Rollback()
return false, err
}
@ -215,9 +210,8 @@ func ConvertToTreeData(groups []*Group, parentId string) []*Group {
Key: group.Name,
Type: group.Type,
Owner: group.Owner,
Id: group.Id,
}
children := ConvertToTreeData(groups, group.Id)
children := ConvertToTreeData(groups, group.Name)
if len(children) > 0 {
node.Children = children
}

View File

@ -76,7 +76,6 @@ type User struct {
SignupApplication string `xorm:"varchar(100)" json:"signupApplication"`
Hash string `xorm:"varchar(100)" json:"hash"`
PreHash string `xorm:"varchar(100)" json:"preHash"`
Groups []string `xorm:"varchar(1000)" json:"groups"`
AccessKey string `xorm:"varchar(100)" json:"accessKey"`
AccessSecret string `xorm:"varchar(100)" json:"accessSecret"`
@ -167,6 +166,7 @@ type User struct {
Roles []*Role `json:"roles"`
Permissions []*Permission `json:"permissions"`
Groups []string `xorm:"groups varchar(1000)" json:"groups"`
LastSigninWrongTime string `xorm:"varchar(100)" json:"lastSigninWrongTime"`
SigninWrongTimes int `json:"signinWrongTimes"`
@ -725,7 +725,7 @@ func DeleteUser(user *User) (bool, error) {
return false, err
}
affected, err = deleteRelationByUser(user.Id)
affected, err = DeleteRelationByUserId(user.Id)
if err != nil {
return false, err
}

View File

@ -10,15 +10,15 @@ import (
)
type UserGroupRelation struct {
UserId string `xorm:"varchar(100) notnull pk" json:"userId"`
GroupId string `xorm:"varchar(100) notnull pk" json:"groupId"`
UserId string `xorm:"varchar(100) notnull pk" json:"userId"`
GroupName string `xorm:"varchar(100) notnull pk" json:"groupName"`
CreatedTime string `xorm:"created" json:"createdTime"`
UpdatedTime string `xorm:"updated" json:"updatedTime"`
}
func updateUserGroupRelation(session *xorm.Session, user *User) (int64, error) {
physicalGroupCount, err := session.Where("type = ?", "Physical").In("id", user.Groups).Count(Group{})
physicalGroupCount, err := session.In("name", user.Groups).Count(Group{Type: "Physical"})
if err != nil {
return 0, err
}
@ -27,7 +27,7 @@ func updateUserGroupRelation(session *xorm.Session, user *User) (int64, error) {
}
groups := []*Group{}
err = session.In("id", user.Groups).Find(&groups)
err = session.In("name", user.Groups).Find(&groups)
if err != nil {
return 0, err
}
@ -42,7 +42,7 @@ func updateUserGroupRelation(session *xorm.Session, user *User) (int64, error) {
relations := []*UserGroupRelation{}
for _, group := range groups {
relations = append(relations, &UserGroupRelation{UserId: user.Id, GroupId: group.Id})
relations = append(relations, &UserGroupRelation{UserId: user.Id, GroupName: group.Name})
}
if len(relations) == 0 {
return 1, nil
@ -76,35 +76,35 @@ func RemoveUserFromGroup(owner, name, groupId string) (bool, error) {
return true, nil
}
func deleteUserGroupRelation(session *xorm.Session, userId, groupId string) (int64, error) {
affected, err := session.ID(core.PK{userId, groupId}).Delete(&UserGroupRelation{})
func DeleteUserGroupRelation(userId, groupId string) (int64, error) {
affected, err := adapter.Engine.ID(core.PK{userId, groupId}).Delete(&UserGroupRelation{})
return affected, err
}
func deleteRelationByUser(id string) (int64, error) {
func DeleteRelationByUserId(id string) (int64, error) {
affected, err := adapter.Engine.Delete(&UserGroupRelation{UserId: id})
return affected, err
}
func GetGroupUserCount(id string, field, value string) (int64, error) {
group, err := GetGroup(id)
func GetGroupUserCount(groupName string, field, value string) (int64, error) {
group, err := getGroupByName(groupName)
if group == nil || err != nil {
return 0, err
}
if field == "" && value == "" {
return adapter.Engine.Count(UserGroupRelation{GroupId: group.Id})
return adapter.Engine.Count(UserGroupRelation{GroupName: group.Name})
} else {
return adapter.Engine.Table("user").
Join("INNER", []string{"user_group_relation", "r"}, "user.id = r.user_id").
Where("r.group_id = ?", group.Id).
Where("r.group_name = ?", group.Name).
And(fmt.Sprintf("user.%s LIKE ?", util.CamelToSnakeCase(field)), "%"+value+"%").
Count()
}
}
func GetPaginationGroupUsers(id string, offset, limit int, field, value, sortField, sortOrder string) ([]*User, error) {
group, err := GetGroup(id)
func GetPaginationGroupUsers(groupName string, offset, limit int, field, value, sortField, sortOrder string) ([]*User, error) {
group, err := getGroupByName(groupName)
if group == nil || err != nil {
return nil, err
}
@ -112,7 +112,7 @@ func GetPaginationGroupUsers(id string, offset, limit int, field, value, sortFie
users := []*User{}
session := adapter.Engine.Table("user").
Join("INNER", []string{"user_group_relation", "r"}, "user.id = r.user_id").
Where("r.group_id = ?", group.Id)
Where("r.group_name = ?", group.Name)
if offset != -1 && limit != -1 {
session.Limit(limit, offset)
@ -139,16 +139,16 @@ func GetPaginationGroupUsers(id string, offset, limit int, field, value, sortFie
return users, nil
}
func GetGroupUsers(id string) ([]*User, error) {
group, err := GetGroup(id)
func GetGroupUsers(groupName string) ([]*User, error) {
group, err := getGroupByName(groupName)
if group == nil || err != nil {
return []*User{}, err
}
users := []*User{}
err = adapter.Engine.Table("user_group_relation").Join("INNER", []string{"user", "u"}, "user_group_relation.user_id = u.id").
Where("user_group_relation.group_id = ?", group.Id).
Find(&users)
err = adapter.Engine.Table("user").
Join("INNER", []string{"user_group_relation", "r"}, "user.id = r.user_id").
Where("r.group_name = ?", group.Name).Find(&users)
if err != nil {
return nil, err
}

View File

@ -44,11 +44,6 @@ class GroupEditPage extends React.Component {
GroupBackend.getGroup(this.state.organizationName, this.state.groupName)
.then((res) => {
if (res.status === "ok") {
if (res.data === null) {
this.props.history.push("/404");
return;
}
this.setState({
group: res.data,
});
@ -96,12 +91,12 @@ class GroupEditPage extends React.Component {
}
getParentIdOptions() {
const groups = this.state.groups.filter((group) => group.id !== this.state.group.id);
const groups = this.state.groups.filter((group) => group.name !== this.state.group.name);
const organization = this.state.organizations.find((organization) => organization.name === this.state.group.owner);
if (organization !== undefined) {
groups.push({id: organization.name, displayName: organization.displayName});
groups.push({name: organization.name, displayName: organization.displayName});
}
return groups.map((group) => ({label: group.displayName, value: group.id}));
return groups.map((group) => ({label: group.displayName, value: group.name}));
}
renderGroup() {
@ -136,7 +131,7 @@ class GroupEditPage extends React.Component {
{Setting.getLabel(i18next.t("general:Name"), i18next.t("general:Name - Tooltip"))} :
</Col>
<Col span={22} >
<Input value={this.state.group.name} onChange={e => {
<Input disabled={true} value={this.state.group.name} onChange={e => {
this.updateGroupField("name", e.target.value);
}} />
</Col>

View File

@ -185,7 +185,7 @@ class GroupListPage extends BaseListPage {
{record.parentId}
</Link>;
}
const parentGroup = this.state.groups.find((group) => group.id === text);
const parentGroup = this.state.groups.find((group) => group.name === text);
if (parentGroup === undefined) {
return "";
}

View File

@ -30,7 +30,6 @@ class GroupTreePage extends React.Component {
owner: Setting.isAdminUser(this.props.account) ? "" : this.props.account.owner,
organizationName: props.organizationName !== undefined ? props.organizationName : props.match.params.organizationName,
groupName: this.props.match?.params.groupName,
groupId: undefined,
treeData: [],
selectedKeys: [this.props.match?.params.groupName],
};
@ -55,7 +54,6 @@ class GroupTreePage extends React.Component {
if (res.status === "ok") {
this.setState({
treeData: res.data,
groupId: this.findNodeId({children: res.data}, this.state.groupName),
});
} else {
Setting.showMessage("error", res.msg);
@ -63,26 +61,10 @@ class GroupTreePage extends React.Component {
});
}
findNodeId(node, targetName) {
if (node.key === targetName) {
return node.id;
}
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
const result = this.findNodeId(node.children[i], targetName);
if (result) {
return result;
}
}
}
return null;
}
setTreeTitle(treeData) {
const haveChildren = Array.isArray(treeData.children) && treeData.children.length > 0;
const isSelected = this.state.groupName === treeData.key;
return {
id: treeData.id,
key: treeData.key,
title: <Space>
{treeData.type === "Physical" ? <UsergroupAddOutlined /> : <HolderOutlined />}
@ -201,7 +183,6 @@ class GroupTreePage extends React.Component {
this.setState({
selectedKeys: selectedKeys,
groupName: info.node.key,
groupId: info.node.id,
});
this.props.history.push(`/trees/${this.state.organizationName}/${info.node.key}`);
};
@ -257,7 +238,7 @@ class GroupTreePage extends React.Component {
updatedTime: moment().format(),
displayName: `New Group - ${randomName}`,
type: "Virtual",
parentId: isRoot ? this.state.organizationName : this.state.groupId,
parentId: isRoot ? this.state.organizationName : this.state.groupName,
isTopGroup: isRoot,
isEnabled: true,
};
@ -300,8 +281,7 @@ class GroupTreePage extends React.Component {
onClick={() => {
this.setState({
selectedKeys: [],
groupName: null,
groupId: undefined,
groupName: undefined,
});
this.props.history.push(`/trees/${this.state.organizationName}`);
}}
@ -323,7 +303,6 @@ class GroupTreePage extends React.Component {
<UserListPage
organizationName={this.state.organizationName}
groupName={this.state.groupName}
groupId={this.state.groupId}
{...this.props}
/>
</Col>

View File

@ -309,7 +309,7 @@ class UserEditPage extends React.Component {
</Col>
<Col span={22} >
<Select virtual={false} mode="multiple" style={{width: "100%"}} disabled={disabled} value={this.state.user.groups ?? []} onChange={(value => {
if (this.state.groups?.filter(group => value.includes(group.id))
if (this.state.groups?.filter(group => value.includes(group.name))
.filter(group => group.type === "Physical").length > 1) {
Setting.showMessage("error", i18next.t("general:You can only select one physical group"));
return;
@ -319,7 +319,7 @@ class UserEditPage extends React.Component {
})}
>
{
this.state.groups?.map((group) => <Option key={group.id} value={group.id}>
this.state.groups?.map((group) => <Option key={group.name} value={group.name}>
<Space>
{group.type === "Physical" ? <UsergroupAddOutlined /> : <HolderOutlined />}
{group.displayName}

View File

@ -75,7 +75,7 @@ class UserListPage extends BaseListPage {
phone: Setting.getRandomNumber(),
countryCode: this.state.organization.countryCodes?.length > 0 ? this.state.organization.countryCodes[0] : "",
address: [],
groups: this.props.groupId ? [this.props.groupId] : [],
groups: this.props.groupName ? [this.props.groupName] : [],
affiliation: "Example Inc.",
tag: "staff",
region: "",
@ -126,8 +126,8 @@ class UserListPage extends BaseListPage {
removeUserFromGroup(i) {
const user = this.state.data[i];
const group = this.props.groupId;
UserBackend.removeUserFromGroup({groupId: group, owner: user.owner, name: user.name})
const group = this.props.groupName;
UserBackend.removeUserFromGroup({groupName: group, owner: user.owner, name: user.name})
.then((res) => {
if (res.status === "ok") {
Setting.showMessage("success", i18next.t("general:Successfully removed"));
@ -396,7 +396,7 @@ class UserListPage extends BaseListPage {
width: "190px",
fixed: (Setting.isMobile()) ? "false" : "right",
render: (text, record, index) => {
const isTreePage = this.props.groupId !== undefined;
const isTreePage = this.props.groupName !== undefined;
const disabled = (record.owner === this.props.account.owner && record.name === this.props.account.name) || (record.owner === "built-in" && record.name === "admin");
return (
<Space>
@ -483,7 +483,7 @@ class UserListPage extends BaseListPage {
});
} else {
(this.props.groupName ?
UserBackend.getUsers(this.state.organizationName, params.pagination.current, params.pagination.pageSize, field, value, sortField, sortOrder, `${this.state.organizationName}/${this.props.groupName}`) :
UserBackend.getUsers(this.state.organizationName, params.pagination.current, params.pagination.pageSize, field, value, sortField, sortOrder, this.props.groupName) :
UserBackend.getUsers(this.state.organizationName, params.pagination.current, params.pagination.pageSize, field, value, sortField, sortOrder))
.then((res) => {
this.setState({

View File

@ -25,8 +25,8 @@ export function getGlobalUsers(page, pageSize, field = "", value = "", sortField
}).then(res => res.json());
}
export function getUsers(owner, page = "", pageSize = "", field = "", value = "", sortField = "", sortOrder = "", groupId = "") {
return fetch(`${Setting.ServerUrl}/api/get-users?owner=${owner}&p=${page}&pageSize=${pageSize}&field=${field}&value=${value}&sortField=${sortField}&sortOrder=${sortOrder}&groupId=${groupId}`, {
export function getUsers(owner, page = "", pageSize = "", field = "", value = "", sortField = "", sortOrder = "", groupName = "") {
return fetch(`${Setting.ServerUrl}/api/get-users?owner=${owner}&p=${page}&pageSize=${pageSize}&field=${field}&value=${value}&sortField=${sortField}&sortOrder=${sortOrder}&groupName=${groupName}`, {
method: "GET",
credentials: "include",
headers: {
@ -223,11 +223,11 @@ export function checkUserPassword(values) {
}).then(res => res.json());
}
export function removeUserFromGroup({owner, name, groupId}) {
export function removeUserFromGroup({owner, name, groupName}) {
const formData = new FormData();
formData.append("owner", owner);
formData.append("name", name);
formData.append("groupId", groupId);
formData.append("groupName", groupName);
return fetch(`${Setting.ServerUrl}/api/remove-user-from-group`, {
method: "POST",
credentials: "include",