Skip to content

Commit

Permalink
Move translations constants to central place
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenafamo committed Nov 30, 2023
1 parent 9608094 commit 8f93fb0
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 52 deletions.
7 changes: 3 additions & 4 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import (

const (
// PageLogin is for identifying the login page for parsing & validation
PageLogin = "login"
TranslationInvalidCredentials = "Invalid Credentials"
PageLogin = "login"
)

func init() {
Expand Down Expand Up @@ -64,7 +63,7 @@ func (a *Auth) LoginPost(w http.ResponseWriter, r *http.Request) error {
pidUser, err := a.Authboss.Storage.Server.Load(r.Context(), pid)
if err == authboss.ErrUserNotFound {
logger.Infof("failed to load user requested by pid: %s", pid)
data := authboss.HTMLData{authboss.DataErr: a.Localize(r.Context(), TranslationInvalidCredentials)}
data := authboss.HTMLData{authboss.DataErr: a.Localize(r.Context(), authboss.TxtInvalidCredentials)}
return a.Authboss.Core.Responder.Respond(w, r, http.StatusOK, PageLogin, data)
} else if err != nil {
return err
Expand All @@ -86,7 +85,7 @@ func (a *Auth) LoginPost(w http.ResponseWriter, r *http.Request) error {
}

logger.Infof("user %s failed to log in", pid)
data := authboss.HTMLData{authboss.DataErr: a.Localize(r.Context(), TranslationInvalidCredentials)}
data := authboss.HTMLData{authboss.DataErr: a.Localize(r.Context(), authboss.TxtInvalidCredentials)}
return a.Authboss.Core.Responder.Respond(w, r, http.StatusOK, PageLogin, data)
}

Expand Down
6 changes: 2 additions & 4 deletions authboss.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import (
"golang.org/x/crypto/bcrypt"
)

const TranslateAuthFailed = "please re-login"

// Authboss contains a configuration and other details for running.
type Authboss struct {
Config
Expand Down Expand Up @@ -111,7 +109,7 @@ func (a *Authboss) Localize(ctx context.Context, text string, args ...any) strin
return fmt.Sprintf(text, args...)
}

if translated := a.Config.Core.Localizer.Localize(ctx, text); translated != "" {
if translated := a.Config.Core.Localizer.Localize(ctx, text, args...); translated != "" {
return translated
}

Expand Down Expand Up @@ -233,7 +231,7 @@ func MountedMiddleware2(ab *Authboss, mountPathed bool, reqs MWRequirements, fai

ro := RedirectOptions{
Code: http.StatusTemporaryRedirect,
Failure: ab.Localize(r.Context(), TranslateAuthFailed),
Failure: ab.Localize(r.Context(), TxtAuthFailed),
RedirectPath: path.Join(ab.Config.Paths.Mount, fmt.Sprintf("/login?%s", vals.Encode())),
}

Expand Down
19 changes: 6 additions & 13 deletions confirm/confirm.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,6 @@ const (
// DataConfirmURL is the name of the e-mail template variable
// that gives the url to send to the user for confirmation.
DataConfirmURL = "url"

// Translations
TranslateConfirmYourAccount = "Please verify your account, an e-mail has been sent to you."
TranslateAccountNotConfirmed = "Your account has not been confirmed, please check your e-mail."
TranslateInvalidConfirmToken = "Your confirmation token is invalid."
TranslateConfrimationSuccess = "You have successfully confirmed your account."
TranslateConfirmEmailSubject = "Confirm New Account"
)

func init() {
Expand Down Expand Up @@ -100,7 +93,7 @@ func (c *Confirm) PreventAuth(w http.ResponseWriter, r *http.Request, handled bo
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: c.Authboss.Config.Paths.ConfirmNotOK,
Failure: c.Localize(r.Context(), TranslateAccountNotConfirmed),
Failure: c.Localize(r.Context(), authboss.TxtAccountNotConfirmed),
}
return true, c.Authboss.Config.Core.Redirector.Redirect(w, r, ro)
}
Expand All @@ -121,7 +114,7 @@ func (c *Confirm) StartConfirmationWeb(w http.ResponseWriter, r *http.Request, h
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: c.Authboss.Config.Paths.ConfirmNotOK,
Success: c.Localize(r.Context(), TranslateConfirmYourAccount),
Success: c.Localize(r.Context(), authboss.TxtConfirmYourAccount),
}
return true, c.Authboss.Config.Core.Redirector.Redirect(w, r, ro)
}
Expand Down Expand Up @@ -164,7 +157,7 @@ func (c *Confirm) SendConfirmEmail(ctx context.Context, to, token string) {
To: []string{to},
From: c.Config.Mail.From,
FromName: c.Config.Mail.FromName,
Subject: c.Config.Mail.SubjectPrefix + c.Localize(ctx, TranslateConfirmEmailSubject),
Subject: c.Config.Mail.SubjectPrefix + c.Localize(ctx, authboss.TxtConfirmEmailSubject),
}

logger.Infof("sending confirm e-mail to: %s", to)
Expand Down Expand Up @@ -243,7 +236,7 @@ func (c *Confirm) Get(w http.ResponseWriter, r *http.Request) error {

ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
Success: c.Localize(r.Context(), TranslateConfrimationSuccess),
Success: c.Localize(r.Context(), authboss.TxtConfrimationSuccess),
RedirectPath: c.Authboss.Config.Paths.ConfirmOK,
}
return c.Authboss.Config.Core.Redirector.Redirect(w, r, ro)
Expand All @@ -263,7 +256,7 @@ func (c *Confirm) mailURL(token string) string {
func (c *Confirm) invalidToken(w http.ResponseWriter, r *http.Request) error {
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
Failure: c.Localize(r.Context(), TranslateInvalidConfirmToken),
Failure: c.Localize(r.Context(), authboss.TxtInvalidConfirmToken),
RedirectPath: c.Authboss.Config.Paths.ConfirmNotOK,
}
return c.Authboss.Config.Core.Redirector.Redirect(w, r, ro)
Expand Down Expand Up @@ -291,7 +284,7 @@ func Middleware(ab *authboss.Authboss) func(http.Handler) http.Handler {
logger.Infof("user %s prevented from accessing %s: not confirmed", user.GetPID(), r.URL.Path)
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
Failure: ab.Localize(r.Context(), TranslateAccountNotConfirmed),
Failure: ab.Localize(r.Context(), authboss.TxtAccountNotConfirmed),
RedirectPath: ab.Config.Paths.ConfirmNotOK,
}
if err := ab.Config.Core.Redirector.Redirect(w, r, ro); err != nil {
Expand Down
6 changes: 3 additions & 3 deletions confirm/confirm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func TestGetValidationFailure(t *testing.T) {
if p := harness.redirector.Options.RedirectPath; p != harness.ab.Paths.ConfirmNotOK {
t.Error("redir path was wrong:", p)
}
if reason := harness.redirector.Options.Failure; reason != harness.ab.Localize(context.Background(), TranslateInvalidConfirmToken) {
if reason := harness.redirector.Options.Failure; reason != harness.ab.Localize(context.Background(), authboss.TxtInvalidConfirmToken) {
t.Error("reason for failure was wrong:", reason)
}
}
Expand All @@ -262,7 +262,7 @@ func TestGetBase64DecodeFailure(t *testing.T) {
if p := harness.redirector.Options.RedirectPath; p != harness.ab.Paths.ConfirmNotOK {
t.Error("redir path was wrong:", p)
}
if reason := harness.redirector.Options.Failure; reason != harness.ab.Localize(context.Background(), TranslateInvalidConfirmToken) {
if reason := harness.redirector.Options.Failure; reason != harness.ab.Localize(context.Background(), authboss.TxtInvalidConfirmToken) {
t.Error("reason for failure was wrong:", reason)
}
}
Expand Down Expand Up @@ -294,7 +294,7 @@ func TestGetUserNotFoundFailure(t *testing.T) {
if p := harness.redirector.Options.RedirectPath; p != harness.ab.Paths.ConfirmNotOK {
t.Error("redir path was wrong:", p)
}
if reason := harness.redirector.Options.Failure; reason != harness.ab.Localize(context.Background(), TranslateInvalidConfirmToken) {
if reason := harness.redirector.Options.Failure; reason != harness.ab.Localize(context.Background(), authboss.TxtInvalidConfirmToken) {
t.Error("reason for failure was wrong:", reason)
}
}
Expand Down
34 changes: 34 additions & 0 deletions localizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,37 @@ type Localizer interface {
// If no translation is found, an empty string should be returned.
Localize(ctx context.Context, txt string, args ...any) string
}

// Translation constants
const (
// Used in the auth module
TxtInvalidCredentials = "Invalid Credentials"
TxtAuthFailed = "Please login"

// Used in the register module
TxtUserAlreadyExists = "User already exists"
TxtRegisteredAndLoggedIn = "Account successfully created, you are now logged in"

// Used in the confirm module
TxtConfirmYourAccount = "Please verify your account, an e-mail has been sent to you."
TxtAccountNotConfirmed = "Your account has not been confirmed, please check your e-mail."
TxtInvalidConfirmToken = "Your confirmation token is invalid."
TxtConfrimationSuccess = "You have successfully confirmed your account."
TxtConfirmEmailSubject = "Confirm New Account"

// Used in the lock module
TxtLocked = "Your account has been locked, please contact the administrator."

// Used in the logout module
TxtLoggedOut = "You have been logged out"

// Used in the oauth2 module
TxtOAuth2LoginOK = "Logged in successfully with %s."
TxtOAuth2LoginNotOK = "%s login cancelled or failed"

// Used in the recover module
TxtRecoverInitiateSuccessFlash = "An email has been sent to you with further instructions on how to reset your password."
TxtPasswordResetEmailSubject = "Password Reset"
TxtRecoverSuccessMsg = "Successfully updated password"
TxtRecoverAndLoginSuccessMsg = "Successfully updated password and logged in"
)
5 changes: 2 additions & 3 deletions lock/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const (
StoreAttemptNumber = "attempt_number"
StoreAttemptTime = "attempt_time"
StoreLocked = "locked"
TranslationLocked = "Your account has been locked, please contact the administrator."
)

func init() {
Expand Down Expand Up @@ -100,7 +99,7 @@ func (l *Lock) updateLockedState(w http.ResponseWriter, r *http.Request, wasCorr

ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
Failure: l.Localize(r.Context(), TranslationLocked),
Failure: l.Localize(r.Context(), authboss.TxtLocked),
RedirectPath: l.Authboss.Config.Paths.LockNotOK,
}
return true, l.Authboss.Config.Core.Redirector.Redirect(w, r, ro)
Expand Down Expand Up @@ -159,7 +158,7 @@ func Middleware(ab *authboss.Authboss) func(http.Handler) http.Handler {
logger.Infof("user %s prevented from accessing %s: locked", user.GetPID(), r.URL.Path)
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
Failure: ab.Localize(r.Context(), TranslationLocked),
Failure: ab.Localize(r.Context(), authboss.TxtLocked),
RedirectPath: ab.Config.Paths.LockNotOK,
}
if err := ab.Config.Core.Redirector.Redirect(w, r, ro); err != nil {
Expand Down
4 changes: 1 addition & 3 deletions logout/logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import (
"github.com/volatiletech/authboss/v3"
)

const TranslateLoggedOut = "You have been logged out"

func init() {
authboss.RegisterModule("logout", &Logout{})
}
Expand Down Expand Up @@ -73,7 +71,7 @@ func (l *Logout) Logout(w http.ResponseWriter, r *http.Request) error {
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: l.Authboss.Paths.LogoutOK,
Success: TranslateLoggedOut,
Success: authboss.TxtLoggedOut,
}
return l.Authboss.Core.Redirector.Redirect(w, r, ro)
}
8 changes: 2 additions & 6 deletions oauth2/oauth2.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,6 @@ import (
const (
FormValueOAuth2State = "state"
FormValueOAuth2Redir = "redir"

// Translations
TranslationOAuth2LoginOK = "Logged in successfully with %s."
TranslationOAuth2LoginNotOK = "%s login cancelled or failed"
)

var errOAuthStateValidation = errors.New("could not validate oauth2 state param")
Expand Down Expand Up @@ -216,7 +212,7 @@ func (o *OAuth2) End(w http.ResponseWriter, r *http.Request) error {
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: o.Authboss.Config.Paths.OAuth2LoginNotOK,
Failure: o.Localize(r.Context(), TranslationOAuth2LoginNotOK, provider),
Failure: o.Localize(r.Context(), authboss.TxtOAuth2LoginNotOK, provider),
}
return o.Authboss.Core.Redirector.Redirect(w, r, ro)
}
Expand Down Expand Up @@ -294,7 +290,7 @@ func (o *OAuth2) End(w http.ResponseWriter, r *http.Request) error {
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: redirect,
Success: o.Localize(r.Context(), TranslationOAuth2LoginOK, provider),
Success: o.Localize(r.Context(), authboss.TxtOAuth2LoginOK, provider),
}
return o.Authboss.Config.Core.Redirector.Redirect(w, r, ro)
}
Expand Down
15 changes: 5 additions & 10 deletions recover/recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ const (
PageRecoverStart = "recover_start"
PageRecoverMiddle = "recover_middle"
PageRecoverEnd = "recover_end"

TranslateRecoverInitiateSuccessFlash = "An email has been sent to you with further instructions on how to reset your password."
TranslatePasswordResetEmailSubject = "Password Reset"
TranslateRecoverSuccessMsg = "Successfully updated password"
TranslateRecoverAndLoginSuccessMsg = "Successfully updated password and logged in"
)

func init() {
Expand Down Expand Up @@ -97,7 +92,7 @@ func (r *Recover) StartPost(w http.ResponseWriter, req *http.Request) error {
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: r.Authboss.Config.Paths.RecoverOK,
Success: TranslateRecoverInitiateSuccessFlash,
Success: authboss.TxtRecoverInitiateSuccessFlash,
}
return r.Authboss.Core.Redirector.Redirect(w, req, ro)
}
Expand Down Expand Up @@ -148,7 +143,7 @@ func (r *Recover) StartPost(w http.ResponseWriter, req *http.Request) error {
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
RedirectPath: r.Authboss.Config.Paths.RecoverOK,
Success: TranslateRecoverInitiateSuccessFlash,
Success: authboss.TxtRecoverInitiateSuccessFlash,
}
return r.Authboss.Core.Redirector.Redirect(w, req, ro)
}
Expand All @@ -164,7 +159,7 @@ func (r *Recover) SendRecoverEmail(ctx context.Context, to []string, encodedToke
To: to,
From: r.Authboss.Config.Mail.From,
FromName: r.Authboss.Config.Mail.FromName,
Subject: r.Authboss.Config.Mail.SubjectPrefix + r.Localize(ctx, TranslatePasswordResetEmailSubject),
Subject: r.Authboss.Config.Mail.SubjectPrefix + r.Localize(ctx, authboss.TxtPasswordResetEmailSubject),
}

ro := authboss.EmailResponseOptions{
Expand Down Expand Up @@ -290,7 +285,7 @@ func (r *Recover) EndPost(w http.ResponseWriter, req *http.Request) error {
return err
}

successMsg := r.Localize(req.Context(), TranslateRecoverSuccessMsg)
successMsg := r.Localize(req.Context(), authboss.TxtRecoverSuccessMsg)
if r.Authboss.Config.Modules.RecoverLoginAfterRecovery {
handled, err = r.Events.FireBefore(authboss.EventAuth, w, req)
if err != nil {
Expand All @@ -307,7 +302,7 @@ func (r *Recover) EndPost(w http.ResponseWriter, req *http.Request) error {
}

authboss.PutSession(w, authboss.SessionKey, user.GetPID())
successMsg = r.Localize(req.Context(), TranslateRecoverAndLoginSuccessMsg)
successMsg = r.Localize(req.Context(), authboss.TxtRecoverAndLoginSuccessMsg)

handled, err = r.Authboss.Events.FireAfter(authboss.EventAuth, w, req)
if err != nil {
Expand Down
7 changes: 2 additions & 5 deletions register/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@ import (
// Pages
const (
PageRegister = "register"
// Translations
TranslateUserAlreadyExists = "User already exists"
TranslateRegisteredAndLoggedIn = "Account successfully created, you are now logged in"
)

func init() {
Expand Down Expand Up @@ -110,7 +107,7 @@ func (r *Register) Post(w http.ResponseWriter, req *http.Request) error {
switch {
case err == authboss.ErrUserFound:
logger.Infof("user %s attempted to re-register", pid)
errs = []error{errors.New(TranslateUserAlreadyExists)}
errs = []error{errors.New(authboss.TxtUserAlreadyExists)}
data := authboss.HTMLData{
authboss.DataValidation: authboss.ErrorMap(errs),
}
Expand All @@ -137,7 +134,7 @@ func (r *Register) Post(w http.ResponseWriter, req *http.Request) error {
logger.Infof("registered and logged in user %s", pid)
ro := authboss.RedirectOptions{
Code: http.StatusTemporaryRedirect,
Success: TranslateRegisteredAndLoggedIn,
Success: authboss.TxtRegisteredAndLoggedIn,
RedirectPath: r.Config.Paths.RegisterOK,
}
return r.Config.Core.Redirector.Redirect(w, req, ro)
Expand Down
2 changes: 1 addition & 1 deletion register/register_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ func TestRegisterPostUserExists(t *testing.T) {
}

errList := h.responder.Data[authboss.DataValidation].(map[string][]string)
if e := errList[""][0]; e != h.ab.Localize(context.Background(), TranslateUserAlreadyExists) {
if e := errList[""][0]; e != h.ab.Localize(context.Background(), authboss.TxtUserAlreadyExists) {
t.Error("validation error wrong:", e)
}

Expand Down

0 comments on commit 8f93fb0

Please sign in to comment.