feat: fix error handling in CheckPassword() related functions

This commit is contained in:
Yang Luo 2023-11-19 19:58:07 +08:00
parent 7786018051
commit 811999b6cc
10 changed files with 150 additions and 114 deletions

View File

@ -34,6 +34,7 @@ import (
"github.com/casdoor/casdoor/proxy" "github.com/casdoor/casdoor/proxy"
"github.com/casdoor/casdoor/util" "github.com/casdoor/casdoor/util"
"github.com/google/uuid" "github.com/google/uuid"
"golang.org/x/oauth2"
) )
var ( var (
@ -331,8 +332,6 @@ func (c *ApiController) Login() {
} }
var user *object.User var user *object.User
var msg string
if authForm.Password == "" { if authForm.Password == "" {
if user, err = object.GetUserByFields(authForm.Organization, authForm.Username); err != nil { if user, err = object.GetUserByFields(authForm.Organization, authForm.Username); err != nil {
c.ResponseError(err.Error(), nil) c.ResponseError(err.Error(), nil)
@ -354,20 +353,21 @@ func (c *ApiController) Login() {
} }
// check result through Email or Phone // check result through Email or Phone
checkResult := object.CheckSigninCode(user, checkDest, authForm.Code, c.GetAcceptLanguage()) err = object.CheckSigninCode(user, checkDest, authForm.Code, c.GetAcceptLanguage())
if len(checkResult) != 0 { if err != nil {
c.ResponseError(fmt.Sprintf("%s - %s", verificationCodeType, checkResult)) c.ResponseError(fmt.Sprintf("%s - %s", verificationCodeType, err.Error()))
return return
} }
// disable the verification code // disable the verification code
err := object.DisableVerificationCode(checkDest) err = object.DisableVerificationCode(checkDest)
if err != nil { if err != nil {
c.ResponseError(err.Error(), nil) c.ResponseError(err.Error(), nil)
return return
} }
} else { } else {
application, err := object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application)) var application *object.Application
application, err = object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application))
if err != nil { if err != nil {
c.ResponseError(err.Error(), nil) c.ResponseError(err.Error(), nil)
return return
@ -386,7 +386,8 @@ func (c *ApiController) Login() {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
} else if enableCaptcha { } else if enableCaptcha {
isHuman, err := captcha.VerifyCaptchaByCaptchaType(authForm.CaptchaType, authForm.CaptchaToken, authForm.ClientSecret) var isHuman bool
isHuman, err = captcha.VerifyCaptchaByCaptchaType(authForm.CaptchaType, authForm.CaptchaToken, authForm.ClientSecret)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -399,13 +400,15 @@ func (c *ApiController) Login() {
} }
password := authForm.Password password := authForm.Password
user, msg = object.CheckUserPassword(authForm.Organization, authForm.Username, password, c.GetAcceptLanguage(), enableCaptcha) user, err = object.CheckUserPassword(authForm.Organization, authForm.Username, password, c.GetAcceptLanguage(), enableCaptcha)
} }
if msg != "" { if err != nil {
resp = &Response{Status: "error", Msg: msg} c.ResponseError(err.Error())
return
} else { } else {
application, err := object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application)) var application *object.Application
application, err = object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application))
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -416,7 +419,8 @@ func (c *ApiController) Login() {
return return
} }
organization, err := object.GetOrganizationByUser(user) var organization *object.Organization
organization, err = object.GetOrganizationByUser(user)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
} }
@ -461,12 +465,15 @@ func (c *ApiController) Login() {
c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), authForm.Application)) c.ResponseError(fmt.Sprintf(c.T("auth:The application: %s does not exist"), authForm.Application))
return return
} }
organization, err := object.GetOrganization(util.GetId("admin", application.Organization))
var organization *object.Organization
organization, err = object.GetOrganization(util.GetId("admin", application.Organization))
if err != nil { if err != nil {
c.ResponseError(c.T(err.Error())) c.ResponseError(c.T(err.Error()))
} }
provider, err := object.GetProvider(util.GetId("admin", authForm.Provider)) var provider *object.Provider
provider, err = object.GetProvider(util.GetId("admin", authForm.Provider))
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -488,7 +495,8 @@ func (c *ApiController) Login() {
} else if provider.Category == "OAuth" || provider.Category == "Web3" { } else if provider.Category == "OAuth" || provider.Category == "Web3" {
// OAuth // OAuth
idpInfo := object.FromProviderToIdpInfo(c.Ctx, provider) idpInfo := object.FromProviderToIdpInfo(c.Ctx, provider)
idProvider, err := idp.GetIdProvider(idpInfo, authForm.RedirectUri) var idProvider idp.IdProvider
idProvider, err = idp.GetIdProvider(idpInfo, authForm.RedirectUri)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -506,7 +514,8 @@ func (c *ApiController) Login() {
} }
// https://github.com/golang/oauth2/issues/123#issuecomment-103715338 // https://github.com/golang/oauth2/issues/123#issuecomment-103715338
token, err := idProvider.GetToken(authForm.Code) var token *oauth2.Token
token, err = idProvider.GetToken(authForm.Code)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -548,7 +557,7 @@ func (c *ApiController) Login() {
c.ResponseError(c.T("check:The user is forbidden to sign in, please contact the administrator")) c.ResponseError(c.T("check:The user is forbidden to sign in, please contact the administrator"))
} }
// sync info from 3rd-party if possible // sync info from 3rd-party if possible
_, err := object.SetUserOAuthProperties(organization, user, provider.Type, userInfo) _, err = object.SetUserOAuthProperties(organization, user, provider.Type, userInfo)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -593,14 +602,16 @@ func (c *ApiController) Login() {
} }
// Handle username conflicts // Handle username conflicts
tmpUser, err := object.GetUser(util.GetId(application.Organization, userInfo.Username)) var tmpUser *object.User
tmpUser, err = object.GetUser(util.GetId(application.Organization, userInfo.Username))
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
} }
if tmpUser != nil { if tmpUser != nil {
uid, err := uuid.NewRandom() var uid uuid.UUID
uid, err = uuid.NewRandom()
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -611,14 +622,16 @@ func (c *ApiController) Login() {
} }
properties := map[string]string{} properties := map[string]string{}
count, err := object.GetUserCount(application.Organization, "", "", "") var count int64
count, err = object.GetUserCount(application.Organization, "", "", "")
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
} }
properties["no"] = strconv.Itoa(int(count + 2)) properties["no"] = strconv.Itoa(int(count + 2))
initScore, err := organization.GetInitScore() var initScore int
initScore, err = organization.GetInitScore()
if err != nil { if err != nil {
c.ResponseError(fmt.Errorf(c.T("account:Get init score failed, error: %w"), err).Error()) c.ResponseError(fmt.Errorf(c.T("account:Get init score failed, error: %w"), err).Error())
return return
@ -650,7 +663,8 @@ func (c *ApiController) Login() {
Properties: properties, Properties: properties,
} }
affected, err := object.AddUser(user) var affected bool
affected, err = object.AddUser(user)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -672,7 +686,7 @@ func (c *ApiController) Login() {
} }
// sync info from 3rd-party if possible // sync info from 3rd-party if possible
_, err := object.SetUserOAuthProperties(organization, user, provider.Type, userInfo) _, err = object.SetUserOAuthProperties(organization, user, provider.Type, userInfo)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -708,7 +722,8 @@ func (c *ApiController) Login() {
return return
} }
oldUser, err := object.GetUserByField(application.Organization, provider.Type, userInfo.Id) var oldUser *object.User
oldUser, err = object.GetUserByField(application.Organization, provider.Type, userInfo.Id)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -719,7 +734,8 @@ func (c *ApiController) Login() {
return return
} }
user, err := object.GetUser(userId) var user *object.User
user, err = object.GetUser(userId)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -732,7 +748,8 @@ func (c *ApiController) Login() {
return return
} }
isLinked, err := object.LinkUserAccount(user, provider.Type, userInfo.Id) var isLinked bool
isLinked, err = object.LinkUserAccount(user, provider.Type, userInfo.Id)
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -745,7 +762,8 @@ func (c *ApiController) Login() {
} }
} }
} else if c.getMfaUserSession() != "" { } else if c.getMfaUserSession() != "" {
user, err := object.GetUser(c.getMfaUserSession()) var user *object.User
user, err = object.GetUser(c.getMfaUserSession())
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -778,7 +796,8 @@ func (c *ApiController) Login() {
return return
} }
application, err := object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application)) var application *object.Application
application, err = object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application))
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return
@ -799,7 +818,8 @@ func (c *ApiController) Login() {
} else { } else {
if c.GetSessionUsername() != "" { if c.GetSessionUsername() != "" {
// user already signed in to Casdoor, so let the user click the avatar button to do the quick sign-in // user already signed in to Casdoor, so let the user click the avatar button to do the quick sign-in
application, err := object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application)) var application *object.Application
application, err = object.GetApplication(fmt.Sprintf("admin/%s", authForm.Application))
if err != nil { if err != nil {
c.ResponseError(err.Error()) c.ResponseError(err.Error())
return return

View File

@ -476,16 +476,16 @@ func (c *ApiController) SetPassword() {
isAdmin := c.IsAdmin() isAdmin := c.IsAdmin()
if isAdmin { if isAdmin {
if oldPassword != "" { if oldPassword != "" {
msg := object.CheckPassword(targetUser, oldPassword, c.GetAcceptLanguage()) err = object.CheckPassword(targetUser, oldPassword, c.GetAcceptLanguage())
if msg != "" { if err != nil {
c.ResponseError(msg) c.ResponseError(err.Error())
return return
} }
} }
} else if code == "" { } else if code == "" {
msg := object.CheckPassword(targetUser, oldPassword, c.GetAcceptLanguage()) err = object.CheckPassword(targetUser, oldPassword, c.GetAcceptLanguage())
if msg != "" { if err != nil {
c.ResponseError(msg) c.ResponseError(err.Error())
return return
} }
} }
@ -518,11 +518,11 @@ func (c *ApiController) CheckUserPassword() {
return return
} }
_, msg := object.CheckUserPassword(user.Owner, user.Name, user.Password, c.GetAcceptLanguage()) _, err = object.CheckUserPassword(user.Owner, user.Name, user.Password, c.GetAcceptLanguage())
if msg == "" { if err != nil {
c.ResponseOk() c.ResponseError(err.Error())
} else { } else {
c.ResponseError(msg) c.ResponseOk()
} }
} }

View File

@ -49,20 +49,20 @@ func handleBind(w ldap.ResponseWriter, m *ldap.Message) {
if r.AuthenticationChoice() == "simple" { if r.AuthenticationChoice() == "simple" {
bindUsername, bindOrg, err := getNameAndOrgFromDN(string(r.Name())) bindUsername, bindOrg, err := getNameAndOrgFromDN(string(r.Name()))
if err != "" { if err != nil {
log.Printf("Bind failed ,ErrMsg=%s", err) log.Printf("getNameAndOrgFromDN() error: %s", err.Error())
res.SetResultCode(ldap.LDAPResultInvalidDNSyntax) res.SetResultCode(ldap.LDAPResultInvalidDNSyntax)
res.SetDiagnosticMessage("bind failed ErrMsg: " + err) res.SetDiagnosticMessage(fmt.Sprintf("getNameAndOrgFromDN() error: %s", err.Error()))
w.Write(res) w.Write(res)
return return
} }
bindPassword := string(r.AuthenticationSimple()) bindPassword := string(r.AuthenticationSimple())
bindUser, err := object.CheckUserPassword(bindOrg, bindUsername, bindPassword, "en") bindUser, err := object.CheckUserPassword(bindOrg, bindUsername, bindPassword, "en")
if err != "" { if err != nil {
log.Printf("Bind failed User=%s, Pass=%#v, ErrMsg=%s", string(r.Name()), r.Authentication(), err) log.Printf("Bind failed User=%s, Pass=%#v, ErrMsg=%s", string(r.Name()), r.Authentication(), err)
res.SetResultCode(ldap.LDAPResultInvalidCredentials) res.SetResultCode(ldap.LDAPResultInvalidCredentials)
res.SetDiagnosticMessage("invalid credentials ErrMsg: " + err) res.SetDiagnosticMessage("invalid credentials ErrMsg: " + err.Error())
w.Write(res) w.Write(res)
return return
} }
@ -78,7 +78,7 @@ func handleBind(w ldap.ResponseWriter, m *ldap.Message) {
m.Client.OrgName = bindOrg m.Client.OrgName = bindOrg
} else { } else {
res.SetResultCode(ldap.LDAPResultAuthMethodNotSupported) res.SetResultCode(ldap.LDAPResultAuthMethodNotSupported)
res.SetDiagnosticMessage("Authentication method not supported,Please use Simple Authentication") res.SetDiagnosticMessage("Authentication method not supported, please use Simple Authentication")
} }
w.Write(res) w.Write(res)
} }

View File

@ -26,7 +26,7 @@ import (
ldap "github.com/forestmgy/ldapserver" ldap "github.com/forestmgy/ldapserver"
) )
func getNameAndOrgFromDN(DN string) (string, string, string) { func getNameAndOrgFromDN(DN string) (string, string, error) {
DNFields := strings.Split(DN, ",") DNFields := strings.Split(DN, ",")
params := make(map[string]string, len(DNFields)) params := make(map[string]string, len(DNFields))
for _, field := range DNFields { for _, field := range DNFields {
@ -37,12 +37,12 @@ func getNameAndOrgFromDN(DN string) (string, string, string) {
} }
if params["cn"] == "" { if params["cn"] == "" {
return "", "", "please use Admin Name format like cn=xxx,ou=xxx,dc=example,dc=com" return "", "", fmt.Errorf("please use Admin Name format like cn=xxx,ou=xxx,dc=example,dc=com")
} }
if params["ou"] == "" { if params["ou"] == "" {
return params["cn"], object.CasdoorOrganization, "" return params["cn"], object.CasdoorOrganization, nil
} }
return params["cn"], params["ou"], "" return params["cn"], params["ou"], nil
} }
func getNameAndOrgFromFilter(baseDN, filter string) (string, string, int) { func getNameAndOrgFromFilter(baseDN, filter string) (string, string, int) {
@ -50,7 +50,11 @@ func getNameAndOrgFromFilter(baseDN, filter string) (string, string, int) {
return "", "", ldap.LDAPResultInvalidDNSyntax return "", "", ldap.LDAPResultInvalidDNSyntax
} }
name, org, _ := getNameAndOrgFromDN(fmt.Sprintf("cn=%s,", getUsername(filter)) + baseDN) name, org, err := getNameAndOrgFromDN(fmt.Sprintf("cn=%s,", getUsername(filter)) + baseDN)
if err != nil {
panic(err)
}
return name, org, ldap.LDAPResultSuccess return name, org, ldap.LDAPResultSuccess
} }

