im.go 26.8 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 21 22 23 24
/*

 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 (
	"errors"
	"fmt"
	"kubesphere.io/kubesphere/pkg/constants"
	"kubesphere.io/kubesphere/pkg/informers"
H
hongming 已提交
25 26
	"kubesphere.io/kubesphere/pkg/simple/client/k8s"
	"kubesphere.io/kubesphere/pkg/simple/client/redis"
H
hongming 已提交
27 28 29 30 31 32 33 34 35 36 37
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/go-ldap/ldap"
	"github.com/golang/glog"
	"k8s.io/api/rbac/v1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
H
hongming 已提交
38
	ldapclient "kubesphere.io/kubesphere/pkg/simple/client/ldap"
H
hongming 已提交
39 40 41 42 43 44

	"kubesphere.io/kubesphere/pkg/models"
	jwtutils "kubesphere.io/kubesphere/pkg/utils/jwt"
)

var (
Z
zryfish 已提交
45 46 47 48
	counter         Counter
	adminEmail      string
	adminPassword   string
	tokenExpireTime time.Duration
H
hongming 已提交
49 50
)

Z
zryfish 已提交
51 52 53 54
func Init(email, password string, t time.Duration) error {
	adminEmail = email
	adminPassword = password
	tokenExpireTime = t
H
hongming 已提交
55

H
hongming 已提交
56
	conn, err := ldapclient.Client()
H
hongming 已提交
57 58 59 60 61 62 63

	if err != nil {
		return err
	}

	defer conn.Close()

H
hongming 已提交
64 65
	err = checkAndCreateDefaultUser(conn)

H
hongming 已提交
66 67 68 69
	if err != nil {
		return err
	}

H
hongming 已提交
70 71 72 73 74 75 76 77 78
	err = checkAndCreateDefaultGroup(conn)

	return err
}

func checkAndCreateDefaultGroup(conn ldap.Client) error {

	groupSearchRequest := ldap.NewSearchRequest(
		ldapclient.GroupSearchBase,
H
hongming 已提交
79
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
H
hongming 已提交
80
		"(&(objectClass=posixGroup))",
H
hongming 已提交
81 82 83 84
		nil,
		nil,
	)

H
hongming 已提交
85
	groups, err := conn.Search(groupSearchRequest)
H
hongming 已提交
86

H
hongming 已提交
87 88
	if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
		err = createGroupsBaseDN(conn)
Z
zryfish 已提交
89 90 91
		if err != nil {
			return fmt.Errorf("GroupBaseDN %s create failed: %s\n", ldapclient.GroupSearchBase, err)
		}
H
hongming 已提交
92 93
	}

H
hongming 已提交
94
	if err != nil {
Z
zryfish 已提交
95
		return fmt.Errorf("iam database init failed: %s\n", err)
H
hongming 已提交
96
	}
H
hongming 已提交
97

Z
zryfish 已提交
98
	if groups == nil || len(groups.Entries) == 0 {
H
hongming 已提交
99
		_, err = CreateGroup(models.Group{Path: constants.SystemWorkspace, Name: constants.SystemWorkspace, Creator: constants.AdminUserName, Description: "system workspace"})
H
hongming 已提交
100 101

		if err != nil {
H
hongming 已提交
102
			return fmt.Errorf("system-workspace create failed: %s\n", err)
H
hongming 已提交
103 104 105
		}
	}

H
hongming 已提交
106 107 108 109 110 111 112
	return nil
}

func checkAndCreateDefaultUser(conn ldap.Client) error {

	userSearchRequest := ldap.NewSearchRequest(
		ldapclient.UserSearchBase,
H
hongming 已提交
113
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
H
hongming 已提交
114
		"(&(objectClass=inetOrgPerson))",
H
hongming 已提交
115 116 117 118
		nil,
		nil,
	)

H
hongming 已提交
119
	users, err := conn.Search(userSearchRequest)
H
hongming 已提交
120

H
hongming 已提交
121 122
	if ldap.IsErrorWithCode(err, ldap.LDAPResultNoSuchObject) {
		err = createUserBaseDN(conn)
Z
zryfish 已提交
123 124 125
		if err != nil {
			return fmt.Errorf("UserBaseDN %s create failed: %s\n", ldapclient.UserSearchBase, err)
		}
H
hongming 已提交
126 127
	}

H
hongming 已提交
128
	if err != nil {
Z
zryfish 已提交
129
		return fmt.Errorf("iam database init failed: %s\n", err)
H
hongming 已提交
130
	}
H
hongming 已提交
131

Z
zryfish 已提交
132 133 134
	if users == nil || len(users.Entries) == 0 {
		counter = NewCounter(0)
		err := CreateUser(models.User{Username: constants.AdminUserName, Email: adminEmail, Password: adminPassword, Description: "Administrator account that was always created by default."})
H
hongming 已提交
135
		if err != nil {
H
hongming 已提交
136
			return fmt.Errorf("admin create failed: %s\n", err)
H
hongming 已提交
137
		}
Z
zryfish 已提交
138 139
	} else {
		counter = NewCounter(len(users.Entries))
H
hongming 已提交
140 141 142 143 144
	}

	return nil
}

H
hongming 已提交
145
func createUserBaseDN(conn ldap.Client) error {
H
hongming 已提交
146

H
hongming 已提交
147
	conn, err := ldapclient.Client()
H
hongming 已提交
148 149 150 151 152
	if err != nil {
		return err
	}
	defer conn.Close()

H
hongming 已提交
153
	groupsCreateRequest := ldap.NewAddRequest(ldapclient.UserSearchBase, nil)
H
hongming 已提交
154 155 156 157 158
	groupsCreateRequest.Attribute("objectClass", []string{"organizationalUnit", "top"})
	groupsCreateRequest.Attribute("ou", []string{"Users"})
	return conn.Add(groupsCreateRequest)
}

H
hongming 已提交
159 160
func createGroupsBaseDN(conn ldap.Client) error {
	groupsCreateRequest := ldap.NewAddRequest(ldapclient.GroupSearchBase, nil)
H
hongming 已提交
161 162 163 164 165 166 167 168
	groupsCreateRequest.Attribute("objectClass", []string{"organizationalUnit", "top"})
	groupsCreateRequest.Attribute("ou", []string{"Groups"})
	return conn.Add(groupsCreateRequest)
}

// User login
func Login(username string, password string, ip string) (string, error) {

H
hongming 已提交
169
	conn, err := ldapclient.Client()
H
hongming 已提交
170 171 172 173 174 175 176 177

	if err != nil {
		return "", err
	}

	defer conn.Close()

	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
178
		ldapclient.UserSearchBase,
H
hongming 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
		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 {
		return "", err
	}

	if len(result.Entries) != 1 {
		return "", ldap.NewError(ldap.LDAPResultInvalidCredentials, errors.New("incorrect password"))
	}

	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 {
		return "", err
	}

	claims := jwt.MapClaims{}

Z
zryfish 已提交
208 209 210
	claims["exp"] = time.Now().Add(tokenExpireTime).Unix()
	claims["username"] = uid
	claims["email"] = email
H
hongming 已提交
211 212 213 214 215

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	uToken, _ := token.SignedString(jwtutils.Secret)

Z
zryfish 已提交
216 217
	loginLog(uid, ip)

H
hongming 已提交
218 219 220
	return uToken, nil
}

Z
zryfish 已提交
221 222 223 224 225 226 227 228
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 已提交
229 230
func UserList(limit int, offset int) (int, []models.User, error) {

H
hongming 已提交
231
	conn, err := ldapclient.Client()
H
hongming 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

	if err != nil {
		return 0, nil, err
	}

	defer conn.Close()

	users := make([]models.User, 0)

	pageControl := ldap.NewControlPaging(1000)

	entries := make([]*ldap.Entry, 0)

	cursor := 0
l1:
	for {

		userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
250
			ldapclient.UserSearchBase,
H
hongming 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
			ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
			"(&(objectClass=inetOrgPerson))",
			[]string{"uid", "mail", "description"},
			[]ldap.Control{pageControl},
		)

		response, err := conn.Search(userSearchRequest)

		if err != nil {
			return 0, nil, err
		}

		for _, entry := range response.Entries {
			cursor++
			if cursor > offset {
				if len(entries) < limit {
					entries = append(entries, entry)
				} else {
					break l1
				}
			}
		}

		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 已提交
283
	redisClient := redis.Client()
H
hongming 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

	for _, v := range entries {

		uid := v.GetAttributeValue("uid")
		email := v.GetAttributeValue("mail")
		description := v.GetAttributeValue("description")
		user := models.User{Username: uid, Email: email, Description: description}

		avatar, err := redisClient.HMGet("kubesphere:users:avatar", uid).Result()

		if err != nil {
			return 0, nil, err
		}

		if len(avatar) > 0 {
			if url, ok := avatar[0].(string); ok {
				user.AvatarUrl = url
			}
		}

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

		if err != nil {
			return 0, nil, err
		}

		if len(lastLogin) > 0 {
			user.LastLoginTime = strings.Split(lastLogin[0], ",")[0]
		}

		user.ClusterRules = make([]models.SimpleRule, 0)

		users = append(users, user)
	}

	return counter.Get(), users, nil
}

func LoginLog(username string) ([]string, error) {
H
hongming 已提交
323
	redisClient := redis.Client()
H
hongming 已提交
324 325 326 327 328 329 330 331 332 333 334 335

	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 Search(keyword string, limit int, offset int) (int, []models.User, error) {

H
hongming 已提交
336
	conn, err := ldapclient.Client()
H
hongming 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

	if err != nil {
		return 0, nil, err
	}

	defer conn.Close()

	users := make([]models.User, 0)

	pageControl := ldap.NewControlPaging(80)

	entries := make([]*ldap.Entry, 0)

	cursor := 0
l1:
	for {
		userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
354
			ldapclient.UserSearchBase,
H
hongming 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
			ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
			fmt.Sprintf("(&(objectClass=inetOrgPerson)(|(uid=*%s*)(mail=*%s*)(description=*%s*)))", keyword, keyword, keyword),
			[]string{"uid", "mail", "description"},
			[]ldap.Control{pageControl},
		)

		response, err := conn.Search(userSearchRequest)

		if err != nil {
			return 0, nil, err
		}

		for _, entry := range response.Entries {
			cursor++
			if cursor > offset {
				if len(entries) < limit {
					entries = append(entries, entry)
				} else {
					break l1
				}
			}
		}

		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 已提交
387
	redisClient := redis.Client()
H
hongming 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

	for _, v := range entries {

		uid := v.GetAttributeValue("uid")
		email := v.GetAttributeValue("mail")
		description := v.GetAttributeValue("description")
		user := models.User{Username: uid, Email: email, Description: description}

		avatar, err := redisClient.HMGet("kubesphere:users:avatar", uid).Result()

		if err != nil {
			return 0, nil, err
		}

		if len(avatar) > 0 {
			if url, ok := avatar[0].(string); ok {
				user.AvatarUrl = url
			}
		}

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

		if err != nil {
			return 0, nil, err
		}

		if len(lastLogin) > 0 {
			user.LastLoginTime = strings.Split(lastLogin[0], ",")[0]
		}

		user.ClusterRules = make([]models.SimpleRule, 0)

		users = append(users, user)
	}

	return counter.Get(), users, nil
}

func UserDetail(username string, conn ldap.Client) (*models.User, error) {

	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
429
		ldapclient.UserSearchBase,
H
hongming 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", username),
		[]string{"mail", "description", "preferredLanguage"},
		nil,
	)

	result, err := conn.Search(userSearchRequest)

	if err != nil {
		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")
	user := models.User{Username: username, Email: email, Description: description, Lang: lang}

	groupSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
452
		ldapclient.GroupSearchBase,
H
hongming 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
		ldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(&(objectClass=posixGroup)(memberUid=%s))", username),
		nil,
		nil,
	)

	result, err = conn.Search(groupSearchRequest)

	if err != nil {
		return nil, err

	}

	groups := make([]string, 0)

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

	user.Groups = groups

H
hongming 已提交
475
	redisClient := redis.Client()
H
hongming 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506

	avatar, err := redisClient.HMGet("kubesphere:users:avatar", username).Result()

	if err != nil {
		return nil, err
	}

	if len(avatar) > 0 {
		if url, ok := avatar[0].(string); ok {
			user.AvatarUrl = url
		}
	}

	user.Status = 0

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

	if err != nil {
		return nil, err
	}

	if len(lastLogin) > 0 {
		user.LastLoginTime = strings.Split(lastLogin[0], ",")[0]
	}

	return &user, nil
}

func DeleteUser(username string) error {

	// bind root DN
H
hongming 已提交
507
	conn, err := ldapclient.Client()
H
hongming 已提交
508 509 510 511 512 513
	if err != nil {
		return err
	}

	defer conn.Close()

H
hongming 已提交
514
	deleteRequest := ldap.NewDelRequest(fmt.Sprintf("uid=%s,%s", username, ldapclient.UserSearchBase), nil)
H
hongming 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555

	err = conn.Del(deleteRequest)

	if err != nil {
		return err
	}

	err = deleteRoleBindings(username)

	if err != nil {
		return err
	}

	counter.Sub(1)

	return nil
}

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 {

		length1 := len(roleBinding.Subjects)

		for index, subject := range roleBinding.Subjects {
			if subject.Kind == v1.UserKind && subject.Name == username {
				roleBinding.Subjects = append(roleBinding.Subjects[:index], roleBinding.Subjects[index+1:]...)
				index--
			}
		}

		length2 := len(roleBinding.Subjects)

		if length2 == 0 {
			deletePolicy := meta_v1.DeletePropagationForeground
H
hongming 已提交
556
			err = k8s.Client().RbacV1().RoleBindings(roleBinding.Namespace).Delete(roleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
H
hongming 已提交
557 558 559 560 561

			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 已提交
562
			_, err = k8s.Client().RbacV1().RoleBindings(roleBinding.Namespace).Update(roleBinding)
H
hongming 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

			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 {
		length1 := len(clusterRoleBinding.Subjects)

		for index, subject := range clusterRoleBinding.Subjects {
			if subject.Kind == v1.UserKind && subject.Name == username {
				clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects[:index], clusterRoleBinding.Subjects[index+1:]...)
				index--
			}
		}

		length2 := len(clusterRoleBinding.Subjects)
		if length2 == 0 {
			if groups := regexp.MustCompile(fmt.Sprintf(`^system:(\S+):(%s)$`, strings.Join(constants.WorkSpaceRoles, "|"))).FindStringSubmatch(clusterRoleBinding.RoleRef.Name); len(groups) == 3 {
H
hongming 已提交
586
				_, err = k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
H
hongming 已提交
587 588
			} else {
				deletePolicy := meta_v1.DeletePropagationForeground
H
hongming 已提交
589
				err = k8s.Client().RbacV1().ClusterRoleBindings().Delete(clusterRoleBinding.Name, &meta_v1.DeleteOptions{PropagationPolicy: &deletePolicy})
H
hongming 已提交
590 591 592 593 594
			}
			if err != nil {
				glog.Errorf("update cluster role binding %s failed:%s", clusterRoleBinding.Name, err)
			}
		} else if length2 < length1 {
H
hongming 已提交
595
			_, err = k8s.Client().RbacV1().ClusterRoleBindings().Update(clusterRoleBinding)
H
hongming 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608 609

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

	}

	return nil
}

func UserCreateCheck(check string) (exist bool, err error) {

	// bind root DN
H
hongming 已提交
610
	conn, err := ldapclient.Client()
H
hongming 已提交
611 612 613 614 615 616 617 618 619

	if err != nil {
		return false, err
	}

	defer conn.Close()

	// search for the given username
	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
620
		ldapclient.UserSearchBase,
H
hongming 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
		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 {
		return false, err
	}

	if len(result.Entries) > 0 {
		return true, nil
	} else {
		return false, nil
	}
}

func CreateUser(user models.User) error {
	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 已提交
646
	conn, err := ldapclient.Client()
H
hongming 已提交
647 648 649 650 651 652 653 654

	if err != nil {
		return err
	}

	defer conn.Close()

	userSearchRequest := ldap.NewSearchRequest(
H
hongming 已提交
655
		ldapclient.UserSearchBase,
H
hongming 已提交
656 657 658 659 660 661 662 663 664 665 666 667 668
		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 {
		return err
	}

	if len(result.Entries) > 0 {
Z
zryfish 已提交
669
		return ldap.NewError(ldap.LDAPResultEntryAlreadyExists, fmt.Errorf("username or email already exists"))
H
hongming 已提交
670 671 672 673 674 675 676 677 678 679
	}

	maxUid, err := getMaxUid(conn)

	if err != nil {
		return err
	}

	maxUid += 1

H
hongming 已提交
680
	userCreateRequest := ldap.NewAddRequest(fmt.Sprintf("uid=%s,%s", user.Username, ldapclient.UserSearchBase), nil)
H
hongming 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
	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 != "" {
		userCreateRequest.Attribute("preferredLanguage", []string{user.Lang}) // RFC4519/2307: password of user
	}
	if user.Description != "" {
		userCreateRequest.Attribute("description", []string{user.Description}) // RFC4519: descriptive information
	}

	err = conn.Add(userCreateRequest)

	if err != nil {
		return err
	}

	counter.Add(1)

	if user.ClusterRole != "" {
		CreateClusterRoleBinding(user.Username, user.ClusterRole)
	}

	return nil
}

func getMaxUid(conn ldap.Client) (int, error) {
H
hongming 已提交
713
	userSearchRequest := ldap.NewSearchRequest(ldapclient.UserSearchBase,
H
hongming 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
		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 已提交
743
	groupSearchRequest := ldap.NewSearchRequest(ldapclient.GroupSearchBase,
H
hongming 已提交
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
		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
}

func UpdateUser(user models.User) error {

H
hongming 已提交
773
	conn, err := ldapclient.Client()
H
hongming 已提交
774 775 776 777 778 779
	if err != nil {
		return err
	}

	defer conn.Close()

H
hongming 已提交
780
	dn := fmt.Sprintf("uid=%s,%s", user.Username, ldapclient.UserSearchBase)
H
hongming 已提交
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
	userModifyRequest := ldap.NewModifyRequest(dn, nil)
	if user.Email != "" {
		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})
	}

	err = conn.Modify(userModifyRequest)

	if err != nil {
		return err
	}

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

	if err != nil {
		return err
	}

	return nil
}
func DeleteGroup(path string) error {

	// bind root DN
H
hongming 已提交
814
	conn, err := ldapclient.Client()
H
hongming 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
	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 {
		return err
	}

	return nil
}

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

	// bind root DN
H
hongming 已提交
835
	conn, err := ldapclient.Client()
H
hongming 已提交
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	maxGid, err := getMaxGid(conn)

	if err != nil {
		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})
	}

	groupCreateRequest.Attribute("memberUid", []string{group.Creator})

	err = conn.Add(groupCreateRequest)

	if err != nil {
		return nil, err
	}

	group.Gid = strconv.Itoa(maxGid)

	group.CreateTime = time.Now().UTC().Format("2006-01-02T15:04:05Z")

H
hongming 已提交
876
	redisClient := redis.Client()
H
hongming 已提交
877 878 879 880 881 882 883 884 885 886 887 888 889 890

	if err := redisClient.HMSet("kubesphere:groups:create-time", map[string]interface{}{group.Name: group.CreateTime}).Err(); err != nil {
		return nil, err
	}
	if err := redisClient.HMSet("kubesphere:groups:creator", map[string]interface{}{group.Name: group.Creator}).Err(); err != nil {
		return nil, err
	}

	return &group, nil
}

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

	// bind root DN
H
hongming 已提交
891
	conn, err := ldapclient.Client()
H
hongming 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	old, err := GroupDetail(group.Path, conn)

	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 {
		return nil, err
	}

	return group, nil
}

func CountChild(path string) (int, error) {
	// bind root DN
H
hongming 已提交
934
	conn, err := ldapclient.Client()
H
hongming 已提交
935 936 937 938 939 940 941
	if err != nil {
		return 0, err
	}
	defer conn.Close()

	var groupSearchRequest *ldap.SearchRequest
	if path == "" {
H
hongming 已提交
942
		groupSearchRequest = ldap.NewSearchRequest(ldapclient.GroupSearchBase,
H
hongming 已提交
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
			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 0, err
	}

	return len(result.Entries), nil
}

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

	// bind root DN
H
hongming 已提交
968
	conn, err := ldapclient.Client()
H
hongming 已提交
969 970 971 972 973 974 975 976 977

	if err != nil {
		return nil, err
	}

	defer conn.Close()

	var groupSearchRequest *ldap.SearchRequest
	if path == "" {
H
hongming 已提交
978
		groupSearchRequest = ldap.NewSearchRequest(ldapclient.GroupSearchBase,
H
hongming 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
			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

H
hongming 已提交
1030
		redisClient := redis.Client()
H
hongming 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 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 1079 1080 1081 1082 1083 1084 1085

		createTime, _ := redisClient.HMGet("kubesphere:groups:create-time", group.Name).Result()

		if len(createTime) > 0 {
			if t, ok := createTime[0].(string); ok {
				group.CreateTime = t
			}
		}

		creator, _ := redisClient.HMGet("kubesphere:groups:creator", group.Name).Result()

		if len(creator) > 0 {
			if t, ok := creator[0].(string); ok {
				group.Creator = t
			}
		}

		groups = append(groups, group)
	}

	return groups, nil
}

func GroupDetail(path string, conn ldap.Client) (*models.Group, error) {

	searchBase, cn := splitPath(path)

	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 {
		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 已提交
1086
	redisClient := redis.Client()
H
hongming 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

	createTime, _ := redisClient.HMGet("kubesphere:groups:create-time", group.Name).Result()

	if len(createTime) > 0 {
		if t, ok := createTime[0].(string); ok {
			group.CreateTime = t
		}
	}

	creator, _ := redisClient.HMGet("kubesphere:groups:creator", group.Name).Result()

	if len(creator) > 0 {
		if t, ok := creator[0].(string); ok {
			group.Creator = t
		}
	}

	return &group, nil

}