im.go 32.7 KB
Newer Older
H
hongming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*

 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 (
H
hongming 已提交
21
	"encoding/json"
H
hongming 已提交
22 23
	"errors"
	"fmt"
R
runzexia 已提交
24
	"github.com/emicklei/go-restful"
H
hongming 已提交
25
	"io/ioutil"
H
hongming 已提交
26
	"kubesphere.io/kubesphere/pkg/constants"
R
runzexia 已提交
27
	"kubesphere.io/kubesphere/pkg/db"
H
hongming 已提交
28
	"kubesphere.io/kubesphere/pkg/informers"
R
runzexia 已提交
29
	"kubesphere.io/kubesphere/pkg/models/devops"
H
hongming 已提交
30 31
	"kubesphere.io/kubesphere/pkg/models/kubeconfig"
	"kubesphere.io/kubesphere/pkg/models/kubectl"
H
hongming 已提交
32
	"kubesphere.io/kubesphere/pkg/params"
R
runzexia 已提交
33 34
	"kubesphere.io/kubesphere/pkg/simple/client/admin_jenkins"
	"kubesphere.io/kubesphere/pkg/simple/client/devops_mysql"
H
hongming 已提交
35 36
	"kubesphere.io/kubesphere/pkg/simple/client/k8s"
	"kubesphere.io/kubesphere/pkg/simple/client/redis"
H
hongming 已提交
37
	"kubesphere.io/kubesphere/pkg/utils/k8sutil"
H
hongming 已提交
38
	"kubesphere.io/kubesphere/pkg/utils/sliceutil"
R
runzexia 已提交
39
	"net/http"
H
hongming 已提交
40
	"regexp"
H
hongming 已提交
41
	"sort"
H
hongming 已提交
42 43 44 45 46 47 48
	"strconv"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/go-ldap/ldap"
	"github.com/golang/glog"
49
	rbacv1 "k8s.io/api/rbac/v1"
H
hongming 已提交
50 51
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
H
hongming 已提交
52
	ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
H
hongming 已提交
53 54

	"kubesphere.io/kubesphere/pkg/models"
H
hongming 已提交
55
	"kubesphere.io/kubesphere/pkg/utils/jwtutil"
H
hongming 已提交
56 57 58
)

var (
59 60 61 62 63 64
	adminEmail       string
	adminPassword    string
	tokenExpireTime  time.Duration
	maxAuthFailed    int
	authTimeInterval time.Duration
	initUsers        []initUser
H
hongming 已提交
65 66
)

H
hongming 已提交
67 68 69 70 71
type initUser struct {
	models.User
	Hidden bool `json:"hidden"`
}

H
hongming 已提交
72
const (
73 74 75 76
	userInitFile            = "/etc/ks-iam/users.json"
	authRateLimitRegex      = `(\d+)/(\d+[s|m|h])`
	defaultMaxAuthFailed    = 5
	defaultAuthTimeInterval = 30 * time.Minute
H
hongming 已提交
77 78
)

79
func Init(email, password string, expireTime time.Duration, authRateLimit string) error {
Z
zryfish 已提交
80 81
	adminEmail = email
	adminPassword = password
82 83
	tokenExpireTime = expireTime
	maxAuthFailed, authTimeInterval = parseAuthRateLimit(authRateLimit)
H
hongming 已提交
84
	conn, err := ldapclient.Client()
H
hongming 已提交
85 86 87 88 89 90 91

	if err != nil {
		return err
	}

	defer conn.Close()

H
hongming 已提交
92 93
	err = checkAndCreateDefaultUser(conn)

H
hongming 已提交
94
	if err != nil {
H
hongming 已提交
95
		glog.Errorln("create default users", err)
H
hongming 已提交
96 97 98
		return err
	}

H
hongming 已提交
99 100
	err = checkAndCreateDefaultGroup(conn)

H
hongming 已提交
101 102 103 104 105 106
	if err != nil {
		glog.Errorln("create default groups", err)
		return err
	}

	return nil
H
hongming 已提交
107 108
}

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
func parseAuthRateLimit(authRateLimit string) (int, time.Duration) {
	regex := regexp.MustCompile(authRateLimitRegex)
	groups := regex.FindStringSubmatch(authRateLimit)

	maxCount := defaultMaxAuthFailed
	timeInterval := defaultAuthTimeInterval

	if len(groups) == 3 {
		maxCount, _ = strconv.Atoi(groups[1])
		timeInterval, _ = time.ParseDuration(groups[2])
	} else {
		glog.Warning("invalid auth rate limit", authRateLimit)
	}

	return maxCount, timeInterval
}

H
hongming 已提交
126 127 128 129
func checkAndCreateDefaultGroup(conn ldap.Client) error {

	groupSearchRequest := ldap.NewSearchRequest(
		ldapclient.GroupSearchBase,
H
hongming 已提交
130
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
H
hongming 已提交
131
		"(&(objectClass=posixGroup))",
H
hongming 已提交
132 133 134 135
		nil,
		nil,
	)

H
hongming 已提交
136
	_, err := conn.Search(groupSearchRequest)
H
hongming 已提交
137

H
hongming 已提交
138 139
	if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
		err = createGroupsBaseDN(conn)
Z
zryfish 已提交
140 141 142
		if err != nil {
			return fmt.Errorf("GroupBaseDN %s create failed: %s\n", ldapclient.GroupSearchBase, err)
		}
H
hongming 已提交
143 144
	}

H
hongming 已提交
145
	if err != nil {
Z
zryfish 已提交
146
		return fmt.Errorf("iam database init failed: %s\n", err)
H
hongming 已提交
147
	}
H
hongming 已提交
148

H
hongming 已提交
149 150 151 152 153 154 155
	return nil
}

func checkAndCreateDefaultUser(conn ldap.Client) error {

	userSearchRequest := ldap.NewSearchRequest(
		ldapclient.UserSearchBase,
H
hongming 已提交
156
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
H
hongming 已提交
157
		"(&(objectClass=inetOrgPerson))",
H
hongming 已提交
158
		[]string{"uid"},
H
hongming 已提交
159 160 161
		nil,
	)

H
hongming 已提交
162
	result, err := conn.Search(userSearchRequest)
H
hongming 已提交
163

H
hongming 已提交
164 165
	if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
		err = createUserBaseDN(conn)
Z
zryfish 已提交
166 167 168
		if err != nil {
			return fmt.Errorf("UserBaseDN %s create failed: %s\n", ldapclient.UserSearchBase, err)
		}
H
hongming 已提交
169 170
	}

H
hongming 已提交
171
	if err != nil {
Z
zryfish 已提交
172
		return fmt.Errorf("iam database init failed: %s\n", err)
H
hongming 已提交
173
	}
H
hongming 已提交
174

H
hongming 已提交
175 176 177 178
	data, err := ioutil.ReadFile(userInitFile)
	if err == nil {
		json.Unmarshal(data, &initUsers)
	}
H
hongming 已提交
179
	initUsers = append(initUsers, initUser{User: models.User{Username: constants.AdminUserName, Email: adminEmail, Password: adminPassword, Description: "Administrator account that was always created by default.", ClusterRole: constants.ClusterAdmin}})
H
hongming 已提交
180

H
hongming 已提交
181 182 183
	for _, user := range initUsers {
		if result == nil || !containsUser(result.Entries, user) {
			_, err = CreateUser(&user.User)
H
hongming 已提交
184
			if err != nil && !ldap.IsErrorWithCode(err, ldap.LDAPResultEntryAlreadyExists) {
H
hongming 已提交
185
				glog.Errorln("user init failed", user.Username, err)
H
hongming 已提交
186 187
				return fmt.Errorf("user %s init failed: %s\n", user.Username, err)
			}
H
hongming 已提交
188 189 190 191 192 193
		}
	}

	return nil
}

H
hongming 已提交
194 195 196 197 198 199 200 201 202 203
func containsUser(entries []*ldap.Entry, user initUser) bool {
	for _, entry := range entries {
		uid := entry.GetAttributeValue("uid")
		if uid == user.Username {
			return true
		}
	}
	return false
}

H
hongming 已提交
204
func createUserBaseDN(conn ldap.Client) error {
H
hongming 已提交
205

H
hongming 已提交
206
	conn, err := ldapclient.Client()
H
hongming 已提交
207 208 209 210 211
	if err != nil {
		return err
	}
	defer conn.Close()

H
hongming 已提交
212
	groupsCreateRequest := ldap.NewAddRequest(ldapclient.UserSearchBase, nil)
H
hongming 已提交
213 214 215 216 217
	groupsCreateRequest.Attribute("objectClass", []string{"organizationalUnit", "top"})
	groupsCreateRequest.Attribute("ou", []string{"Users"})
	return conn.Add(groupsCreateRequest)
}

H
hongming 已提交
218 219
func createGroupsBaseDN(conn ldap.Client) error {
	groupsCreateRequest := ldap.NewAddRequest(ldapclient.GroupSearchBase, nil)
H
hongming 已提交
220 221 222 223 224 225
	groupsCreateRequest.Attribute("objectClass", []string{"organizationalUnit", "top"})
	groupsCreateRequest.Attribute("ou", []string{"Groups"})
	return conn.Add(groupsCreateRequest)
}

// User login
H
hongming 已提交
226
func Login(username string, password string, ip string) (*models.Token, error) {
H
hongming 已提交
227

228 229 230 231 232 233 234 235 236 237 238 239 240
	redisClient := redis.Client()

	records, err := redisClient.Keys(fmt.Sprintf("kubesphere:authfailed:%s:*", username)).Result()

	if err != nil {
		glog.Error(err)
		return nil, err
	}

	if len(records) >= maxAuthFailed {
		return nil, restful.NewError(http.StatusTooManyRequests, "auth rate limit exceeded")
	}

H
hongming 已提交
241
	conn, err := ldapclient.Client()
H
hongming 已提交
242 243

	if err != nil {
244
		glog.Error(err)
H
hongming 已提交
245
		return nil, err
H
hongming 已提交
246 247 248 249 250
	}

	defer conn.Close()

	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
251
		ldapclient.UserSearchBase,
H
hongming 已提交
252 253 254 255 256 257 258 259 260
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=%s)(mail=%s)))", username, username),
		[]string{"uid", "mail"},
		nil,
	)

	result, err := conn.Search(userSearchRequest)

	if err != nil {
H
hongming 已提交
261
		return nil, err
H
hongming 已提交
262 263 264
	}

	if len(result.Entries) != 1 {
H
hongming 已提交
265
		return nil, ldap.NewError(ldap.LDAPResultInvalidCredentials, errors.New("incorrect password"))
H
hongming 已提交
266 267 268 269 270 271 272 273 274 275
	}

	uid := result.Entries[0].GetAttributeValue("uid")
	email := result.Entries[0].GetAttributeValue("mail")
	dn := result.Entries[0].DN

	// bind as the user to verify their password
	err = conn.Bind(dn, password)

	if err != nil {
276 277 278 279 280 281 282
		glog.Infoln("auth failed", username, err)

		if ldap.IsErrorWithCode(err, ldap.LDAPResultInvalidCredentials) {
			loginFailedRecord := fmt.Sprintf("kubesphere:authfailed:%s:%d", username, time.Now().UnixNano())
			redisClient.Set(loginFailedRecord, "", authTimeInterval)
		}

H
hongming 已提交
283
		return nil, err
H
hongming 已提交
284 285 286 287
	}

	claims := jwt.MapClaims{}

H
hongming 已提交
288 289 290
	if tokenExpireTime > 0 {
		claims["exp"] = time.Now().Add(tokenExpireTime).Unix()
	}
Z
zryfish 已提交
291 292
	claims["username"] = uid
	claims["email"] = email
H
hongming 已提交
293

H
hongming 已提交
294
	token := jwtutil.MustSigned(claims)
H
hongming 已提交
295

Z
zryfish 已提交
296 297
	loginLog(uid, ip)

H
hongming 已提交
298
	return &models.Token{Token: token}, nil
H
hongming 已提交
299 300
}

Z
zryfish 已提交
301 302 303 304 305 306 307 308
func loginLog(uid, ip string) {
	if ip != "" {
		redisClient := redis.Client()
		redisClient.RPush(fmt.Sprintf("kubesphere:users:%s:login-log", uid), fmt.Sprintf("%s,%s", time.Now().UTC().Format("2006-01-02T15:04:05Z"), ip))
		redisClient.LTrim(fmt.Sprintf("kubesphere:users:%s:login-log", uid), -10, -1)
	}
}

H
hongming 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321
func LoginLog(username string) ([]string, error) {
	redisClient := redis.Client()

	data, err := redisClient.LRange(fmt.Sprintf("kubesphere:users:%s:login-log", username), -10, -1).Result()

	if err != nil {
		return nil, err
	}

	return data, nil
}

func ListUsers(conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error) {
H
hongming 已提交
322

H
hongming 已提交
323
	conn, err := ldapclient.Client()
H
hongming 已提交
324 325

	if err != nil {
H
hongming 已提交
326
		return nil, err
H
hongming 已提交
327 328 329 330
	}

	defer conn.Close()

H
hongming 已提交
331
	pageControl := ldap.NewControlPaging(1000)
H
hongming 已提交
332

H
hongming 已提交
333 334
	users := make([]models.User, 0)

H
hongming 已提交
335
	filter := "(&(objectClass=inetOrgPerson))"
H
hongming 已提交
336

H
hongming 已提交
337 338 339
	if keyword := conditions.Match["keyword"]; keyword != "" {
		filter = fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=*%s*)(mail=*%s*)(description=*%s*)))", keyword, keyword, keyword)
	}
H
hongming 已提交
340

H
hongming 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	if username := conditions.Match["username"]; username != "" {
		uidFilter := ""
		for _, username := range strings.Split(username, "|") {
			uidFilter += fmt.Sprintf("(uid=%s)", username)
		}
		filter = fmt.Sprintf("(&(objectClass=inetOrgPerson)(|%s))", uidFilter)
	}

	if email := conditions.Match["email"]; email != "" {
		emailFilter := ""
		for _, username := range strings.Split(email, "|") {
			emailFilter += fmt.Sprintf("(mail=%s)", username)
		}
		filter = fmt.Sprintf("(&(objectClass=inetOrgPerson)(|%s))", emailFilter)
	}

H
hongming 已提交
357 358
	for {
		userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
359
			ldapclient.UserSearchBase,
H
hongming 已提交
360
			ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
H
hongming 已提交
361 362
			filter,
			[]string{"uid", "mail", "description", "preferredLanguage", "createTimestamp"},
H
hongming 已提交
363 364 365 366 367 368
			[]ldap.Control{pageControl},
		)

		response, err := conn.Search(userSearchRequest)

		if err != nil {
H
hongming 已提交
369
			glog.Errorln("search user", err)
H
hongming 已提交
370
			return nil, err
H
hongming 已提交
371 372 373
		}

		for _, entry := range response.Entries {
H
hongming 已提交
374 375 376 377 378 379 380 381 382

			uid := entry.GetAttributeValue("uid")
			email := entry.GetAttributeValue("mail")
			description := entry.GetAttributeValue("description")
			lang := entry.GetAttributeValue("preferredLanguage")
			createTimestamp, _ := time.Parse("20060102150405Z", entry.GetAttributeValue("createTimestamp"))

			user := models.User{Username: uid, Email: email, Description: description, Lang: lang, CreateTime: createTimestamp}

H
hongming 已提交
383 384 385
			if !shouldHidden(user) {
				users = append(users, user)
			}
H
hongming 已提交
386 387 388 389 390 391 392 393 394 395 396
		}

		updatedControl := ldap.FindControl(response.Controls, ldap.ControlTypePaging)
		if ctrl, ok := updatedControl.(*ldap.ControlPaging); ctrl != nil && ok && len(ctrl.Cookie) != 0 {
			pageControl.SetCookie(ctrl.Cookie)
			continue
		}

		break
	}

H
hongming 已提交
397 398 399 400 401 402 403 404
	sort.Slice(users, func(i, j int) bool {
		if reverse {
			tmp := i
			i = j
			j = tmp
		}
		switch orderBy {
		case "username":
H
hongming 已提交
405
			return strings.Compare(users[i].Username, users[j].Username) <= 0
H
hongming 已提交
406
		case "createTime":
H
hongming 已提交
407
			fallthrough
H
hongming 已提交
408
		default:
H
hongming 已提交
409
			return users[i].CreateTime.Before(users[j].CreateTime)
H
hongming 已提交
410 411
		}
	})
H
hongming 已提交
412

H
hongming 已提交
413
	items := make([]interface{}, 0)
H
hongming 已提交
414

H
hongming 已提交
415
	for i, user := range users {
H
hongming 已提交
416

H
hongming 已提交
417
		if i >= offset && len(items) < limit {
H
hongming 已提交
418

H
hongming 已提交
419 420
			user.AvatarUrl = getAvatar(user.Username)
			user.LastLoginTime = getLastLoginTime(user.Username)
H
hongming 已提交
421 422 423 424 425 426 427
			clusterRole, err := GetUserClusterRole(user.Username)
			if err != nil {
				return nil, err
			}
			user.ClusterRole = clusterRole.Name
			items = append(items, user)
		}
H
hongming 已提交
428 429
	}

H
hongming 已提交
430
	return &models.PageableResponse{Items: items, TotalCount: len(users)}, nil
H
hongming 已提交
431 432
}

H
hongming 已提交
433 434 435 436 437 438 439 440 441
func shouldHidden(user models.User) bool {
	for _, initUser := range initUsers {
		if initUser.Username == user.Username {
			return initUser.Hidden
		}
	}
	return false
}

H
hongming 已提交
442
func DescribeUser(username string) (*models.User, error) {
H
hongming 已提交
443

H
hongming 已提交
444
	user, err := GetUserInfo(username)
H
hongming 已提交
445 446 447 448 449

	if err != nil {
		return nil, err
	}

H
hongming 已提交
450
	groups, err := GetUserGroups(username)
H
hongming 已提交
451

H
hongming 已提交
452 453
	if err == nil {
		user.Groups = groups
H
hongming 已提交
454 455
	}

H
hongming 已提交
456
	user.AvatarUrl = getAvatar(username)
H
hongming 已提交
457

H
hongming 已提交
458 459 460
	return user, nil
}

