Last active
May 15, 2017 09:30
-
-
Save naokij/d532788cd0320236c59422835dc66c6c to your computer and use it in GitHub Desktop.
ldap验证
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers | |
import ( | |
"errors" | |
"fmt" | |
"bitbucket.org/emagine/vdrill-cp/config" | |
"gopkg.in/ldap.v2" | |
) | |
/* | |
对应的config | |
ldap: | |
host: hostname.yourdomain.com //ldap服务器地址 | |
port: 3268 //ldap服务器端口 | |
attribute: mail //用户名对应ldap object属性 | |
base: DC=yourdomain,DC=com //搜寻范围 | |
user: CN=ldap helper,OU=yourdomain.com,DC=yourdomain,DC=com //第一次绑定用户 | |
password: p@sswd //第一次绑定密码 | |
ssl: false //使用使用ssl | |
*/ | |
//管理员登录表单 | |
type AdminLoginForm struct { | |
Email string `form:"email" valid:"email~login.email_invalid,required~login.email_required"` | |
Password string `form:"password" valid:"required~login.password_required"` | |
Locale string `form:"locale"` | |
} | |
func validLDAPLogin(form *AdminLoginForm) (result bool, err error) { | |
result = false | |
err = nil | |
lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", config.Config.LDAP.Host, config.Config.LDAP.Port)) | |
if err != nil { | |
return | |
} | |
defer lc.Close() | |
err = lc.Bind(config.Config.LDAP.User, config.Config.LDAP.Password) | |
if err != nil { | |
return | |
} | |
searchRequest := ldap.NewSearchRequest( | |
config.Config.LDAP.Base, | |
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, | |
fmt.Sprintf("(&(objectClass=User)(%s=%s))", config.Config.LDAP.Attribute, form.Email), | |
[]string{"dn"}, | |
nil, | |
) | |
searchResult, err := lc.Search(searchRequest) | |
if err != nil { | |
return | |
} | |
if len(searchResult.Entries) != 1 { | |
err = errors.New("ldap.no_user_found_or_many_users_found") | |
} | |
userdn := searchResult.Entries[0].DN | |
err = lc.Bind(userdn, form.Password) | |
if err == nil { | |
result = true | |
} else { | |
err = nil | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment