feat: support i18n in backend err messages (#1232)

* 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
This commit is contained in:
Mr Forest
2022-10-23 15:16:24 +08:00
committed by GitHub
parent 7c77519069
commit d86f3c88c7
64 changed files with 1838 additions and 194 deletions

View File

@ -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
}
@ -111,21 +111,21 @@ 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
}
}
@ -133,9 +133,9 @@ func (c *ApiController) Signup() {
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
}
}
@ -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
}
@ -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
}
@ -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

View File

@ -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
}
@ -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
}

View File

@ -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
}
@ -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() {
@ -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)
@ -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
}
}
@ -218,11 +218,11 @@ 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
}
@ -230,7 +230,7 @@ func (c *ApiController) Login() {
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)
@ -247,12 +247,12 @@ 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 != "" {
@ -260,7 +260,7 @@ func (c *ApiController) Login() {
} 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
}
@ -274,7 +274,7 @@ 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
}
@ -282,7 +282,7 @@ func (c *ApiController) Login() {
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
}
@ -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
}
@ -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
}
}
@ -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)
@ -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
}
@ -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
}
@ -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
}
@ -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
}
@ -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
}
@ -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
}
}
@ -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())
}

View File

@ -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
}

View File

@ -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
}
@ -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
}
@ -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
}
@ -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
}
@ -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
}

View File