H
hongming 已提交
461 462
// Get user info only included email description & lang
func GetUserInfo(username string) (*models.User, error) {
H
hongming 已提交
463

H
hongming 已提交
464
	conn, err := ldapclient.Client()
H
hongming 已提交
465

H
hongming 已提交
466 467
	if err != nil {
		return nil, err
H
hongming 已提交
468 469
	}

H
hongming 已提交
470 471
	defer conn.Close()

H
hongming 已提交
472
	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
473
		ldapclient.UserSearchBase,
H
hongming 已提交
474 475
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", username),
H
hongming 已提交
476
		[]string{"mail", "description", "preferredLanguage", "createTimestamp"},
H
hongming 已提交
477 478 479 480 481 482
		nil,
	)

	result, err := conn.Search(userSearchRequest)

	if err != nil {
H
hongming 已提交
483
		glog.Errorln("search user", err)
H
hongming 已提交
484 485 486 487 488 489 490 491 492 493
		return nil, err
	}

	if len(result.Entries) != 1 {
		return nil, ldap.NewError(ldap.LDAPResultNoSuchObject, fmt.Errorf("user %s does not exist", username))
	}

	email := result.Entries[0].GetAttributeValue("mail")
	description := result.Entries[0].GetAttributeValue("description")
	lang := result.Entries[0].GetAttributeValue("preferredLanguage")
H
hongming 已提交
494 495 496
	createTimestamp, _ := time.Parse("20060102150405Z", result.Entries[0].GetAttributeValue("createTimestamp"))
	user := &models.User{Username: username, Email: email, Description: description, Lang: lang, CreateTime: createTimestamp}

H
hongming 已提交
497 498
	user.LastLoginTime = getLastLoginTime(username)

H
hongming 已提交
499 500 501 502 503 504 505 506 507 508 509
	return user, nil
}

func GetUserGroups(username string) ([]string, error) {
	conn, err := ldapclient.Client()

	if err != nil {
		return nil, err
	}

	defer conn.Close()
H
hongming 已提交
510 511

	groupSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
512
		ldapclient.GroupSearchBase,
H
hongming 已提交
513 514 515 516 517 518
		ldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=posixGroup)(memberUid=%s))", username),
		nil,
		nil,
	)

H
hongming 已提交
519
	result, err := conn.Search(groupSearchRequest)
H
hongming 已提交
520 521 522 523 524 525 526 527 528 529 530 531

	if err != nil {
		return nil, err
	}

	groups := make([]string, 0)

	for _, group := range result.Entries {
		groupName := convertDNToPath(group.DN)
		groups = append(groups, groupName)
	}

H
hongming 已提交
532 533
	return groups, nil
}
H
hongming 已提交
534

H
hongming 已提交
535
func getLastLoginTime(username string) string {
H
hongming 已提交
536
	lastLogin, err := redis.Client().LRange(fmt.Sprintf("kubesphere:users:%s:login-log", username), -1, -1).Result()
H
hongming 已提交
537 538

	if err != nil {
H
hongming 已提交
539
		return ""
H
hongming 已提交
540 541
	}

H
hongming 已提交
542
	if len(lastLogin) > 0 {
H
hongming 已提交
543
		return strings.Split(lastLogin[0], ",")[0]
H
hongming 已提交
544
	}
H
hongming 已提交
545 546

	return ""
H
hongming 已提交
547 548 549 550 551 552
}

func setAvatar(username, avatar string) error {
	_, err := redis.Client().HMSet("kubesphere:users:avatar", map[string]interface{}{"username": avatar}).Result()
	return err
}
H
hongming 已提交
553

H
hongming 已提交
554
func getAvatar(username string) string {
H
hongming 已提交
555

H
hongming 已提交
556
	avatar, err := redis.Client().HMGet("kubesphere:users:avatar", username).Result()
H
hongming 已提交
557 558

	if err != nil {
H
hongming 已提交
559
		return ""
H
hongming 已提交
560 561
	}

H
hongming 已提交
562 563
	if len(avatar) > 0 {
		if url, ok := avatar[0].(string); ok {
H
hongming 已提交
564
			return url
H
hongming 已提交
565
		}
H
hongming 已提交
566
	}
H
hongming 已提交
567 568

	return ""
H
hongming 已提交
569 570 571 572
}

func DeleteUser(username string) error {

H
hongming 已提交
573
	conn, err := ldapclient.Client()
H
hongming 已提交
574

H
hongming 已提交
575 576 577 578 579 580
	if err != nil {
		return err
	}

	defer conn.Close()

H
hongming 已提交
581
	deleteRequest := ldap.NewDelRequest(fmt.Sprintf("uid=%s,%s", username, ldapclient.UserSearchBase), nil)
H
hongming 已提交
582

H
hongming 已提交
583
	if err = conn.Del(deleteRequest); err != nil {
H
hongming 已提交
584
		glog.Errorln("delete user", err)
H
hongming 已提交
585 586 587
		return err
	}

H
hongming 已提交
588 589 590 591 592 593 594
	if err = deleteRoleBindings(username); err != nil {
		glog.Errorln("delete user role bindings failed", username, err)
	}

	if err := kubeconfig.DelKubeConfig(username); err != nil {
		glog.Errorln("delete user kubeconfig failed", username, err)
	}
H
hongming 已提交
595

H
hongming 已提交
596 597 598 599
	if err := kubectl.DelKubectlDeploy(username); err != nil {
		glog.Errorln("delete user terminal pod failed", username, err)
	}

R
runzexia 已提交
600 601 602
	devopsDb := devops_mysql.OpenDatabase()

	jenkinsClient := admin_jenkins.Client()
R
runzexia 已提交
603 604 605 606 607
	if jenkinsClient == nil {
		err := fmt.Errorf("could not connect to jenkins")
		glog.Error(err)
		return restful.NewError(http.StatusServiceUnavailable, err.Error())
	}
R
runzexia 已提交
608 609 610 611 612 613
	_, err = devopsDb.DeleteFrom(devops.DevOpsProjectMembershipTableName).
		Where(db.And(
			db.Eq(devops.DevOpsProjectMembershipUsernameColumn, username),
		)).Exec()
	if err != nil {
		glog.Errorf("%+v", err)
R
runzexia 已提交
614
		return err
R
runzexia 已提交
615 616 617 618 619
	}

	err = jenkinsClient.DeleteUserInProject(username)
	if err != nil {
		glog.Errorf("%+v", err)
R
runzexia 已提交
620
		return err
R
runzexia 已提交
621 622
	}

H
hongming 已提交
623
	return nil
R
runzexia 已提交
624

H
hongming 已提交
625 626 627 628 629 630 631 632 633 634 635
}

