harbor/src/common/dao/role.go

93 lines
2.1 KiB
Go
Raw Normal View History

2017-04-13 12:54:58 +02:00
// Copyright (c) 2017 VMware, Inc. All Rights Reserved.
//
// Licensed 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.
2016-02-26 11:54:14 +01:00
2016-02-01 12:59:10 +01:00
package dao
import (
"fmt"
"github.com/astaxie/beego/orm"
"github.com/goharbor/harbor/src/common/models"
2016-02-01 12:59:10 +01:00
)
// GetUserProjectRoles returns roles that the user has according to the project.
2018-02-06 03:59:49 +01:00
func GetUserProjectRoles(userID int, projectID int64, entityType string) ([]models.Role, error) {
2016-02-01 12:59:10 +01:00
2016-05-20 10:36:10 +02:00
o := GetOrmer()
2016-02-01 12:59:10 +01:00
2016-03-28 09:34:41 +02:00
sql := `select *
from role
where role_id =
(
select role
from project_member
2018-02-06 03:59:49 +01:00
where project_id = ? and entity_id = ? and entity_type = 'u'
2016-03-28 09:34:41 +02:00
)`
2016-02-01 12:59:10 +01:00
var roleList []models.Role
2016-03-29 06:09:27 +02:00
_, err := o.Raw(sql, projectID, userID).QueryRows(&roleList)
2016-02-01 12:59:10 +01:00
if err != nil {
return nil, err
}
return roleList, nil
}
// IsAdminRole returns whether the user is admin.
func IsAdminRole(userIDOrUsername interface{}) (bool, error) {
u := models.User{}
switch v := userIDOrUsername.(type) {
case int:
u.UserID = v
case string:
u.Username = v
default:
return false, fmt.Errorf("invalid parameter, only int and string are supported: %v", userIDOrUsername)
}
2016-03-28 09:34:41 +02:00
2016-04-15 15:48:28 +02:00
if u.UserID == NonExistUserID && len(u.Username) == 0 {
return false, nil
}
user, err := GetUser(u)
2016-02-01 12:59:10 +01:00
if err != nil {
return false, err
}
2016-03-28 09:34:41 +02:00
if user == nil {
return false, nil
}
return user.HasAdminRole, nil
2016-03-28 09:34:41 +02:00
}
// GetRoleByID ...
func GetRoleByID(id int) (*models.Role, error) {
2016-05-20 10:36:10 +02:00
o := GetOrmer()
sql := `select *
from role
where role_id = ?`
var role models.Role
if err := o.Raw(sql, id).QueryRow(&role); err != nil {
if err == orm.ErrNoRows {
return nil, nil
}
return nil, err
}
return &role, nil
}