View File

@ -142,7 +142,7 @@ func CheckUserSignup(application *Application, organization *Organization, form
return "" return ""
} }
func checkSigninErrorTimes(user *User, lang string) string { func checkSigninErrorTimes(user *User, lang string) error {
if user.SigninWrongTimes >= SigninWrongTimesLimit { if user.SigninWrongTimes >= SigninWrongTimesLimit {
lastSignWrongTime, _ := time.Parse(time.RFC3339, user.LastSigninWrongTime) lastSignWrongTime, _ := time.Parse(time.RFC3339, user.LastSigninWrongTime)
passedTime := time.Now().UTC().Sub(lastSignWrongTime) passedTime := time.Now().UTC().Sub(lastSignWrongTime)
@ -150,37 +150,39 @@ func checkSigninErrorTimes(user *User, lang string) string {
// deny the login if the error times is greater than the limit and the last login time is less than the duration // deny the login if the error times is greater than the limit and the last login time is less than the duration
if minutes > 0 { if minutes > 0 {
return fmt.Sprintf(i18n.Translate(lang, "check:You have entered the wrong password or code too many times, please wait for %d minutes and try again"), minutes) return fmt.Errorf(i18n.Translate(lang, "check:You have entered the wrong password or code too many times, please wait for %d minutes and try again"), minutes)
} }
// reset the error times // reset the error times
user.SigninWrongTimes = 0 user.SigninWrongTimes = 0
UpdateUser(user.GetId(), user, []string{"signin_wrong_times"}, false) _, err := UpdateUser(user.GetId(), user, []string{"signin_wrong_times"}, false)
return err
} }
return "" return nil
} }
func CheckPassword(user *User, password string, lang string, options ...bool) string { func CheckPassword(user *User, password string, lang string, options ...bool) error {
enableCaptcha := false enableCaptcha := false
if len(options) > 0 { if len(options) > 0 {
enableCaptcha = options[0] enableCaptcha = options[0]
} }
// check the login error times // check the login error times
if !enableCaptcha { if !enableCaptcha {
if msg := checkSigninErrorTimes(user, lang); msg != "" { err := checkSigninErrorTimes(user, lang)
return msg if err != nil {
return err
} }
} }
organization, err := GetOrganizationByUser(user) organization, err := GetOrganizationByUser(user)
if err != nil { if err != nil {
panic(err) return err
} }
if organization == nil { if organization == nil {
return i18n.Translate(lang, "check:Organization does not exist") return fmt.Errorf(i18n.Translate(lang, "check:Organization does not exist"))
} }
passwordType := user.PasswordType passwordType := user.PasswordType
@ -191,19 +193,17 @@ func CheckPassword(user *User, password string, lang string, options ...bool) st
if credManager != nil { if credManager != nil {
if organization.MasterPassword != "" { if organization.MasterPassword != "" {
if credManager.IsPasswordCorrect(password, organization.MasterPassword, "", organization.PasswordSalt) { if credManager.IsPasswordCorrect(password, organization.MasterPassword, "", organization.PasswordSalt) {
resetUserSigninErrorTimes(user) return resetUserSigninErrorTimes(user)
return ""
} }
} }
if credManager.IsPasswordCorrect(password, user.Password, user.PasswordSalt, organization.PasswordSalt) { if credManager.IsPasswordCorrect(password, user.Password, user.PasswordSalt, organization.PasswordSalt) {
resetUserSigninErrorTimes(user) return resetUserSigninErrorTimes(user)
return ""
} }
return recordSigninErrorInfo(user, lang, enableCaptcha) return recordSigninErrorInfo(user, lang, enableCaptcha)
} else { } else {
return fmt.Sprintf(i18n.Translate(lang, "check:unsupported password type: %s"), organization.PasswordType) return fmt.Errorf(i18n.Translate(lang, "check:unsupported password type: %s"), organization.PasswordType)
} }
} }
@ -217,10 +217,10 @@ func CheckPasswordComplexity(user *User, password string) string {
return CheckPasswordComplexityByOrg(organization, password) return CheckPasswordComplexityByOrg(organization, password)
} }
func checkLdapUserPassword(user *User, password string, lang string) string { func checkLdapUserPassword(user *User, password string, lang string) error {
ldaps, err := GetLdaps(user.Owner) ldaps, err := GetLdaps(user.Owner)
if err != nil { if err != nil {
return err.Error() return err
} }
ldapLoginSuccess := false ldapLoginSuccess := false
@ -237,14 +237,14 @@ func checkLdapUserPassword(user *User, password string, lang string) string {
searchResult, err := conn.Conn.Search(searchReq) searchResult, err := conn.Conn.Search(searchReq)
if err != nil { if err != nil {
return err.Error() return err
} }
if len(searchResult.Entries) == 0 { if len(searchResult.Entries) == 0 {
continue continue
} }
if len(searchResult.Entries) > 1 { if len(searchResult.Entries) > 1 {
return i18n.Translate(lang, "check:Multiple accounts with same uid, please check your ldap server") return fmt.Errorf(i18n.Translate(lang, "check:Multiple accounts with same uid, please check your ldap server"))
} }
hit = true hit = true
@ -257,45 +257,47 @@ func checkLdapUserPassword(user *User, password string, lang string) string {
if !ldapLoginSuccess { if !ldapLoginSuccess {
if !hit { if !hit {
return "user not exist" return fmt.Errorf("user not exist")
} }
return i18n.Translate(lang, "check:LDAP user name or password incorrect") return fmt.Errorf(i18n.Translate(lang, "check:LDAP user name or password incorrect"))
} }
return "" return nil
} }
func CheckUserPassword(organization string, username string, password string, lang string, options ...bool) (*User, string) { func CheckUserPassword(organization string, username string, password string, lang string, options ...bool) (*User, error) {
enableCaptcha := false enableCaptcha := false
if len(options) > 0 { if len(options) > 0 {
enableCaptcha = options[0] enableCaptcha = options[0]
} }
user, err := GetUserByFields(organization, username) user, err := GetUserByFields(organization, username)
if err != nil { if err != nil {
panic(err) return nil, err
} }
if user == nil || user.IsDeleted { if user == nil || user.IsDeleted {
return nil, fmt.Sprintf(i18n.Translate(lang, "general:The user: %s doesn't exist"), util.GetId(organization, username)) return nil, fmt.Errorf(i18n.Translate(lang, "general:The user: %s doesn't exist"), util.GetId(organization, username))
} }
if user.IsForbidden { if user.IsForbidden {
return nil, i18n.Translate(lang, "check:The user is forbidden to sign in, please contact the administrator") return nil, fmt.Errorf(i18n.Translate(lang, "check:The user is forbidden to sign in, please contact the administrator"))
} }
if user.Ldap != "" { if user.Ldap != "" {
// ONLY for ldap users // only for LDAP users
if msg := checkLdapUserPassword(user, password, lang); msg != "" { err = checkLdapUserPassword(user, password, lang)
if msg == "user not exist" { if err != nil {
return nil, fmt.Sprintf(i18n.Translate(lang, "check:The user: %s doesn't exist in LDAP server"), username) if err.Error() == "user not exist" {
return nil, fmt.Errorf(i18n.Translate(lang, "check:The user: %s doesn't exist in LDAP server"), username)
} }
return nil, msg return nil, err
} }
} else { } else {
if msg := CheckPassword(user, password, lang, enableCaptcha); msg != "" { err = CheckPassword(user, password, lang, enableCaptcha)
return nil, msg if err != nil {
return nil, err
} }
} }
return user, "" return user, nil
} }
func CheckUserPermission(requestUserId, userId string, strict bool, lang string) (bool, error) { func CheckUserPermission(requestUserId, userId string, strict bool, lang string) (bool, error) {
@ -308,7 +310,7 @@ func CheckUserPermission(requestUserId, userId string, strict bool, lang string)
if userId != "" { if userId != "" {
targetUser, err := GetUser(userId) targetUser, err := GetUser(userId)
if err != nil { if err != nil {
panic(err) return false, err
} }
if targetUser == nil { if targetUser == nil {

View File

@ -36,20 +36,23 @@ func isValidRealName(s string) bool {
return reRealName.MatchString(s) return reRealName.MatchString(s)
} }
func resetUserSigninErrorTimes(user *User) { func resetUserSigninErrorTimes(user *User) error {
// if the password is correct and wrong times is not zero, reset the error times // if the password is correct and wrong times is not zero, reset the error times
if user.SigninWrongTimes == 0 { if user.SigninWrongTimes == 0 {
return return nil
} }
user.SigninWrongTimes = 0 user.SigninWrongTimes = 0
UpdateUser(user.GetId(), user, []string{"signin_wrong_times", "last_signin_wrong_time"}, false) _, err := UpdateUser(user.GetId(), user, []string{"signin_wrong_times", "last_signin_wrong_time"}, false)
return err
} }
func recordSigninErrorInfo(user *User, lang string, options ...bool) string { func recordSigninErrorInfo(user *User, lang string, options ...bool) error {
enableCaptcha := false enableCaptcha := false
if len(options) > 0 { if len(options) > 0 {
enableCaptcha = options[0] enableCaptcha = options[0]
} }
// increase failed login count // increase failed login count
if user.SigninWrongTimes < SigninWrongTimesLimit { if user.SigninWrongTimes < SigninWrongTimesLimit {
user.SigninWrongTimes++ user.SigninWrongTimes++
@ -61,13 +64,18 @@ func recordSigninErrorInfo(user *User, lang string, options ...bool) string {
} }
// update user // update user
UpdateUser(user.GetId(), user, []string{"signin_wrong_times", "last_signin_wrong_time"}, false) _, err := UpdateUser(user.GetId(), user, []string{"signin_wrong_times", "last_signin_wrong_time"}, false)
if err != nil {
return err
}
leftChances := SigninWrongTimesLimit - user.SigninWrongTimes leftChances := SigninWrongTimesLimit - user.SigninWrongTimes
if leftChances == 0 && enableCaptcha { if leftChances == 0 && enableCaptcha {
return fmt.Sprint(i18n.Translate(lang, "check:password or code is incorrect")) return fmt.Errorf(i18n.Translate(lang, "check:password or code is incorrect"))
} else if leftChances >= 0 { } else if leftChances >= 0 {
return fmt.Sprintf(i18n.Translate(lang, "check:password or code is incorrect, you have %d remaining chances"), leftChances) return fmt.Errorf(i18n.Translate(lang, "check:password or code is incorrect, you have %d remaining chances"), leftChances)
} }
// don't show the chance error message if the user has no chance left // don't show the chance error message if the user has no chance left
return fmt.Sprintf(i18n.Translate(lang, "check:You have entered the wrong password or code too many times, please wait for %d minutes and try again"), int(LastSignWrongTimeDuration.Minutes())) return fmt.Errorf(i18n.Translate(lang, "check:You have entered the wrong password or code too many times, please wait for %d minutes and try again"), int(LastSignWrongTimeDuration.Minutes()))
} }

View File

@ -621,25 +621,25 @@ func GetPasswordToken(application *Application, username string, password string
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
if user == nil { if user == nil {
return nil, &TokenError{ return nil, &TokenError{
Error: InvalidGrant, Error: InvalidGrant,
ErrorDescription: "the user does not exist", ErrorDescription: "the user does not exist",
}, nil }, nil
} }
var msg string
if user.Ldap != "" { if user.Ldap != "" {
msg = checkLdapUserPassword(user, password, "en") err = checkLdapUserPassword(user, password, "en")
} else { } else {
msg = CheckPassword(user, password, "en") err = CheckPassword(user, password, "en")
} }
if msg != "" { if err != nil {
return nil, &TokenError{ return nil, &TokenError{
Error: InvalidGrant, Error: InvalidGrant,
ErrorDescription: "invalid username or password", ErrorDescription: fmt.Sprintf("invalid username or password: %s", err.Error()),
}, nil }, nil
} }
if user.IsForbidden { if user.IsForbidden {
return nil, &TokenError{ return nil, &TokenError{
Error: InvalidGrant, Error: InvalidGrant,

View File

@ -192,32 +192,32 @@ func CheckVerificationCode(dest string, code string, lang string) *VerifyResult
return &VerifyResult{VerificationSuccess, ""} return &VerifyResult{VerificationSuccess, ""}
} }
func DisableVerificationCode(dest string) (err error) { func DisableVerificationCode(dest string) error {
record, err := getVerificationRecord(dest) record, err := getVerificationRecord(dest)
if record == nil || err != nil { if record == nil || err != nil {
return return nil
} }
record.IsUsed = true record.IsUsed = true
_, err = ormer.Engine.ID(core.PK{record.Owner, record.Name}).AllCols().Update(record) _, err = ormer.Engine.ID(core.PK{record.Owner, record.Name}).AllCols().Update(record)
return return err
} }
func CheckSigninCode(user *User, dest, code, lang string) string { func CheckSigninCode(user *User, dest, code, lang string) error {
// check the login error times // check the login error times
if msg := checkSigninErrorTimes(user, lang); msg != "" { err := checkSigninErrorTimes(user, lang)
return msg if err != nil {
return err
} }
result := CheckVerificationCode(dest, code, lang) result := CheckVerificationCode(dest, code, lang)
switch result.Code { switch result.Code {
case VerificationSuccess: case VerificationSuccess:
resetUserSigninErrorTimes(user) return resetUserSigninErrorTimes(user)
return ""
case wrongCodeError: case wrongCodeError:
return recordSigninErrorInfo(user, lang) return recordSigninErrorInfo(user, lang)
default: default:
return result.Msg return fmt.Errorf(result.Msg)
} }
} }

View File

@ -55,15 +55,18 @@ func handleAccessRequest(w radius.ResponseWriter, r *radius.Request) {
password := rfc2865.UserPassword_GetString(r.Packet) password := rfc2865.UserPassword_GetString(r.Packet)
organization := rfc2865.Class_GetString(r.Packet) organization := rfc2865.Class_GetString(r.Packet)
log.Printf("handleAccessRequest() username=%v, org=%v, password=%v", username, organization, password) log.Printf("handleAccessRequest() username=%v, org=%v, password=%v", username, organization, password)
if organization == "" { if organization == "" {
w.Write(r.Response(radius.CodeAccessReject)) w.Write(r.Response(radius.CodeAccessReject))
return return
} }
_, msg := object.CheckUserPassword(organization, username, password, "en")
if msg != "" { _, err := object.CheckUserPassword(organization, username, password, "en")
if err != nil {
w.Write(r.Response(radius.CodeAccessReject)) w.Write(r.Response(radius.CodeAccessReject))
return return
} }
w.Write(r.Response(radius.CodeAccessAccept)) w.Write(r.Response(radius.CodeAccessAccept))
} }

View File

@ -83,13 +83,12 @@ func AutoSigninFilter(ctx *context.Context) {
password := ctx.Input.Query("password") password := ctx.Input.Query("password")
if userId != "" && password != "" && ctx.Input.Query("grant_type") == "" { if userId != "" && password != "" && ctx.Input.Query("grant_type") == "" {
owner, name := util.GetOwnerAndNameFromId(userId) owner, name := util.GetOwnerAndNameFromId(userId)
_, msg := object.CheckUserPassword(owner, name, password, "en") _, err = object.CheckUserPassword(owner, name, password, "en")
if msg != "" { if err != nil {
responseError(ctx, msg) responseError(ctx, err.Error())
return return
} }
setSessionUser(ctx, userId) setSessionUser(ctx, userId)
return
} }
} }