func deleteRoleBindings(username string) error {
	roleBindingLister := informers.SharedInformerFactory().Rbac().V1().RoleBindings().Lister()
	roleBindings, err := roleBindingLister.List(labels.Everything())

	if err != nil {
		return err
	}

	for _, roleBinding := range roleBindings {
H
hongming 已提交
636
		roleBinding = roleBinding.DeepCopy()
H
hongming 已提交
637 638 639
		length1 := len(roleBinding.Subjects)

		for index, subject := range roleBinding.Subjects {
640
			if subject.Kind == rbacv1.UserKind && subject.Name == username {
H
hongming 已提交
641 642 643 644 645 646 647 648 649
				roleBinding.Subjects = append(roleBinding.Subjects[:index], roleBinding.Subjects[index+1:]...)
				index--
			}
		}

		length2 := len(roleBinding.Subjects)

		if length2 == 0 {
			deletePolicy := meta_v1.DeletePropagationForeground
H
hongming 已提交
650
			err = k8s.Client().RbacV1().RoleBindings(roleBinding.Namespace).Delete(roleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
H
hongming 已提交
651 652 653 654 655

			if err != nil {
				glog.Errorf("delete role binding %s %s %s failed: %v", username, roleBinding.Namespace, roleBinding.Name, err)
			}
		} else if length2 < length1 {
H
hongming 已提交
656
			_, err = k8s.Client().RbacV1().RoleBindings(roleBinding.Namespace).Update(roleBinding)
H
hongming 已提交
657 658 659 660 661 662 663 664 665 666 667

			if err != nil {
				glog.Errorf("update role binding %s %s %s failed: %v", username, roleBinding.Namespace, roleBinding.Name, err)
			}
		}
	}

	clusterRoleBindingLister := informers.SharedInformerFactory().Rbac().V1().ClusterRoleBindings().Lister()
	clusterRoleBindings, err := clusterRoleBindingLister.List(labels.Everything())

	for _, clusterRoleBinding := range clusterRoleBindings {
H
hongming 已提交
668
		clusterRoleBinding = clusterRoleBinding.DeepCopy()
H
hongming 已提交
669 670 671
		length1 := len(clusterRoleBinding.Subjects)

		for index, subject := range clusterRoleBinding.Subjects {
672
			if subject.Kind == rbacv1.UserKind && subject.Name == username {
H
hongming 已提交
673 674 675 676 677 678 679
				clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects[:index], clusterRoleBinding.Subjects[index+1:]...)
				index--
			}
		}

		length2 := len(clusterRoleBinding.Subjects)
		if length2 == 0 {
680 681
			// delete if it's not workspace role binding
			if isWorkspaceRoleBinding(clusterRoleBinding) {
H
hongming 已提交
682
				_, err = k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
H
hongming 已提交
683 684
			} else {
				deletePolicy := meta_v1.DeletePropagationForeground
H
hongming 已提交
685
				err = k8s.Client().RbacV1().ClusterRoleBindings().Delete(clusterRoleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
H
hongming 已提交
686 687 688 689 690
			}
			if err != nil {
				glog.Errorf("update cluster role binding %s failed:%s", clusterRoleBinding.Name, err)
			}
		} else if length2 < length1 {
H
hongming 已提交
691
			_, err = k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
H
hongming 已提交
692 693 694 695 696 697 698 699 700 701 702

			if err != nil {
				glog.Errorf("update cluster role binding %s failed:%s", clusterRoleBinding.Name, err)
			}
		}

	}

	return nil
}

703 704 705 706
func isWorkspaceRoleBinding(clusterRoleBinding *rbacv1.ClusterRoleBinding) bool {
	return k8sutil.IsControlledBy(clusterRoleBinding.OwnerReferences, "Workspace", "")
}

H
hongming 已提交
707 708 709
func UserCreateCheck(check string) (exist bool, err error) {

	// bind root DN
H
hongming 已提交
710
	conn, err := ldapclient.Client()
H
hongming 已提交
711 712 713 714 715 716 717 718 719

	if err != nil {
		return false, err
	}

	defer conn.Close()

	// search for the given username
	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
720
		ldapclient.UserSearchBase,
H
hongming 已提交
721 722 723 724 725 726 727 728 729
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=%s)(mail=%s)))", check, check),
		[]string{"uid", "mail"},
		nil,
	)

	result, err := conn.Search(userSearchRequest)

	if err != nil {
H
hongming 已提交
730
		glog.Errorln("search user", err)
H
hongming 已提交
731 732 733
		return false, err
	}

H
hongming 已提交
734
	return len(result.Entries) > 0, nil
H
hongming 已提交
735 736
}

H
hongming 已提交
737
func CreateUser(user *models.User) (*models.User, error) {
H
hongming 已提交
738 739 740 741 742
	user.Username = strings.TrimSpace(user.Username)
	user.Email = strings.TrimSpace(user.Email)
	user.Password = strings.TrimSpace(user.Password)
	user.Description = strings.TrimSpace(user.Description)

H
hongming 已提交
743
	conn, err := ldapclient.Client()
H
hongming 已提交
744 745

	if err != nil {
H
hongming 已提交
746
		return nil, err
H
hongming 已提交
747 748 749 750 751
	}

	defer conn.Close()

	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
752
		ldapclient.UserSearchBase,
H
hongming 已提交
753 754 755 756 757 758 759 760 761
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=%s)(mail=%s)))", user.Username, user.Email),
		[]string{"uid", "mail"},
		nil,
	)

	result, err := conn.Search(userSearchRequest)

	if err != nil {
H
hongming 已提交
762
		glog.Errorln("search user", err)
H
hongming 已提交
763
		return nil, err
H
hongming 已提交
764 765 766
	}

	if len(result.Entries) > 0 {
H
hongming 已提交
767
		return nil, ldap.NewError(ldap.LDAPResultEntryAlreadyExists, fmt.Errorf("username or email already exists"))
H
hongming 已提交
768 769 770 771 772
	}

	maxUid, err := getMaxUid(conn)

	if err != nil {
H
hongming 已提交
773
		glog.Errorln("get max uid", err)
H
hongming 已提交
774
		return nil, err
H
hongming 已提交
775 776 777 778
	}

	maxUid += 1

