Skip to content

Commit

Permalink
feat: support i18n in backend err messages (casdoor#1232)
Browse files Browse the repository at this point in the history
* feat: support i18n in backend err messages

* use gofumpt to fmt code

* fix review problems

* support auto generate err message

* delete beego/i18n moudle

* fix Github action test problems

* fix review problems

* use gofumpt to format code

* use gofumpt to fmt code
  • Loading branch information
forestmgy authored Oct 23, 2022
1 parent 7c77519 commit d86f3c8
Show file tree
Hide file tree
Showing 64 changed files with 1,838 additions and 194 deletions.
1 change: 1 addition & 0 deletions conf/app.conf
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ staticBaseUrl = "https://cdn.casbin.org"
isDemoMode = false
batchSize = 100
ldapServerPort = 389
languages = en,zh,es,fr,de,ja,ko,ru
20 changes: 10 additions & 10 deletions controllers/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ type Captcha struct {
// @router /signup [post]
func (c *ApiController) Signup() {
if c.GetSessionUsername() != "" {
c.ResponseError("Please sign out first before signing up", c.GetSessionUsername())
c.ResponseError(c.T("SignUpErr.SignOutFirst"), c.GetSessionUsername())
return
}

Expand All @@ -111,31 +111,31 @@ func (c *ApiController) Signup() {

application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
if !application.EnableSignUp {
c.ResponseError("The application does not allow to sign up new account")
c.ResponseError(c.T("SignUpErr.DoNotAllowSignUp"))
return
}

organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", form.Organization))
msg := object.CheckUserSignup(application, organization, form.Username, form.Password, form.Name, form.FirstName, form.LastName, form.Email, form.Phone, form.Affiliation)
msg := object.CheckUserSignup(application, organization, form.Username, form.Password, form.Name, form.FirstName, form.LastName, form.Email, form.Phone, form.Affiliation, c.GetAcceptLanguage())
if msg != "" {
c.ResponseError(msg)
return
}

if application.IsSignupItemVisible("Email") && application.GetSignupItemRule("Email") != "No verification" && form.Email != "" {
checkResult := object.CheckVerificationCode(form.Email, form.EmailCode)
checkResult := object.CheckVerificationCode(form.Email, form.EmailCode, c.GetAcceptLanguage())
if len(checkResult) != 0 {
c.ResponseError(fmt.Sprintf("Email: %s", checkResult))
c.ResponseError(c.T("EmailErr.EmailCheckResult"), checkResult)
return
}
}

var checkPhone string
if application.IsSignupItemVisible("Phone") && form.Phone != "" {
checkPhone = fmt.Sprintf("+%s%s", form.PhonePrefix, form.Phone)
checkResult := object.CheckVerificationCode(checkPhone, form.PhoneCode)
checkResult := object.CheckVerificationCode(checkPhone, form.PhoneCode, c.GetAcceptLanguage())
if len(checkResult) != 0 {
c.ResponseError(fmt.Sprintf("Phone: %s", checkResult))
c.ResponseError(c.T("PhoneErr.PhoneCheckResult"), checkResult)
return
}
}
Expand All @@ -159,7 +159,7 @@ func (c *ApiController) Signup() {

initScore, err := getInitScore()
if err != nil {
c.ResponseError(fmt.Errorf("get init score failed, error: %w", err).Error())
c.ResponseError(fmt.Errorf(c.T("InitErr.InitScoreFailed"), err).Error())
return
}

Expand Down Expand Up @@ -205,7 +205,7 @@ func (c *ApiController) Signup() {

affected := object.AddUser(user)
if !affected {
c.ResponseError(fmt.Sprintf("Failed to create user, user information is invalid: %s", util.StructToJson(user)))
c.ResponseError(c.T("UserErr.InvalidInformation"), util.StructToJson(user))
return
}

Expand Down Expand Up @@ -309,7 +309,7 @@ func (c *ApiController) GetCaptcha() {
applicationId := c.Input().Get("applicationId")
isCurrentProvider := c.Input().Get("isCurrentProvider")

captchaProvider, err := object.GetCaptchaProviderByApplication(applicationId, isCurrentProvider)
captchaProvider, err := object.GetCaptchaProviderByApplication(applicationId, isCurrentProvider, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
Expand Down
4 changes: 2 additions & 2 deletions controllers/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func (c *ApiController) GetUserApplication() {
id := c.Input().Get("id")
user := object.GetUser(id)
if user == nil {
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", id))
c.ResponseError(fmt.Sprintf(c.T("UserErr.DoNotExist"), id))
return
}

Expand All @@ -107,7 +107,7 @@ func (c *ApiController) GetOrganizationApplications() {
organization := c.Input().Get("organization")

if organization == "" {
c.ResponseError("Parameter organization is missing")
c.ResponseError(c.T("ParameterErr.OrgMissingErr"))
return
}

Expand Down
54 changes: 27 additions & 27 deletions controllers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob
return
}
if !allowed {
c.ResponseError("Unauthorized operation")
c.ResponseError(c.T("AuthErr.Unauthorized"))
return
}

Expand All @@ -75,10 +75,10 @@ func (c *ApiController) HandleLoggedIn(application *object.Application, user *ob
codeChallenge := c.Input().Get("code_challenge")

if challengeMethod != "S256" && challengeMethod != "null" && challengeMethod != "" {
c.ResponseError("Challenge method should be S256")
c.ResponseError(c.T("AuthErr.ChallengeMethodErr"))
return
}
code := object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge, c.Ctx.Request.Host)
code := object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge, c.Ctx.Request.Host, c.GetAcceptLanguage())
resp = codeToResponse(code)

if application.EnableSigninSession || application.HasPromptPage() {
Expand Down Expand Up @@ -151,7 +151,7 @@ func (c *ApiController) GetApplicationLogin() {
scope := c.Input().Get("scope")
state := c.Input().Get("state")

msg, application := object.CheckOAuthLogin(clientId, responseType, redirectUri, scope, state)
msg, application := object.CheckOAuthLogin(clientId, responseType, redirectUri, scope, state, c.GetAcceptLanguage())
application = object.GetMaskedApplication(application, "")
if msg != "" {
c.ResponseError(msg, application)
Expand Down Expand Up @@ -196,7 +196,7 @@ func (c *ApiController) Login() {
if form.Username != "" {
if form.Type == ResponseTypeLogin {
if c.GetSessionUsername() != "" {
c.ResponseError("Please sign out first before signing in", c.GetSessionUsername())
c.ResponseError(c.T("LoginErr.SignOutFirst"), c.GetSessionUsername())
return
}
}
Expand All @@ -218,19 +218,19 @@ func (c *ApiController) Login() {
if user != nil && util.GetMaskedEmail(user.Email) == form.Username {
form.Username = user.Email
}
checkResult = object.CheckVerificationCode(form.Username, form.Code)
checkResult = object.CheckVerificationCode(form.Username, form.Code, c.GetAcceptLanguage())
} else {
verificationCodeType = "phone"
if len(form.PhonePrefix) == 0 {
responseText := fmt.Sprintf("%s%s", verificationCodeType, "No phone prefix")
responseText := fmt.Sprintf(c.T("PhoneErr.NoPrefix"), verificationCodeType)
c.ResponseError(responseText)
return
}
if user != nil && util.GetMaskedPhone(user.Phone) == form.Username {
form.Username = user.Phone
}
checkPhone := fmt.Sprintf("+%s%s", form.PhonePrefix, form.Username)
checkResult = object.CheckVerificationCode(checkPhone, form.Code)
checkResult = object.CheckVerificationCode(checkPhone, form.Code, c.GetAcceptLanguage())
}
if len(checkResult) != 0 {
responseText := fmt.Sprintf("%s%s", verificationCodeType, checkResult)
Expand All @@ -247,20 +247,20 @@ func (c *ApiController) Login() {

user = object.GetUserByFields(form.Organization, form.Username)
if user == nil {
c.ResponseError(fmt.Sprintf("The user: %s/%s doesn't exist", form.Organization, form.Username))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.UserDoNotExist"), form.Organization, form.Username))
return
}
} else {
password := form.Password
user, msg = object.CheckUserPassword(form.Organization, form.Username, password)
user, msg = object.CheckUserPassword(form.Organization, form.Username, password, c.GetAcceptLanguage())
}

if msg != "" {
resp = &Response{Status: "error", Msg: msg}
} else {
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
if application == nil {
c.ResponseError(fmt.Sprintf("The application: %s does not exist", form.Application))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.AppDoNotExist"), form.Application))
return
}

Expand All @@ -274,15 +274,15 @@ func (c *ApiController) Login() {
} else if form.Provider != "" {
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
if application == nil {
c.ResponseError(fmt.Sprintf("The application: %s does not exist", form.Application))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.AppDoNotExist"), form.Application))
return
}

organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", application.Organization))
provider := object.GetProvider(fmt.Sprintf("admin/%s", form.Provider))
providerItem := application.GetProviderItem(provider.Name)
if !providerItem.IsProviderVisible() {
c.ResponseError(fmt.Sprintf("The provider: %s is not enabled for the application", provider.Name))
c.ResponseError(fmt.Sprintf(c.T("ProviderErr.ProviderNotEnabled"), provider.Name))
return
}

Expand All @@ -306,14 +306,14 @@ func (c *ApiController) Login() {

idProvider := idp.GetIdProvider(provider.Type, provider.SubType, clientId, clientSecret, provider.AppId, form.RedirectUri, provider.Domain, provider.CustomAuthUrl, provider.CustomTokenUrl, provider.CustomUserInfoUrl)
if idProvider == nil {
c.ResponseError(fmt.Sprintf("The provider type: %s is not supported", provider.Type))
c.ResponseError(fmt.Sprintf(c.T("ProviderErr.ProviderNotSupported"), provider.Type))
return
}

setHttpClient(idProvider, provider.Type)

if form.State != conf.GetConfigString("authState") && form.State != application.Name {
c.ResponseError(fmt.Sprintf("state expected: \"%s\", but got: \"%s\"", conf.GetConfigString("authState"), form.State))
c.ResponseError(fmt.Sprintf(c.T("AuthErr.AuthStateWrong"), conf.GetConfigString("authState"), form.State))
return
}

Expand All @@ -325,13 +325,13 @@ func (c *ApiController) Login() {
}

if !token.Valid() {
c.ResponseError("Invalid token")
c.ResponseError(c.T("TokenErr.InvalidToken"))
return
}

userInfo, err = idProvider.GetUserInfo(token)
if err != nil {
c.ResponseError(fmt.Sprintf("Failed to login in: %s", err.Error()))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.LoginFail"), err.Error()))
return
}
}
Expand All @@ -348,7 +348,7 @@ func (c *ApiController) Login() {
// Sign in via OAuth (want to sign up but already have account)

if user.IsForbidden {
c.ResponseError("the user is forbidden to sign in, please contact the administrator")
c.ResponseError(c.T("LoginErr.UserIsForbidden"))
}

resp = c.HandleLoggedIn(application, user, &form)
Expand All @@ -360,12 +360,12 @@ func (c *ApiController) Login() {
} else if provider.Category == "OAuth" {
// Sign up via OAuth
if !application.EnableSignUp {
c.ResponseError(fmt.Sprintf("The account for provider: %s and username: %s (%s) does not exist and is not allowed to sign up as new account, please contact your IT support", provider.Type, userInfo.Username, userInfo.DisplayName))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.AppNotEnableSignUp"), provider.Type, userInfo.Username, userInfo.DisplayName))
return
}

if !providerItem.CanSignUp {
c.ResponseError(fmt.Sprintf("The account for provider: %s and username: %s (%s) does not exist and is not allowed to sign up as new account via %s, please use another way to sign up", provider.Type, userInfo.Username, userInfo.DisplayName, provider.Type))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.ProviderCanNotSignUp"), provider.Type, userInfo.Username, userInfo.DisplayName, provider.Type))
return
}

Expand All @@ -386,7 +386,7 @@ func (c *ApiController) Login() {
properties["no"] = strconv.Itoa(len(object.GetUsers(application.Organization)) + 2)
initScore, err := getInitScore()
if err != nil {
c.ResponseError(fmt.Errorf("get init score failed, error: %w", err).Error())
c.ResponseError(fmt.Errorf(c.T("InitErr.InitScoreFailed"), err).Error())
return
}

Expand All @@ -413,7 +413,7 @@ func (c *ApiController) Login() {

affected := object.AddUser(user)
if !affected {
c.ResponseError(fmt.Sprintf("Failed to create user, user information is invalid: %s", util.StructToJson(user)))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.InvalidUserInformation"), util.StructToJson(user)))
return
}

Expand All @@ -438,13 +438,13 @@ func (c *ApiController) Login() {
} else { // form.Method != "signup"
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("The account does not exist", userInfo)
c.ResponseError(c.T("LoginErr.AccountDoNotExist"), userInfo)
return
}

oldUser := object.GetUserByField(application.Organization, provider.Type, userInfo.Id)
if oldUser != nil {
c.ResponseError(fmt.Sprintf("The account for provider: %s and username: %s (%s) is already linked to another account: %s (%s)", provider.Type, userInfo.Username, userInfo.DisplayName, oldUser.Name, oldUser.DisplayName))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.OldUser"), provider.Type, userInfo.Username, userInfo.DisplayName, oldUser.Name, oldUser.DisplayName))
return
}

Expand All @@ -465,7 +465,7 @@ func (c *ApiController) Login() {
// user already signed in to Casdoor, so let the user click the avatar button to do the quick sign-in
application := object.GetApplication(fmt.Sprintf("admin/%s", form.Application))
if application == nil {
c.ResponseError(fmt.Sprintf("The application: %s does not exist", form.Application))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.AppDoNotExist"), form.Application))
return
}

Expand All @@ -477,7 +477,7 @@ func (c *ApiController) Login() {
record.User = user.Name
util.SafeGoroutine(func() { object.AddRecord(record) })
} else {
c.ResponseError(fmt.Sprintf("unknown authentication type (not password or provider), form = %s", util.StructToJson(form)))
c.ResponseError(fmt.Sprintf(c.T("LoginErr.UnknownAuthentication"), util.StructToJson(form)))
return
}
}
Expand All @@ -489,7 +489,7 @@ func (c *ApiController) Login() {
func (c *ApiController) GetSamlLogin() {
providerId := c.Input().Get("id")
relayState := c.Input().Get("relayState")
authURL, method, err := object.GenerateSamlLoginUrl(providerId, relayState)
authURL, method, err := object.GenerateSamlLoginUrl(providerId, relayState, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
}
Expand Down
2 changes: 1 addition & 1 deletion controllers/cas.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ func (c *RootController) SamlValidate() {
}

if !strings.HasPrefix(target, service) {
c.ResponseError(fmt.Sprintf("service %s and %s do not match", target, service))
c.ResponseError(fmt.Sprintf(c.T("CasErr.ServiceDoNotMatch"), target, service))
return
}

Expand Down
10 changes: 5 additions & 5 deletions controllers/enforcer.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
func (c *ApiController) Enforce() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
c.ResponseError(c.T("EnforcerErr.SignInFirst"))
return
}

Expand All @@ -41,7 +41,7 @@ func (c *ApiController) Enforce() {
func (c *ApiController) BatchEnforce() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
c.ResponseError(c.T("EnforcerErr.SignInFirst"))
return
}

Expand All @@ -59,7 +59,7 @@ func (c *ApiController) BatchEnforce() {
func (c *ApiController) GetAllObjects() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
c.ResponseError(c.T("EnforcerErr.SignInFirst"))
return
}

Expand All @@ -70,7 +70,7 @@ func (c *ApiController) GetAllObjects() {
func (c *ApiController) GetAllActions() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
c.ResponseError(c.T("EnforcerErr.SignInFirst"))
return
}

Expand All @@ -81,7 +81,7 @@ func (c *ApiController) GetAllActions() {
func (c *ApiController) GetAllRoles() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
c.ResponseError(c.T("EnforcerErr.SignInFirst"))
return
}

Expand Down
Loading

0 comments on commit d86f3c8

Please sign in to comment.