@ -52,7 +52,7 @@ func (c *ApiController) GetLdapUser() {
ldapServer := LdapServer{}
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ldapServer)
if err != nil || util.IsStrsEmpty(ldapServer.Host, ldapServer.Admin, ldapServer.Passwd, ldapServer.BaseDn) {
c.ResponseError("Missing parameter")
c.ResponseError(c.T("ParameterErr.Missing"))
return
}
@ -120,7 +120,7 @@ func (c *ApiController) GetLdap() {
id := c.Input().Get("id")
if util.IsStrsEmpty(id) {
c.ResponseError("Missing parameter")
c.ResponseError(c.T("ParameterErr.Missing"))
return
}
@ -136,17 +136,17 @@ func (c *ApiController) AddLdap() {
var ldap object.Ldap
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ldap)
if err != nil {
c.ResponseError("Missing parameter")
c.ResponseError(c.T("ParameterErr.Missing"))
return
}
if util.IsStrsEmpty(ldap.Owner, ldap.ServerName, ldap.Host, ldap.Admin, ldap.Passwd, ldap.BaseDn) {
c.ResponseError("Missing parameter")
c.ResponseError(c.T("ParameterErr.Missing"))
return
}
if object.CheckLdapExist(&ldap) {
c.ResponseError("Ldap server exist")
c.ResponseError(c.T("LdapErr.ServerExisted"))
return
}
@ -171,7 +171,7 @@ func (c *ApiController) UpdateLdap() {
var ldap object.Ldap
err := json.Unmarshal(c.Ctx.Input.RequestBody, &ldap)
if err != nil || util.IsStrsEmpty(ldap.Owner, ldap.ServerName, ldap.Host, ldap.Admin, ldap.Passwd, ldap.BaseDn) {
c.ResponseError("Missing parameter")
c.ResponseError(c.T("ParameterErr.Missing"))
return
}

View File

@ -49,7 +49,7 @@ func handleBind(w ldapserver.ResponseWriter, m *ldapserver.Message) {
return
}
bindpassword := string(r.AuthenticationSimple())
binduser, err := object.CheckUserPassword(bindorg, bindusername, bindpassword)
binduser, err := object.CheckUserPassword(bindorg, bindusername, bindpassword, "en")
if err != "" {
log.Printf("Bind failed User=%s, Pass=%#v, ErrMsg=%s", string(r.Name()), r.Authentication(), err)
res.SetResultCode(ldapserver.LDAPResultInvalidCredentials)

View File

@ -47,7 +47,7 @@ func (c *ApiController) Unlink() {
if user.Id != unlinkedUser.Id && !user.IsGlobalAdmin {
// if the user is not the same as the one we are unlinking, we need to make sure the user is the global admin.
c.ResponseError("You are not the global admin, you can't unlink other users")
c.ResponseError(c.T("AuthErr.CanNotUnlinkUsers"))
return
}
@ -55,23 +55,23 @@ func (c *ApiController) Unlink() {
// if the user is unlinking themselves, should check the provider can be unlinked, if not, we should return an error.
application := object.GetApplicationByUser(user)
if application == nil {
c.ResponseError("You can't unlink yourself, you are not a member of any application")
c.ResponseError(c.T("AuthErr.CanNotLinkMySelf"))
return
}
if len(application.Providers) == 0 {
c.ResponseError("This application has no providers")
c.ResponseError(c.T("ApplicationErr.HasNoProviders"))
return
}
provider := application.GetProviderItemByType(providerType)
if provider == nil {
c.ResponseError("This application has no providers of type " + providerType)
c.ResponseError(c.T("ApplicationErr.HasNoProvidersOfType") + providerType)
return
}
if !provider.CanUnlink {
c.ResponseError("This provider can't be unlinked")
c.ResponseError(c.T("ProviderErr.CanNotBeUnlinked"))
return
}
@ -84,7 +84,7 @@ func (c *ApiController) Unlink() {
value := object.GetUserField(&unlinkedUser, providerType)
if value == "" {
c.ResponseError("Please link first", value)
c.ResponseError(c.T("ProviderErr.LinkFirstErr"), value)
return
}

View File

@ -141,13 +141,13 @@ func (c *ApiController) BuyProduct() {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please login first")
c.ResponseError(c.T("LoginErr.LoginFirst"))
return
}
user := object.GetUser(userId)
if user == nil {
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", userId))
c.ResponseError(fmt.Sprintf(c.T("UserErr.DoNotExist"), userId))
return
}

View File

@ -113,7 +113,7 @@ func (c *ApiController) DeleteResource() {
return
}
err = object.DeleteFile(provider, resource.Name)
err = object.DeleteFile(provider, resource.Name, c.GetAcceptLanguage())
if err != nil {
c.ResponseError(err.Error())
return
@ -145,7 +145,7 @@ func (c *ApiController) UploadResource() {
defer file.Close()
if username == "" || fullFilePath == "" {
c.ResponseError(fmt.Sprintf("username or fullFilePath is empty: username = %s, fullFilePath = %s", username, fullFilePath))
c.ResponseError(fmt.Sprintf(c.T("ResourceErr.UsernameOrFilePathEmpty"), username, fullFilePath))
return
}
@ -205,7 +205,7 @@ func (c *ApiController) UploadResource() {
if user == nil {
user = object.GetUserNoCheck(username)
if user == nil {
c.ResponseError("user is nil for tag: \"avatar\"")
c.ResponseError(c.T("ResourceErr.UserIsNil"))
return
}
}

View File

@ -25,7 +25,7 @@ func (c *ApiController) GetSamlMeta() {
paramApp := c.Input().Get("application")
application := object.GetApplication(paramApp)
if application == nil {
c.ResponseError(fmt.Sprintf("err: application %s not found", paramApp))
c.ResponseError(fmt.Sprintf(c.T("ApplicationErr.AppNotFound"), paramApp))
return
}
metadata, _ := object.GetSamlMeta(application, host)

View File

@ -81,7 +81,7 @@ func (c *ApiController) SendEmail() {
}
if util.IsStrsEmpty(emailForm.Title, emailForm.Content, emailForm.Sender) {
c.ResponseError(fmt.Sprintf("Empty parameters for emailForm: %v", emailForm))
c.ResponseError(fmt.Sprintf(c.T("EmailErr.EmptyParam"), emailForm))
return
}
@ -93,7 +93,7 @@ func (c *ApiController) SendEmail() {
}
if len(invalidReceivers) != 0 {
c.ResponseError(fmt.Sprintf("Invalid Email receivers: %s", invalidReceivers))
c.ResponseError(fmt.Sprintf(c.T("EmailErr.InvalidReceivers"), invalidReceivers))
return
}
@ -141,7 +141,7 @@ func (c *ApiController) SendSms() {
}
if len(invalidReceivers) != 0 {
c.ResponseError(fmt.Sprintf("Invalid phone receivers: %s", invalidReceivers))
c.ResponseError(fmt.Sprintf(c.T("PhoneErr.InvalidReceivers"), invalidReceivers))
return
}

View File

@ -40,7 +40,7 @@ func (c *ApiController) GetSystemInfo() {
user := object.GetUser(id)
if user == nil || !user.IsGlobalAdmin {
c.ResponseError("You are not authorized to access this resource")
c.ResponseError(c.T("ResourceErr.NotAuthorized"))
return
}

View File

@ -150,12 +150,12 @@ func (c *ApiController) GetOAuthCode() {
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
}
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge, host)
c.Data["json"] = object.GetOAuthCode(userId, clientId, responseType, redirectUri, scope, state, nonce, codeChallenge, host, c.GetAcceptLanguage())
c.ServeJSON()
}
@ -204,7 +204,7 @@ func (c *ApiController) GetOAuthToken() {
}
host := c.Ctx.Request.Host
c.Data["json"] = object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier, scope, username, password, host, tag, avatar)
c.Data["json"] = object.GetOAuthToken(grantType, clientId, clientSecret, code, verifier, scope, username, password, host, tag, avatar, c.GetAcceptLanguage())
c.SetTokenErrorHttpStatus()
c.ServeJSON()
}
@ -290,7 +290,7 @@ func (c *ApiController) IntrospectToken() {
clientId = c.Input().Get("client_id")
clientSecret = c.Input().Get("client_secret")
if clientId == "" || clientSecret == "" {
c.ResponseError("empty clientId or clientSecret")
c.ResponseError(c.T("TokenErr.EmptyClientID"))
c.Data["json"] = &object.TokenError{
Error: object.InvalidRequest,
}
@ -301,7 +301,7 @@ func (c *ApiController) IntrospectToken() {
}
application := object.GetApplicationByClientId(clientId)
if application == nil || application.ClientSecret != clientSecret {
c.ResponseError("invalid application or wrong clientSecret")
c.ResponseError(c.T("TokenErr.InvalidAppOrWrongClientSecret"))
c.Data["json"] = &object.TokenError{
Error: object.InvalidClient,
}

View File

@ -100,7 +100,7 @@ func (c *ApiController) GetUser() {
organization := object.GetOrganization(fmt.Sprintf("%s/%s", "admin", owner))
if !organization.IsProfilePublic {
requestUserId := c.GetSessionUsername()
hasPermission, err := object.CheckUserPermission(requestUserId, id, owner, false)
hasPermission, err := object.CheckUserPermission(requestUserId, id, owner, false, c.GetAcceptLanguage())
if !hasPermission {
c.ResponseError(err.Error())
return
@ -149,7 +149,7 @@ func (c *ApiController) UpdateUser() {
}
if user.DisplayName == "" {
c.ResponseError("Display name cannot be empty")
c.ResponseError(c.T("UserErr.DisplayNameCanNotBeEmpty"))
return
}
@ -183,7 +183,7 @@ func (c *ApiController) AddUser() {
return
}
msg := object.CheckUsername(user.Name)
msg := object.CheckUsername(user.Name, c.GetAcceptLanguage())
if msg != "" {
c.ResponseError(msg)
return
@ -230,7 +230,7 @@ func (c *ApiController) GetEmailAndPhone() {
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("UserErr.DoNotExistInOrg"), form.Organization, form.Username))
return
}
@ -271,7 +271,7 @@ func (c *ApiController) SetPassword() {
requestUserId := c.GetSessionUsername()
userId := fmt.Sprintf("%s/%s", userOwner, userName)
hasPermission, err := object.CheckUserPermission(requestUserId, userId, userOwner, true)
hasPermission, err := object.CheckUserPermission(requestUserId, userId, userOwner, true, c.GetAcceptLanguage())
if !hasPermission {
c.ResponseError(err.Error())
return
@ -280,7 +280,7 @@ func (c *ApiController) SetPassword() {
targetUser := object.GetUser(userId)
if oldPassword != "" {
msg := object.CheckPassword(targetUser, oldPassword)
msg := object.CheckPassword(targetUser, oldPassword, c.GetAcceptLanguage())
if msg != "" {
c.ResponseError(msg)
return
@ -288,12 +288,12 @@ func (c *ApiController) SetPassword() {
}
if strings.Contains(newPassword, " ") {
c.ResponseError("New password cannot contain blank space.")
c.ResponseError(c.T("SetPasswordErr.CanNotContainBlank"))
return
}
if len(newPassword) <= 5 {
c.ResponseError("New password must have at least 6 characters")
c.ResponseError(c.T("SetPasswordErr.LessThanSixCharacters"))
return
}
@ -315,7 +315,7 @@ func (c *ApiController) CheckUserPassword() {
return
}
_, msg := object.CheckUserPassword(user.Owner, user.Name, user.Password)
_, msg := object.CheckUserPassword(user.Owner, user.Name, user.Password, c.GetAcceptLanguage())
if msg == "" {
c.ResponseOk()
} else {

View File

@ -61,6 +61,6 @@ func (c *ApiController) UploadUsers() {
if affected {
c.ResponseOk()
} else {
c.ResponseError("Failed to import users")
c.ResponseError(c.T("UserErr.FailToImportUsers"))
}
}

View File

@ -19,6 +19,7 @@ import (
"strconv"
"github.com/casdoor/casdoor/conf"
"github.com/casdoor/casdoor/i18n"
"github.com/casdoor/casdoor/object"
"github.com/casdoor/casdoor/util"
)
@ -48,6 +49,16 @@ func (c *ApiController) ResponseError(error string, data ...interface{}) {
c.ResponseJsonData(resp, data...)
}
func (c *ApiController) T(error string) string {
return i18n.Translate(c.GetAcceptLanguage(), error)
}
// GetAcceptLanguage ...
func (c *ApiController) GetAcceptLanguage() string {
lang := c.Ctx.Request.Header.Get("Accept-Language")
return lang[0:2]
}
// SetTokenErrorHttpStatus ...
func (c *ApiController) SetTokenErrorHttpStatus() {
_, ok := c.Data["json"].(*object.TokenError)
@ -69,7 +80,7 @@ func (c *ApiController) SetTokenErrorHttpStatus() {
func (c *ApiController) RequireSignedIn() (string, bool) {
userId := c.GetSessionUsername()
if userId == "" {
c.ResponseError("Please sign in first")
c.ResponseError(c.T("LoginErr.SignInFirst"))
return "", false
}
return userId, true
@ -84,7 +95,7 @@ func (c *ApiController) RequireSignedInUser() (*object.User, bool) {
user := object.GetUser(userId)
if user == nil {
c.ResponseError(fmt.Sprintf("The user: %s doesn't exist", userId))
c.ResponseError(fmt.Sprintf(c.T("UserErr.DoNotExist"), userId))
return nil, false
}
return user, true
@ -112,7 +123,7 @@ func (c *ApiController) GetProviderFromContext(category string) (*object.Provide
if providerName != "" {
provider := object.GetProvider(util.GetId(providerName))
if provider == nil {
c.ResponseError(fmt.Sprintf("The provider: %s is not found", providerName))
c.ResponseError(c.T("ProviderErr.ProviderNotFound"), providerName)
return nil, nil, false
}
return provider, nil, true
@ -125,13 +136,13 @@ func (c *ApiController) GetProviderFromContext(category string) (*object.Provide
application, user := object.GetApplicationByUserId(userId)
if application == nil {
c.ResponseError(fmt.Sprintf("No application is found for userId: \"%s\"", userId))
c.ResponseError(fmt.Sprintf(c.T("ApplicationErr.AppNotFoundForUserID"), userId))
return nil, nil, false
}
provider := application.GetProviderByCategory(category)
if provider == nil {
c.ResponseError(fmt.Sprintf("No provider for category: \"%s\" is found for application: %s", category, application.Name))
c.ResponseError(fmt.Sprintf(c.T("ProviderErr.ProviderNotFoundForCategory"), category, application.Name))
return nil, nil, false
}

View File

@ -50,23 +50,23 @@ func (c *ApiController) SendVerificationCode() {
remoteAddr := util.GetIPFromRequest(c.Ctx.Request)
if destType == "" {
c.ResponseError("Missing parameter: type.")
c.ResponseError(c.T("ParameterErr.Missing") + ": type.")
return
}
if dest == "" {
c.ResponseError("Missing parameter: dest.")
c.ResponseError(c.T("ParameterErr.Missing") + ": dest.")
return
}
if applicationId == "" {
c.ResponseError("Missing parameter: applicationId.")
c.ResponseError(c.T("ParameterErr.Missing") + ": applicationId.")
return
}
if !strings.Contains(applicationId, "/") {
c.ResponseError("Wrong parameter: applicationId.")
c.ResponseError(c.T("ParameterErr.Wrong") + ": applicationId.")
return
}
if checkType == "" {
c.ResponseError("Missing parameter: checkType.")
c.ResponseError(c.T("ParameterErr.Missing") + ": checkType.")
return
}
@ -74,7 +74,7 @@ func (c *ApiController) SendVerificationCode() {
if captchaProvider != nil {
if checkKey == "" {
c.ResponseError("Missing parameter: checkKey.")
c.ResponseError(c.T("ParameterErr.Missing") + ": checkKey.")
return
}
isHuman, err := captchaProvider.VerifyCaptcha(checkKey, checkId)
@ -84,7 +84,7 @@ func (c *ApiController) SendVerificationCode() {
}
if !isHuman {
c.ResponseError("Turing test failed.")
c.ResponseError(c.T("AuthErr.NotHuman"))
return
}
}
@ -94,7 +94,7 @@ func (c *ApiController) SendVerificationCode() {
organization := object.GetOrganization(fmt.Sprintf("%s/%s", application.Owner, application.Organization))
if checkUser == "true" && user == nil && object.GetUserByFields(organization.Name, dest) == nil {
c.ResponseError("Please login first")
c.ResponseError(c.T("LoginErr.LoginFirst"))
return
}
@ -110,7 +110,7 @@ func (c *ApiController) SendVerificationCode() {
dest = user.Email
}
if !util.IsEmailValid(dest) {
c.ResponseError("Invalid Email address")
c.ResponseError(c.T("EmailErr.EmailInvalid"))
return
}
@ -121,11 +121,11 @@ func (c *ApiController) SendVerificationCode() {
dest = user.Phone
}
if !util.IsPhoneCnValid(dest) {
c.ResponseError("Invalid phone number")
c.ResponseError(c.T("PhoneErr.NumberInvalid"))
return
}
if organization == nil {
c.ResponseError("The organization doesn't exist.")
c.ResponseError(c.T("OrgErr.DoNotExist"))
return
}
@ -157,7 +157,7 @@ func (c *ApiController) ResetEmailOrPhone() {
dest := c.Ctx.Request.Form.Get("dest")
code := c.Ctx.Request.Form.Get("code")
if len(dest) == 0 || len(code) == 0 || len(destType) == 0 {
c.ResponseError("Missing parameter.")
c.ResponseError(c.T("ParameterErr.Missing"))
return
}
@ -166,11 +166,11 @@ func (c *ApiController) ResetEmailOrPhone() {
if destType == "phone" {
phoneItem := object.GetAccountItemByName("Phone", org)
if phoneItem == nil {
c.ResponseError("Unable to get the phone modify rule.")
c.ResponseError(c.T("PhoneErr.UnableGetModifyRule"))
return
}
if pass, errMsg := object.CheckAccountItemModifyRule(phoneItem, user); !pass {
if pass, errMsg := object.CheckAccountItemModifyRule(phoneItem, user, c.GetAcceptLanguage()); !pass {
c.ResponseError(errMsg)
return
}
@ -183,16 +183,16 @@ func (c *ApiController) ResetEmailOrPhone() {
} else if destType == "email" {
emailItem := object.GetAccountItemByName("Email", org)
if emailItem == nil {
c.ResponseError("Unable to get the email modify rule.")
c.ResponseError(c.T("EmailErr.UnableGetModifyRule"))
return
}
if pass, errMsg := object.CheckAccountItemModifyRule(emailItem, user); !pass {
if pass, errMsg := object.CheckAccountItemModifyRule(emailItem, user, c.GetAcceptLanguage()); !pass {
c.ResponseError(errMsg)
return
}
}
if ret := object.CheckVerificationCode(checkDest, code); len(ret) != 0 {
if ret := object.CheckVerificationCode(checkDest, code, c.GetAcceptLanguage()); len(ret) != 0 {
c.ResponseError(ret)
return
}
@ -205,7 +205,7 @@ func (c *ApiController) ResetEmailOrPhone() {
user.Phone = dest
object.SetUserField(user, "phone", user.Phone)
default:
c.ResponseError("Unknown type.")
c.ResponseError(c.T("ParameterErr.UnknownType"))
return
}
@ -224,17 +224,17 @@ func (c *ApiController) VerifyCaptcha() {
captchaToken := c.Ctx.Request.Form.Get("captchaToken")
clientSecret := c.Ctx.Request.Form.Get("clientSecret")
if captchaToken == "" {
c.ResponseError("Missing parameter: captchaToken.")
c.ResponseError(c.T("ParameterErr.Missing") + ": captchaToken.")
return
}
if clientSecret == "" {
c.ResponseError("Missing parameter: clientSecret.")
c.ResponseError(c.T("ParameterErr.Missing") + ": clientSecret.")
return
}
provider := captcha.GetCaptchaProvider(captchaType)
if provider == nil {
c.ResponseError("Invalid captcha provider.")
c.ResponseError(c.T("ProviderErr.InvalidProvider"))
return
}

View File

@ -35,7 +35,7 @@ func (c *ApiController) WebAuthnSignupBegin() {
webauthnObj := object.GetWebAuthnObject(c.Ctx.Request.Host)
user := c.getCurrentUser()
if user == nil {
c.ResponseError("Please login first.")
c.ResponseError(c.T("LoginErr.LoginFirst"))
return
}
@ -66,13 +66,13 @@ func (c *ApiController) WebAuthnSignupFinish() {
webauthnObj := object.GetWebAuthnObject(c.Ctx.Request.Host)
user := c.getCurrentUser()
if user == nil {
c.ResponseError("Please login first.")
c.ResponseError(c.T("LoginErr.LoginFirst"))
return
}
sessionObj := c.GetSession("registration")
sessionData, ok := sessionObj.(webauthn.SessionData)
if !ok {
c.ResponseError("Please call WebAuthnSignupBegin first")
c.ResponseError(c.T("AuthErr.CallWebAuthnSigninBegin"))
return
}
c.Ctx.Request.Body = io.NopCloser(bytes.NewBuffer(c.Ctx.Input.RequestBody))
@ -101,7 +101,7 @@ func (c *ApiController) WebAuthnSigninBegin() {
userName := c.Input().Get("name")
user := object.GetUserByFields(userOwner, userName)
if user == nil {
c.ResponseError(fmt.Sprintf("The user: %s/%s doesn't exist", userOwner, userName))
c.ResponseError(fmt.Sprintf(c.T("UserErr.DoNotExistInOrg"), userOwner, userName))
return
}
options, sessionData, err := webauthnObj.BeginLogin(user)
@ -127,7 +127,7 @@ func (c *ApiController) WebAuthnSigninFinish() {
sessionObj := c.GetSession("authentication")
sessionData, ok := sessionObj.(webauthn.SessionData)
if !ok {
c.ResponseError("Please call WebAuthnSigninBegin first")
c.ResponseError(c.T("AuthErr.CallWebAuthnSigninBegin"))
return
}
c.Ctx.Request.Body = io.NopCloser(bytes.NewBuffer(c.Ctx.Input.RequestBody))