H
hongming 已提交
779
	userCreateRequest := ldap.NewAddRequest(fmt.Sprintf("uid=%s,%s", user.Username, ldapclient.UserSearchBase), nil)
H
hongming 已提交
780 781 782 783 784 785 786 787 788 789
	userCreateRequest.Attribute("objectClass", []string{"inetOrgPerson", "posixAccount", "top"})
	userCreateRequest.Attribute("cn", []string{user.Username})                       // RFC4519: common name(s) for which the entity is known by
	userCreateRequest.Attribute("sn", []string{" "})                                 // RFC2256: last (family) name(s) for which the entity is known by
	userCreateRequest.Attribute("gidNumber", []string{"500"})                        // RFC2307: An integer uniquely identifying a group in an administrative domain
	userCreateRequest.Attribute("homeDirectory", []string{"/home/" + user.Username}) // The absolute path to the home directory
	userCreateRequest.Attribute("uid", []string{user.Username})                      // RFC4519: user identifier
	userCreateRequest.Attribute("uidNumber", []string{strconv.Itoa(maxUid)})         // RFC2307: An integer uniquely identifying a user in an administrative domain
	userCreateRequest.Attribute("mail", []string{user.Email})                        // RFC1274: RFC822 Mailbox
	userCreateRequest.Attribute("userPassword", []string{user.Password})             // RFC4519/2307: password of user
	if user.Lang != "" {
H
hongming 已提交
790
		userCreateRequest.Attribute("preferredLanguage", []string{user.Lang})
H
hongming 已提交
791 792 793 794 795
	}
	if user.Description != "" {
		userCreateRequest.Attribute("description", []string{user.Description}) // RFC4519: descriptive information
	}

H
hongming 已提交
796 797 798 799 800
	if err := kubeconfig.CreateKubeConfig(user.Username); err != nil {
		glog.Errorln("create user kubeconfig failed", user.Username, err)
		return nil, err
	}

H
hongming 已提交
801 802 803
	err = conn.Add(userCreateRequest)

	if err != nil {
H
hongming 已提交
804
		glog.Errorln("create user", err)
H
hongming 已提交
805
		return nil, err
H
hongming 已提交
806 807
	}

H
hongming 已提交
808 809 810
	if user.AvatarUrl != "" {
		setAvatar(user.Username, user.AvatarUrl)
	}
H
hongming 已提交
811 812

	if user.ClusterRole != "" {
H
hongming 已提交
813 814 815
		err := CreateClusterRoleBinding(user.Username, user.ClusterRole)

		if err != nil {
H
hongming 已提交
816
			glog.Errorln("create cluster role binding filed", err)
H
hongming 已提交
817 818
			return nil, err
		}
H
hongming 已提交
819 820
	}

H
hongming 已提交
821
	return DescribeUser(user.Username)
H
hongming 已提交
822 823 824
}

func getMaxUid(conn ldap.Client) (int, error) {
H
hongming 已提交
825
	userSearchRequest := ldap.NewSearchRequest(ldapclient.UserSearchBase,
H
hongming 已提交
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		"(&(objectClass=inetOrgPerson))",
		[]string{"uidNumber"},
		nil)

	result, err := conn.Search(userSearchRequest)

	if err != nil {
		return 0, err
	}

	var maxUid int

	if len(result.Entries) == 0 {
		maxUid = 1000
	} else {
		for _, usr := range result.Entries {
			uid, _ := strconv.Atoi(usr.GetAttributeValue("uidNumber"))
			if uid > maxUid {
				maxUid = uid
			}
		}
	}

	return maxUid, nil
}

func getMaxGid(conn ldap.Client) (int, error) {

H
hongming 已提交
855
	groupSearchRequest := ldap.NewSearchRequest(ldapclient.GroupSearchBase,
H
hongming 已提交
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		"(&(objectClass=posixGroup))",
		[]string{"gidNumber"},
		nil)

	result, err := conn.Search(groupSearchRequest)

	if err != nil {
		return 0, err
	}

	var maxGid int

	if len(result.Entries) == 0 {
		maxGid = 500
	} else {
		for _, group := range result.Entries {
			gid, _ := strconv.Atoi(group.GetAttributeValue("gidNumber"))
			if gid > maxGid {
				maxGid = gid
			}
		}
	}

	return maxGid, nil
}

