code refactor (#1786)

* implement LDAP mock client

Signed-off-by: hongming <talonwan@yunify.com>

* update

Signed-off-by: hongming <talonwan@yunify.com>

* update

Signed-off-by: hongming <talonwan@yunify.com>

* resolve conflict

Signed-off-by: hongming <talonwan@yunify.com>
This commit is contained in:
hongming
2020-02-24 15:39:36 +08:00
committed by GitHub
parent 96aee0e60b
commit abf9fee845
39 changed files with 1338 additions and 2467 deletions

View File

@@ -1,18 +0,0 @@
/*
Copyright 2019 The KubeSphere Authors.
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.
*/
package iam

View File

@@ -1,69 +0,0 @@
/*
Copyright 2019 The KubeSphere Authors.
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.
*/
package iam
import (
"fmt"
"github.com/emicklei/go-restful"
iamv1alpha2 "kubesphere.io/kubesphere/pkg/api/iam/v1alpha2"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/models/iam"
"kubesphere.io/kubesphere/pkg/server/errors"
"kubesphere.io/kubesphere/pkg/utils/iputil"
"net/http"
)
type OAuthRequest struct {
GrantType string `json:"grant_type"`
Username string `json:"username,omitempty" description:"username"`
Password string `json:"password,omitempty" description:"password"`
RefreshToken string `json:"refresh_token,omitempty"`
}
func OAuth(req *restful.Request, resp *restful.Response) {
authRequest := &OAuthRequest{}
err := req.ReadEntity(authRequest)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
var result *models.AuthGrantResponse
switch authRequest.GrantType {
case "refresh_token":
result, err = iam.RefreshToken(authRequest.RefreshToken)
case "password":
ip := iputil.RemoteIp(req.Request)
result, err = iam.PasswordCredentialGrant(authRequest.Username, authRequest.Password, ip)
default:
resp.Header().Set("WWW-Authenticate", "grant_type is not supported")
resp.WriteHeaderAndEntity(http.StatusUnauthorized, errors.Wrap(fmt.Errorf("grant_type is not supported")))
return
}
if err != nil {
resp.Header().Set("WWW-Authenticate", err.Error())
resp.WriteHeaderAndEntity(http.StatusUnauthorized, errors.Wrap(err))
return
}
resp.WriteEntity(result)
}

View File

@@ -1,201 +0,0 @@
/*
Copyright 2019 The KubeSphere Authors.
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.
*/
package iam
import (
"fmt"
"net/http"
"regexp"
"strings"
"github.com/emicklei/go-restful"
"github.com/go-ldap/ldap"
"kubesphere.io/kubesphere/pkg/models"
"kubesphere.io/kubesphere/pkg/models/iam"
"kubesphere.io/kubesphere/pkg/server/errors"
)
func CreateGroup(req *restful.Request, resp *restful.Response) {
var group models.Group
err := req.ReadEntity(&group)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
if !regexp.MustCompile("[a-z0-9]([-a-z0-9]*[a-z0-9])?").MatchString(group.Name) {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.New(fmt.Sprintf("incalid group name %s", group)))
return
}
created, err := iam.CreateGroup(&group)
if err != nil {
if ldap.IsErrorWithCode(err, ldap.LDAPResultEntryAlreadyExists) {
resp.WriteHeaderAndEntity(http.StatusConflict, errors.Wrap(err))
} else {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
}
return
}
resp.WriteAsJson(created)
}
func DeleteGroup(req *restful.Request, resp *restful.Response) {
path := req.PathParameter("group")
if path == "" {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(fmt.Errorf("group path must not be null")))
return
}
err := iam.DeleteGroup(path)
if err != nil {
if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
resp.WriteHeaderAndEntity(http.StatusNotFound, errors.Wrap(err))
return
}
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(errors.None)
}
func UpdateGroup(req *restful.Request, resp *restful.Response) {
groupPathInPath := req.PathParameter("group")
var group models.Group
req.ReadEntity(&group)
if groupPathInPath != group.Path {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(fmt.Errorf("the path of group (%s) does not match the path on the URL (%s)", group.Path, groupPathInPath)))
return
}
edited, err := iam.UpdateGroup(&group)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(edited)
}
func DescribeGroup(req *restful.Request, resp *restful.Response) {
path := req.PathParameter("group")
group, err := iam.DescribeGroup(path)
if err != nil {
if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
resp.WriteHeaderAndEntity(http.StatusNotFound, errors.Wrap(err))
} else {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
}
return
}
resp.WriteAsJson(group)
}
func ListGroupUsers(req *restful.Request, resp *restful.Response) {
path := req.PathParameter("group")
group, err := iam.DescribeGroup(path)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
users := make([]*iam.User, 0)
modify := false
for i := 0; i < len(group.Members); i++ {
name := group.Members[i]
user, err := iam.GetUserInfo(name)
if err != nil {
if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
group.Members = append(group.Members[:i], group.Members[i+1:]...)
i--
modify = true
continue
} else {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
}
users = append(users, user)
}
if modify {
go iam.UpdateGroup(group)
}
resp.WriteAsJson(users)
}
func ListGroups(req *restful.Request, resp *restful.Response) {
array := req.QueryParameter("path")
if array == "" {
groups, err := iam.ChildList("")
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(groups)
} else {
paths := strings.Split(array, ",")
groups := make([]*models.Group, 0)
for _, v := range paths {
path := strings.TrimSpace(v)
group, err := iam.DescribeGroup(path)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
groups = append(groups, group)
}
resp.WriteAsJson(groups)
}
}

View File

@@ -1,259 +0,0 @@
/*
Copyright 2019 The KubeSphere Authors.
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.
*/
package iam
import (
"fmt"
"k8s.io/klog"
"kubesphere.io/kubesphere/pkg/server/params"
"net/http"
"net/mail"
"strings"
"github.com/emicklei/go-restful"
"github.com/go-ldap/ldap"
rbacv1 "k8s.io/api/rbac/v1"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/models/iam"
"kubesphere.io/kubesphere/pkg/server/errors"
)
func DeleteUser(req *restful.Request, resp *restful.Response) {
username := req.PathParameter("user")
operator := req.HeaderParameter(constants.UserNameHeader)
if operator == username {
err := fmt.Errorf("cannot delete yourself")
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusForbidden, errors.Wrap(err))
return
}
err := iam.DeleteUser(username)
if err != nil {
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(errors.None)
}
func UpdateUser(req *restful.Request, resp *restful.Response) {
usernameInPath := req.PathParameter("user")
usernameInHeader := req.HeaderParameter(constants.UserNameHeader)
var user iam.User
err := req.ReadEntity(&user)
if err != nil {
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
if usernameInPath != user.Username {
err = fmt.Errorf("the name of user (%s) does not match the name on the URL (%s)", user.Username, usernameInPath)
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
if _, err = mail.ParseAddress(user.Email); err != nil {
err = fmt.Errorf("invalid email: %s", user.Email)
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
if user.Password != "" && len(user.Password) < 6 {
err = fmt.Errorf("invalid password")
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
// change password by self
if usernameInHeader == user.Username && user.Password != "" {
isUserManager, err := isUserManager(usernameInHeader)
if err != nil {
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
if !isUserManager {
_, err = iam.Login(usernameInHeader, user.CurrentPassword, "")
}
if err != nil {
err = fmt.Errorf("incorrect current password")
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
}
if usernameInHeader == user.Username {
// change cluster role by self is not permitted
user.ClusterRole = ""
}
result, err := iam.UpdateUser(&user)
if err != nil {
if ldap.IsErrorWithCode(err, ldap.LDAPResultEntryAlreadyExists) {
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusConflict, errors.Wrap(err))
return
}
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(result)
}
func isUserManager(username string) (bool, error) {
rules, err := iam.GetUserClusterRules(username)
if err != nil {
return false, err
}
if iam.RulesMatchesRequired(rules, rbacv1.PolicyRule{Verbs: []string{"update"}, Resources: []string{"users"}, APIGroups: []string{"iam.kubesphere.io"}}) {
return true, nil
}
return false, nil
}
func UserLoginLogs(req *restful.Request, resp *restful.Response) {
username := req.PathParameter("user")
logs, err := iam.LoginLog(username)
if err != nil {
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
result := make([]map[string]string, 0)
for _, v := range logs {
item := strings.Split(v, ",")
time := item[0]
var ip string
if len(item) > 1 {
ip = item[1]
}
result = append(result, map[string]string{"login_time": time, "login_ip": ip})
}
resp.WriteAsJson(result)
}
func DescribeUser(req *restful.Request, resp *restful.Response) {
username := req.PathParameter("user")
user, err := iam.DescribeUser(username)
if err != nil {
if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusNotFound, errors.Wrap(err))
} else {
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
}
return
}
clusterRole, err := iam.GetUserClusterRole(username)
if err != nil {
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
user.ClusterRole = clusterRole.Name
clusterRules, err := iam.GetUserClusterSimpleRules(username)
if err != nil {
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
result := struct {
*iam.User
ClusterRules []iam.SimpleRule `json:"cluster_rules"`
}{
User: user,
ClusterRules: clusterRules,
}
resp.WriteAsJson(result)
}
func Precheck(req *restful.Request, resp *restful.Response) {
check := req.QueryParameter("check")
exist, err := iam.UserCreateCheck(check)
if err != nil {
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(map[string]bool{"exist": exist})
}
func ListUsers(req *restful.Request, resp *restful.Response) {
if check := req.QueryParameter("check"); check != "" {
Precheck(req, resp)
return
}
limit, offset := params.ParsePaging(req.QueryParameter(params.PagingParam))
conditions, err := params.ParseConditions(req.QueryParameter(params.ConditionsParam))
orderBy := req.QueryParameter(params.OrderByParam)
reverse := params.ParseReverse(req)
if err != nil {
klog.Info(err)
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
users, err := iam.ListUsers(conditions, orderBy, reverse, limit, offset)
if err != nil {
klog.Error(err)
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(users)
}

View File

@@ -1,18 +0,0 @@
/*
Copyright 2019 The KubeSphere Authors.
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.
*/
package iam

View File

@@ -1,165 +0,0 @@
/*
Copyright 2019 The KubeSphere Authors.
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.
*/
package iam
import (
"github.com/emicklei/go-restful"
k8serr "k8s.io/apimachinery/pkg/api/errors"
"kubesphere.io/kubesphere/pkg/constants"
"kubesphere.io/kubesphere/pkg/models/iam"
"kubesphere.io/kubesphere/pkg/models/workspaces"
"kubesphere.io/kubesphere/pkg/server/errors"
"kubesphere.io/kubesphere/pkg/server/params"
"net/http"
)
func ListWorkspaceRoles(req *restful.Request, resp *restful.Response) {
workspace := req.PathParameter("workspace")
conditions, err := params.ParseConditions(req.QueryParameter(params.ConditionsParam))
orderBy := req.QueryParameter(params.OrderByParam)
limit, offset := params.ParsePaging(req.QueryParameter(params.PagingParam))
reverse := params.ParseReverse(req)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
result, err := iam.ListWorkspaceRoles(workspace, conditions, orderBy, reverse, limit, offset)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(result.Items)
}
func ListWorkspaceRoleRules(req *restful.Request, resp *restful.Response) {
workspace := req.PathParameter("workspace")
role := req.PathParameter("role")
rules := iam.GetWorkspaceRoleSimpleRules(workspace, role)
resp.WriteAsJson(rules)
}
func DescribeWorkspaceRole(req *restful.Request, resp *restful.Response) {
workspace := req.PathParameter("workspace")
roleName := req.PathParameter("role")
role, err := iam.GetWorkspaceRole(workspace, roleName)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(role)
}
func DescribeWorkspaceUser(req *restful.Request, resp *restful.Response) {
workspace := req.PathParameter("workspace")
username := req.PathParameter("member")
workspaceRole, err := iam.GetUserWorkspaceRole(workspace, username)
if err != nil {
if k8serr.IsNotFound(err) {
resp.WriteHeaderAndEntity(http.StatusNotFound, errors.Wrap(err))
} else {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
}
return
}
user, err := iam.GetUserInfo(username)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
user.WorkspaceRole = workspaceRole.Annotations[constants.DisplayNameAnnotationKey]
resp.WriteAsJson(user)
}
func ListDevopsRoleRules(req *restful.Request, resp *restful.Response) {
role := req.PathParameter("role")
rules := iam.GetDevopsRoleSimpleRules(role)
resp.WriteAsJson(rules)
}
func InviteUser(req *restful.Request, resp *restful.Response) {
workspace := req.PathParameter("workspace")
var user iam.User
err := req.ReadEntity(&user)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
err = workspaces.InviteUser(workspace, &user)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(errors.None)
}
func RemoveUser(req *restful.Request, resp *restful.Response) {
workspace := req.PathParameter("workspace")
username := req.PathParameter("member")
err := workspaces.RemoveUser(workspace, username)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(errors.None)
}
func ListWorkspaceUsers(req *restful.Request, resp *restful.Response) {
workspace := req.PathParameter("workspace")
conditions, err := params.ParseConditions(req.QueryParameter(params.ConditionsParam))
orderBy := req.QueryParameter(params.OrderByParam)
limit, offset := params.ParsePaging(req.QueryParameter(params.PagingParam))
reverse := params.ParseReverse(req)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusBadRequest, errors.Wrap(err))
return
}
result, err := iam.ListWorkspaceUsers(workspace, conditions, orderBy, reverse, limit, offset)
if err != nil {
resp.WriteHeaderAndEntity(http.StatusInternalServerError, errors.Wrap(err))
return
}
resp.WriteAsJson(result)
}