Skip to content

Commit

Permalink
Merge pull request #1 from alexzyWu/master
Browse files Browse the repository at this point in the history
Add SA User & Fix LDAP BUG
  • Loading branch information
alexzyWu authored Dec 21, 2020
2 parents d75cd91 + 1589894 commit 351b2cf
Show file tree
Hide file tree
Showing 113 changed files with 4,641 additions and 512 deletions.
157 changes: 0 additions & 157 deletions cc/go.sum

Large diffs are not rendered by default.

98 changes: 80 additions & 18 deletions cc/pkg/controller/loginController.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@
package controller

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"github.com/go-ldap/ldap/v3"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/spf13/viper"
"mlss-controlcenter-go/pkg/common"
"mlss-controlcenter-go/pkg/logger"
"mlss-controlcenter-go/pkg/models"
Expand All @@ -32,6 +38,11 @@ import (
"strings"
)

const (
ldapPubKey = "ldapPubKey"
ldapPrivKey = "ldapPrivKey"
)

func UMLogin(params logins.UMLoginParams) middleware.Responder {
username := params.Username
password := params.Password
Expand Down Expand Up @@ -93,13 +104,34 @@ func UMLogin(params logins.UMLoginParams) middleware.Responder {

func LDAPLogin(params logins.LDAPLoginParams) middleware.Responder {
username := params.LoginRequest.Username
password := params.LoginRequest.Password
decodeBytes, err := base64.StdEncoding.DecodeString(params.LoginRequest.Password)
if err != nil {
logger.Logger().Error("failed to login, base64 decode failed:%v", err.Error())
return ResponderFunc(http.StatusInternalServerError, "failed to login, base64 decode failed:", err.Error())
}
decryptPassword, err := RsaDecrypt(decodeBytes)
if err != nil {
logger.Logger().Error("failed to login, rsa decrypt failed:%v", err.Error())
return ResponderFunc(http.StatusInternalServerError, "failed to login, rsa decrypt failed:", err.Error())
}

isAccess, err := LDAPAuth(username, password)
if err != nil || isAccess == false {
isAccess := false
if username == common.GetAppConfig().Application.Admin.User {
if string(decryptPassword) == common.GetAppConfig().Application.Admin.Password {
isAccess = true
}
} else {
isAccess, err = LDAPAuth(username, string(decryptPassword))
if err != nil {
logger.Logger().Error("Failed to login, LDAP Auth Error:", err.Error())
return ResponderFunc(http.StatusBadRequest, "Failed to login, LDAP auth failed:", err.Error())
}
}
if isAccess == false {
return ResponderFunc(http.StatusBadRequest, "failed to login", "failed to login")
}

// Check system permission
p, err := service.CheckUserPermission(username)
if err != nil {
return ResponderFunc(http.StatusInternalServerError, "failed to login", err.Error())
Expand All @@ -108,21 +140,20 @@ func LDAPLogin(params logins.LDAPLoginParams) middleware.Responder {
return ResponderFunc(http.StatusUnauthorized, "failed to login, ", "User does not have system permissions")
}

//Set Session User for Return
isSA := service.GetSAByName(username).Name == username
sessionUser := models.SessionUser{
UserName: username,
IsSuperadmin: service.GetSAByName(username).Name == username,
IsSuperadmin: isSA,
}

logger.Logger().Debugf("sessionUser: %v", sessionUser)

marshal, _ := json.Marshal(sessionUser)
var result = models.Result{
Code: "200",
Message: "success",
Result: json.RawMessage(marshal),
}

//authcache.TokenCache.Set(token, sessionUser, cache.DefaultExpiration)
return middleware.ResponderFunc(func(w http.ResponseWriter, _ runtime.Producer) {
cookie := service.LDAPLogin(w, common.GetAppConfig().Core.Cookie.Path, sessionUser)
http.SetCookie(w, &cookie)
Expand All @@ -132,29 +163,60 @@ func LDAPLogin(params logins.LDAPLoginParams) middleware.Responder {
}

func LDAPAuth(username string, password string) (bool, error) {
l, err := ldap.DialURL(common.GetAppConfig().Application.LDAP)
address := common.GetAppConfig().Application.LDAP.Address
baseDN := common.GetAppConfig().Application.LDAP.BaseDN

//Dial LDAP Server
l, err := ldap.DialURL(address)
if err != nil {
logger.Logger().Errorf("ldap server dial error" + err.Error())
logger.Logger().Errorf("LDAP Dial Fail:%v",err.Error())
return false, err
}
if l == nil {
logger.Logger().Errorf("ldap server dial error, connection is nil")
return false, errors.New("ldap server dial error,connection is nil")
}

passwordDecode, err := base64.StdEncoding.DecodeString(password)
//Search User in LDAP Server
nsr := ldap.NewSearchRequest(baseDN, ldap.ScopeBaseObject, ldap.NeverDerefAliases,
0, 0, false,
fmt.Sprintf("(&(objectClass=organizationalPerson)(uid=%s))", username), []string{"dn"}, nil)
sr, err := l.Search(nsr)
if err != nil {
logger.Logger().Errorf("Password decode Error" + err.Error())
logger.Logger().Errorf("LDAP Search Fail:%v",err.Error())
return false, err
}

_, err = l.SimpleBind(&ldap.SimpleBindRequest{
Username: username,
Password: string(passwordDecode),
})
//Auth User Password
userDN := sr.Entries[0].DN
err = l.Bind(userDN, password)
if err != nil {
logger.Logger().Errorf("LDAP Server Auth Error: %s\n", err)
return false, err
}
defer l.Close()
return true, err
return true, nil
}

func GetRsaPubKey(params logins.GetRsaPubKeyParams) middleware.Responder {
return middleware.ResponderFunc(func(w http.ResponseWriter, _ runtime.Producer) {
var result = models.Result{
Code: "200",
Message: "success",
Result: viper.GetString(ldapPubKey),
}
payload, _ := json.Marshal(result)
w.Write(payload)
})
}

func RsaDecrypt(context []byte) ([]byte, error) {
privateKey := viper.GetString(ldapPrivKey)
block, _ := pem.Decode([]byte(privateKey))
if block == nil {
return nil, errors.New("private key error")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.DecryptPKCS1v15(rand.Reader, priv, context)
}
1 change: 1 addition & 0 deletions cc/pkg/middleware/authInterceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/gin-gonic/gin"
"mlss-controlcenter-go/pkg/common"
"mlss-controlcenter-go/pkg/constants"
"mlss-controlcenter-go/pkg/logger"
)

func AuthInterceptor() gin.HandlerFunc {
Expand Down
36 changes: 9 additions & 27 deletions cc/pkg/models/appConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,15 @@ type Application struct {
Port string `yaml:"port"`
Db string `yaml:"db"`
}
LDAP string `yaml:"ldap"`
Admin struct{
User string `yaml:"user"`
Password string `yaml:"password"`

}
LDAP struct{
Address string `yaml:"server"`
BaseDN string `yaml:"baseDN"`
}
}

type Server struct {
Expand All @@ -60,26 +68,6 @@ type Interceptor struct {
DefaultTimestampTimeout string `yaml:"defaultTimestampTimeout"`
}

// Yaml2 struct of yaml
//type Yaml2 struct {
// Mysql `yaml:"mysql,inline"`
// authcache `yaml:"authcache,inline"`
//}

// Mysql struct of mysql conf
//type Mysql struct {
// User string `yaml:"user"`
// Host string `yaml:"host"`
// Password string `yaml:"password"`
// Port string `yaml:"port"`
// Name string `yaml:"name"`
//}

// authcache struct of authcache conf
//type authcache struct {
// Enable bool `yaml:"enable"`
// List []string `yaml:"list,flow"`
//}
type InterceptorConfig struct {
Name string `yaml:"name"`
Add []string `yaml:"add,flow"`
Expand Down Expand Up @@ -127,12 +115,6 @@ type NamespacedResourceConfig struct {
DefaultRQGpu string `yaml:"defaultRQGpu"`
}

//type Gateway struct {
// BdpAddress string `yaml:"bdpAddress"`
// BdapAddress string `yaml:"bdapAddress"`
// BdapsafeAddress string `yaml:"bdapsafeAddress"`
//}

type AuthAddress struct {
User string `yaml:"user"`
Auth string `yaml:"auth"`
Expand Down
57 changes: 0 additions & 57 deletions cc/pkg/repo/hdfs_privs_repo.go

This file was deleted.

4 changes: 3 additions & 1 deletion cc/pkg/restapi/restapi/configure_mlss_cc.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,9 @@ func configureAPI(api *operations.MlssCcAPI) http.Handler {
api.LoginsLDAPLoginHandler = logins.LDAPLoginHandlerFunc(func(params logins.LDAPLoginParams) middleware.Responder {
return controller.LDAPLogin(params)
})

api.LoginsGetRsaPubKeyHandler = logins.GetRsaPubKeyHandlerFunc(func(params logins.GetRsaPubKeyParams) middleware.Responder {
return controller.GetRsaPubKey(params)
})
api.ServerShutdown = func() {}

return setupGlobalMiddleware(api.Serve(setupMiddlewares))
Expand Down
2 changes: 1 addition & 1 deletion cc/pkg/restapi/restapi/doc.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions cc/pkg/restapi/restapi/embedded_spec.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 351b2cf

Please sign in to comment.