H
hongming 已提交
883
func UpdateUser(user *models.User) (*models.User, error) {
H
hongming 已提交
884

H
hongming 已提交
885
	conn, err := ldapclient.Client()
H
hongming 已提交
886

H
hongming 已提交
887
	if err != nil {
H
hongming 已提交
888
		glog.Error(err)
H
hongming 已提交
889
		return nil, err
H
hongming 已提交
890 891 892 893
	}

	defer conn.Close()

H
hongming 已提交
894
	dn := fmt.Sprintf("uid=%s,%s", user.Username, ldapclient.UserSearchBase)
H
hongming 已提交
895 896
	userModifyRequest := ldap.NewModifyRequest(dn, nil)
	if user.Email != "" {
H
hongming 已提交
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
		userSearchRequest := ldap.NewSearchRequest(
			ldapclient.UserSearchBase,
			ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
			fmt.Sprintf("(&(objectClass=inetOrgPerson)(mail=%s))", user.Email),
			[]string{"uid", "mail"},
			nil,
		)
		result, err := conn.Search(userSearchRequest)
		if err != nil {
			glog.Error(err)
			return nil, err
		}
		if len(result.Entries) > 1 {
			err = ldap.NewError(ldap.ErrorDebugging, fmt.Errorf("email is duplicated: %s", user.Email))
			glog.Error(err)
			return nil, err
		}
		if len(result.Entries) == 1 && result.Entries[0].GetAttributeValue("uid") != user.Username {
			err = ldap.NewError(ldap.LDAPResultEntryAlreadyExists, fmt.Errorf("email is duplicated: %s", user.Email))
			glog.Error(err)
			return nil, err
		}
H
hongming 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932
		userModifyRequest.Replace("mail", []string{user.Email})
	}
	if user.Description != "" {
		userModifyRequest.Replace("description", []string{user.Description})
	}

	if user.Lang != "" {
		userModifyRequest.Replace("preferredLanguage", []string{user.Lang})
	}

	if user.Password != "" {
		userModifyRequest.Replace("userPassword", []string{user.Password})
	}

H
hongming 已提交
933 934 935 936 937
	if user.AvatarUrl != "" {
		err = setAvatar(user.Username, user.AvatarUrl)
	}

	if err != nil {
H
hongming 已提交
938
		glog.Error(err)
H
hongming 已提交
939 940 941
		return nil, err
	}

H
hongming 已提交
942 943 944
	err = conn.Modify(userModifyRequest)

	if err != nil {
H
hongming 已提交
945
		glog.Error(err)
H
hongming 已提交
946
		return nil, err
H
hongming 已提交
947 948 949 950 951
	}

	err = CreateClusterRoleBinding(user.Username, user.ClusterRole)

	if err != nil {
H
hongming 已提交
952
		glog.Errorln("create cluster role binding filed", err)
H
hongming 已提交
953
		return nil, err
H
hongming 已提交
954 955
	}

956 957 958 959 960 961 962 963 964 965 966
	// clear auth failed record
	if user.Password != "" {
		redisClient := redis.Client()

		records, err := redisClient.Keys(fmt.Sprintf("kubesphere:authfailed:%s:*", user.Username)).Result()

		if err == nil {
			redisClient.Del(records...)
		}
	}

H
hongming 已提交
967
	return GetUserInfo(user.Username)
H
hongming 已提交
968 969 970 971
}
func DeleteGroup(path string) error {

	// bind root DN
H
hongming 已提交
972
	conn, err := ldapclient.Client()
H
hongming 已提交
973 974 975 976 977 978 979 980 981 982 983
	if err != nil {
		return err
	}
	defer conn.Close()

	searchBase, cn := splitPath(path)

	groupDeleteRequest := ldap.NewDelRequest(fmt.Sprintf("cn=%s,%s", cn, searchBase), nil)
	err = conn.Del(groupDeleteRequest)

	if err != nil {
H
hongming 已提交
984
		glog.Errorln("delete user group", err)
H
hongming 已提交
985 986 987 988 989 990
		return err
	}

	return nil
}

H
hongming 已提交
991
func CreateGroup(group *models.Group) (*models.Group, error) {
H
hongming 已提交
992

H
hongming 已提交
993
	conn, err := ldapclient.Client()
H
hongming 已提交
994

H
hongming 已提交
995 996 997
	if err != nil {
		return nil, err
	}
H
hongming 已提交
998

H
hongming 已提交
999 1000 1001 1002 1003
	defer conn.Close()

	maxGid, err := getMaxGid(conn)

	if err != nil {
H
hongming 已提交
1004
		glog.Errorln("get max gid", err)
H
hongming 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
		return nil, err
	}

	maxGid += 1

	if group.Path == "" {
		group.Path = group.Name
	}

	searchBase, cn := splitPath(group.Path)

	groupCreateRequest := ldap.NewAddRequest(fmt.Sprintf("cn=%s,%s", cn, searchBase), nil)
	groupCreateRequest.Attribute("objectClass", []string{"posixGroup", "top"})
	groupCreateRequest.Attribute("cn", []string{cn})
	groupCreateRequest.Attribute("gidNumber", []string{strconv.Itoa(maxGid)})

	if group.Description != "" {
		groupCreateRequest.Attribute("description", []string{group.Description})
	}

H
hongming 已提交
1025 1026 1027
	if group.Members != nil {
		groupCreateRequest.Attribute("memberUid", group.Members)
	}
H
hongming 已提交
1028 1029 1030 1031

	err = conn.Add(groupCreateRequest)

	if err != nil {
H
hongming 已提交
1032
		glog.Errorln("create group", err)
H
hongming 已提交
1033 1034 1035 1036 1037
		return nil, err
	}

	group.Gid = strconv.Itoa(maxGid)

H
hongming 已提交
1038
	return DescribeGroup(group.Path)
H
hongming 已提交
1039 1040 1041 1042 1043
}

func UpdateGroup(group *models.Group) (*models.Group, error) {

	// bind root DN
H
hongming 已提交
1044
	conn, err := ldapclient.Client()
H
hongming 已提交
1045 1046 1047 1048 1049
	if err != nil {
		return nil, err
	}
	defer conn.Close()

H
hongming 已提交
1050
	old, err := DescribeGroup(group.Path)
H
hongming 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078

	if err != nil {
		return nil, err
	}

	searchBase, cn := splitPath(group.Path)

	groupUpdateRequest := ldap.NewModifyRequest(fmt.Sprintf("cn=%s,%s", cn, searchBase), nil)

	if old.Description == "" {
		if group.Description != "" {
			groupUpdateRequest.Add("description", []string{group.Description})
		}
	} else {
		if group.Description != "" {
			groupUpdateRequest.Replace("description", []string{group.Description})
		} else {
			groupUpdateRequest.Delete("description", []string{})
		}
	}

	if group.Members != nil {
		groupUpdateRequest.Replace("memberUid", group.Members)
	}

	err = conn.Modify(groupUpdateRequest)

	if err != nil {
H
hongming 已提交
1079
		glog.Errorln("update group", err)
H
hongming 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088
		return nil, err
	}

	return group, nil
}

func ChildList(path string) ([]models.Group, error) {

	// bind root DN
H
hongming 已提交
1089
	conn, err := ldapclient.Client()
H
hongming 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098

	if err != nil {
		return nil, err
	}

	defer conn.Close()

	var groupSearchRequest *ldap.SearchRequest
	if path == "" {
H
hongming 已提交
1099
		groupSearchRequest = ldap.NewSearchRequest(ldapclient.GroupSearchBase,
H
hongming 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
			ldap.ScopeSingleLevel, ldap.NeverDerefAliases, 0, 0, false,
			"(&(objectClass=posixGroup))",
			[]string{"cn", "gidNumber", "memberUid", "description"},
			nil)
	} else {
		searchBase, cn := splitPath(path)
		groupSearchRequest = ldap.NewSearchRequest(fmt.Sprintf("cn=%s,%s", cn, searchBase),
			ldap.ScopeSingleLevel, ldap.NeverDerefAliases, 0, 0, false,
			"(&(objectClass=posixGroup))",
			[]string{"cn", "gidNumber", "memberUid", "description"},
			nil)
	}

	result, err := conn.Search(groupSearchRequest)

	if err != nil {
		return nil, err
	}

	groups := make([]models.Group, 0)

	for _, v := range result.Entries {
		dn := v.DN
		cn := v.GetAttributeValue("cn")
		gid := v.GetAttributeValue("gidNumber")
		members := v.GetAttributeValues("memberUid")
		description := v.GetAttributeValue("description")

		group := models.Group{Path: convertDNToPath(dn), Name: cn, Gid: gid, Members: members, Description: description}

		childSearchRequest := ldap.NewSearchRequest(dn,
			ldap.ScopeSingleLevel, ldap.NeverDerefAliases, 0, 0, false,
			"(&(objectClass=posixGroup))",
			[]string{""},
			nil)

		result, err = conn.Search(childSearchRequest)

		if err != nil {
			return nil, err
		}

		childGroups := make([]string, 0)

		for _, v := range result.Entries {
			child := convertDNToPath(v.DN)
			childGroups = append(childGroups, child)
		}

		group.ChildGroups = childGroups

		groups = append(groups, group)
	}

	return groups, nil
}

H
hongming 已提交
1157
func DescribeGroup(path string) (*models.Group, error) {
H
hongming 已提交
1158 1159 1160

	searchBase, cn := splitPath(path)

H
hongming 已提交
1161 1162 1163 1164 1165 1166
	conn, err := ldapclient.Client()

	if err != nil {
		return nil, err
	}

H
hongming 已提交
1167 1168
	defer conn.Close()

H
hongming 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177
	groupSearchRequest := ldap.NewSearchRequest(searchBase,
		ldap.ScopeSingleLevel, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=posixGroup)(cn=%s))", cn),
		[]string{"cn", "gidNumber", "memberUid", "description"},
		nil)

	result, err := conn.Search(groupSearchRequest)

	if err != nil {
H
hongming 已提交
1178
		glog.Errorln("search group", err)
H
hongming 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
		return nil, err
	}

	if len(result.Entries) != 1 {
		return nil, ldap.NewError(ldap.LDAPResultNoSuchObject, fmt.Errorf("group %s does not exist", path))
	}

	dn := result.Entries[0].DN
	cn = result.Entries[0].GetAttributeValue("cn")
	gid := result.Entries[0].GetAttributeValue("gidNumber")
	members := result.Entries[0].GetAttributeValues("memberUid")
	description := result.Entries[0].GetAttributeValue("description")

	group := models.Group{Path: convertDNToPath(dn), Name: cn, Gid: gid, Members: members, Description: description}

	childGroups := make([]string, 0)

	group.ChildGroups = childGroups

H
hongming 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
	return &group, nil

}

func WorkspaceUsersTotalCount(workspace string) (int, error) {
	workspaceRoleBindings, err := GetWorkspaceRoleBindings(workspace)

	if err != nil {
		return 0, err
	}
H
hongming 已提交
1208

H
hongming 已提交
1209
	users := make([]string, 0)
H
hongming 已提交
1210

H
hongming 已提交
1211 1212
	for _, roleBinding := range workspaceRoleBindings {
		for _, subject := range roleBinding.Subjects {
1213
			if subject.Kind == rbacv1.UserKind && !k8sutil.ContainsUser(users, subject.Name) {
H
hongming 已提交
1214 1215
				users = append(users, subject.Name)
			}
H
hongming 已提交
1216 1217 1218
		}
	}

H
hongming 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
	return len(users), nil
}

func ListWorkspaceUsers(workspace string, conditions *params.Conditions, orderBy string, reverse bool, limit, offset int) (*models.PageableResponse, error) {

	workspaceRoleBindings, err := GetWorkspaceRoleBindings(workspace)

	if err != nil {
		return nil, err
	}

	users := make([]*models.User, 0)
H
hongming 已提交
1231

H
hongming 已提交
1232 1233
	for _, roleBinding := range workspaceRoleBindings {
		for _, subject := range roleBinding.Subjects {
1234
			if subject.Kind == rbacv1.UserKind && !k8sutil.ContainsUser(users, subject.Name) {
H
hongming 已提交
1235
				user, err := GetUserInfo(subject.Name)
H
hongming 已提交
1236 1237 1238 1239 1240
				if err != nil {
					return nil, err
				}
				prefix := fmt.Sprintf("workspace:%s:", workspace)
				user.WorkspaceRole = fmt.Sprintf("workspace-%s", strings.TrimPrefix(roleBinding.Name, prefix))
H
hongming 已提交
1241 1242 1243
				if matchConditions(conditions, user) {
					users = append(users, user)
				}
H
hongming 已提交
1244
			}
H
hongming 已提交
1245 1246 1247
		}
	}

H
hongming 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
	// order & reverse
	sort.Slice(users, func(i, j int) bool {
		if reverse {
			tmp := i
			i = j
			j = tmp
		}
		switch orderBy {
		default:
			fallthrough
		case "name":
			return strings.Compare(users[i].Username, users[j].Username) <= 0
		}
	})

	result := make([]interface{}, 0)

	for i, d := range users {
		if i >= offset && (limit == -1 || len(result) < limit) {
			result = append(result, d)
		}
	}
H
hongming 已提交
1270

H
hongming 已提交
1271
	return &models.PageableResponse{Items: result, TotalCount: len(users)}, nil
H
hongming 已提交
1272
}
H
hongming 已提交
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300

func matchConditions(conditions *params.Conditions, user *models.User) bool {
	for k, v := range conditions.Match {
		switch k {
		case "keyword":
			if !strings.Contains(user.Username, v) &&
				!strings.Contains(user.Email, v) &&
				!strings.Contains(user.Description, v) {
				return false
			}
		case "name":
			names := strings.Split(v, "|")
			if !sliceutil.HasString(names, user.Username) {
				return false
			}
		case "email":
			email := strings.Split(v, "|")
			if !sliceutil.HasString(email, user.Email) {
				return false
			}
		case "role":
			if user.WorkspaceRole != v {
				return false
			}
		}
	}
	return true
}