Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

enhancement: add 401 response

goenning6cf0f1c6450a
diff --git a/app/middlewares/auth.go b/app/middlewares/auth.go
index 41d62c517..f72909dad 100644
--- a/app/middlewares/auth.go
+++ b/app/middlewares/auth.go
@@ -27,7 +27,7 @@ func IsAuthorized(roles ...enum.Role) web.MiddlewareFunc {
return next(c)
}
}
- return c.Unauthorized()
+ return c.Forbidden()
}
}
}
diff --git a/app/middlewares/auth_test.go b/app/middlewares/auth_test.go
index 86f24b404..698f2225b 100644
--- a/app/middlewares/auth_test.go
+++ b/app/middlewares/auth_test.go
@@ -57,5 +57,5 @@ func TestIsAuthenticated_WithoutUser(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- Expect(status).Equals(http.StatusForbidden)
+ Expect(status).Equals(http.StatusUnauthorized)
}
diff --git a/app/middlewares/user.go b/app/middlewares/user.go
index a8a93f4a7..c29cbea59 100644
--- a/app/middlewares/user.go
+++ b/app/middlewares/user.go
@@ -96,13 +96,6 @@ func User() web.MiddlewareFunc {
}
if user != nil && c.Tenant() != nil && user.Tenant.ID == c.Tenant().ID {
-
- // only administrators should be allowed to sign in to a locked tenant
- if c.Tenant().Status == enum.TenantLocked && !user.IsAdministrator() {
- c.RemoveCookie(web.CookieAuthName)
- return c.Unauthorized()
- }
-
// blocked users are unable to sign in
if user.Status == enum.UserBlocked {
c.RemoveCookie(web.CookieAuthName)
diff --git a/app/middlewares/user_test.go b/app/middlewares/user_test.go
index c2847952f..b570c1ce5 100644
--- a/app/middlewares/user_test.go
+++ b/app/middlewares/user_test.go
@@ -94,41 +94,10 @@ func TestUser_Blocked(t *testing.T) {
return c.String(http.StatusOK, c.User().Name)
})
- Expect(status).Equals(http.StatusForbidden)
+ Expect(status).Equals(http.StatusUnauthorized)
}
-func TestUser_LockedTenant_Administrator(t *testing.T) {
- RegisterT(t)
-
- server := mock.NewServer()
- mock.DemoTenant.Status = enum.TenantLocked
- token, _ := jwt.Encode(jwt.FiderClaims{
- UserID: mock.JonSnow.ID,
- UserName: mock.JonSnow.Name,
- })
-
- bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
- if q.UserID == mock.JonSnow.ID {
- q.Result = mock.JonSnow
- return nil
- }
- return app.ErrNotFound
- })
-
- server.Use(middlewares.User())
- status, response := server.
- OnTenant(mock.DemoTenant).
- AddHeader("Accept", "application/json").
- AddCookie(web.CookieAuthName, token).
- Execute(func(c *web.Context) error {
- return c.String(http.StatusOK, c.User().Name)
- })
-
- Expect(status).Equals(http.StatusOK)
- Expect(response.Body.String()).Equals("Jon Snow")
-}
-
-func TestUser_LockedTenant_Visitor(t *testing.T) {
+func TestUser_LockedTenant_ShouldAllowSignIn(t *testing.T) {
RegisterT(t)
server := mock.NewServer()
@@ -139,15 +108,13 @@ func TestUser_LockedTenant_Visitor(t *testing.T) {
})
bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {
- if q.UserID == mock.AryaStark.ID {
- q.Result = mock.AryaStark
- return nil
- }
- return app.ErrNotFound
+ Expect(q.UserID).Equals(mock.AryaStark.ID)
+ q.Result = mock.AryaStark
+ return nil
})
server.Use(middlewares.User())
- status, _ := server.
+ status, response := server.
OnTenant(mock.DemoTenant).
AddHeader("Accept", "application/json").
AddCookie(web.CookieAuthName, token).
@@ -155,7 +122,8 @@ func TestUser_LockedTenant_Visitor(t *testing.T) {
return c.String(http.StatusOK, c.User().Name)
})
- Expect(status).Equals(http.StatusForbidden)
+ Expect(status).Equals(http.StatusOK)
+ Expect(response.Body.String()).Equals("Arya Stark")
}
func TestUser_WithCookie_InvalidUser(t *testing.T) {
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index b278de4c4..82ab9cb18 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -212,17 +212,38 @@ func (c *Context) IsAjax() bool {
return strings.Contains(accept, JSONContentType) || strings.Contains(contentType, JSONContentType)
}
-//Unauthorized returns a 403 error response
+//Unauthorized returns a 401 error response
func (c *Context) Unauthorized() error {
+ if c.IsAjax() {
+ return c.JSON(http.StatusUnauthorized, Map{})
+ }
+
+ return c.Page(http.StatusUnauthorized, Props{
+ Page: "Error/Error401.page",
+ Title: "Unauthorized",
+ Description: "You need to be authenticated to access this page.",
+ })
+}
+
+//Forbidden returns a 403 error response
+func (c *Context) Forbidden() error {
+ if c.IsAjax() {
+ return c.JSON(http.StatusForbidden, Map{})
+ }
+
return c.Page(http.StatusForbidden, Props{
Page: "Error/Error403.page",
- Title: "Not Authorized",
- Description: "You are not authorized to view this page.",
+ Title: "Forbidden",
+ Description: "You do not have access to this page.",
})
}
//NotFound returns a 404 error page
func (c *Context) NotFound() error {
+ if c.IsAjax() {
+ return c.JSON(http.StatusNotFound, Map{})
+ }
+
return c.Page(http.StatusNotFound, Props{
Page: "Error/Error404.page",
Title: "Page Not Found",
@@ -269,7 +290,7 @@ func (c *Context) HandleValidation(result *validate.Result) error {
}
if !result.Authorized {
- return c.Unauthorized()
+ return c.Forbidden()
}
return c.BadRequest(Map{
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index f0c92841d..f1fa88278 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -192,7 +192,7 @@ func (r *Renderer) Render(w io.Writer, statusCode int, props Props, ctx *Context
oauthProviders := &query.ListActiveOAuthProviders{
Result: make([]*dto.OAuthProviderOption, 0),
}
- if !ctx.IsAuthenticated() && statusCode >= 200 && statusCode < 300 {
+ if !ctx.IsAuthenticated() && statusCode >= 200 && statusCode < 500 {
err = bus.Dispatch(ctx, oauthProviders)
if err != nil {
panic(errors.Wrap(err, "failed to get list of providers"))
diff --git a/app/pkg/web/renderer_test.go b/app/pkg/web/renderer_test.go
index 834c813fb..91c533dfb 100644
--- a/app/pkg/web/renderer_test.go
+++ b/app/pkg/web/renderer_test.go
@@ -189,15 +189,3 @@ func TestRenderer_WithOAuth(t *testing.T) {
renderer.Render(buf, http.StatusOK, web.Props{}, ctx)
compareRendererResponse(buf, "/app/pkg/web/testdata/oauth.html", ctx)
}
-
-func TestRenderer_NonOK(t *testing.T) {
- RegisterT(t)
-
- // it should not dispatch query.ListActiveOAuthProviders
- buf := new(bytes.Buffer)
- ctx := newGetContext("https://demo.test.fider.io:3000/", nil)
- renderer := web.NewRenderer()
- renderer.Render(buf, http.StatusNotFound, web.Props{}, ctx)
- renderer.Render(buf, http.StatusBadRequest, web.Props{}, ctx)
- renderer.Render(buf, http.StatusTemporaryRedirect, web.Props{}, ctx)
-}
diff --git a/locale/de/client.json b/locale/de/client.json
index a41683401..180269a49 100644
--- a/locale/de/client.json
+++ b/locale/de/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Gestartet",
"error.expired.text": "Der Link, dem du gefolgt bist, ist abgelaufen.",
"error.expired.title": "Abgelaufen",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Ein Fehler ist aufgetreten und wir arbeiten daran, das Problem zu beheben! Wir werden in Kürze wieder online sein.",
"error.internalerror.title": "Oh! Nun, das kam unerwartet…",
"error.pagenotfound.text": "Vielleicht war der Link fehlerhaft oder die Seite existiert nicht mehr.",
diff --git a/locale/en/client.json b/locale/en/client.json
index ef9e14d04..b778b9cb0 100644
--- a/locale/en/client.json
+++ b/locale/en/client.json
@@ -20,12 +20,14 @@
"enum.poststatus.started": "Started",
"error.expired.text": "The link you clicked has expired.",
"error.expired.title": "Expired",
+ "error.forbidden.text": "You are not authorized to view this page.",
+ "error.forbidden.title": "Forbidden",
"error.internalerror.text": "An error has occurred and we're working to fix the problem! We’ll be up and running shortly.",
"error.internalerror.title": "Shoot! Well, this is unexpected…",
"error.pagenotfound.text": "The link you clicked may be broken or the page may have been removed.",
"error.pagenotfound.title": "Page not found",
- "error.unauthorized.text": "You are not authorized to view this page.",
- "error.unauthorized.title": "Not Authorized",
+ "error.unauthorized.text": "You need to authenticate before accessing accessing this page.",
+ "error.unauthorized.title": "Unauthorized",
"home.form.defaultinvitation": "Enter your suggestion here...",
"home.form.defaultwelcomemessage": "We'd love to hear what you're thinking about.\n\nWhat can we do better? This is the place for you to vote, discuss and share ideas.",
"home.lonely.suggestion": "It's recommended that you create <0>at least 3</0> suggestions here before sharing this site. The initial content is important to start engaging your audience.",
diff --git a/locale/es-ES/client.json b/locale/es-ES/client.json
index 116f70715..61e3a3b50 100644
--- a/locale/es-ES/client.json
+++ b/locale/es-ES/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Iniciado",
"error.expired.text": "El enlace en el que hizo clic ha expirado.",
"error.expired.title": "Caducado",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "¡Ha ocurrido un error y estamos trabajando para solucionar el problema! Estaremos funcionando en breve.",
"error.internalerror.title": "¡Caracoles! Bueno, esto es inesperado…",
"error.pagenotfound.text": "El hipervínculo que has seguido puede estar roto o quizás esta página ya no exista.",
diff --git a/locale/fr/client.json b/locale/fr/client.json
index 235b7a9b7..20539db89 100644
--- a/locale/fr/client.json
+++ b/locale/fr/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Démarré",
"error.expired.text": "Le lien que vous avez cliqué a expiré.",
"error.expired.title": "Expiré",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Une erreur est survenue et nous travaillons à la résolution du problème ! Nous serons opérationnels sous peu.",
"error.internalerror.title": "Oops ! C'est inattendu…",
"error.pagenotfound.text": "Le lien que vous avez suivi est peut être brisé ou la page peut avoir été supprimée.",
diff --git a/locale/nl/client.json b/locale/nl/client.json
index 00434389d..23a765987 100644
--- a/locale/nl/client.json
+++ b/locale/nl/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Gestart",
"error.expired.text": "De link waarop je hebt geklikt is verlopen.",
"error.expired.title": "Verlopen",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Er is een fout opgetreden en we werken aan een oplossing! We zijn snel weer beschikbaar.",
"error.internalerror.title": "Ai! Nou, dit is onverwacht…",
"error.pagenotfound.text": "De link waarop u heeft geklikt werkt niet of de pagina is mogelijk verwijderd.",
diff --git a/locale/pt-BR/client.json b/locale/pt-BR/client.json
index 84997d470..bf10f5177 100644
--- a/locale/pt-BR/client.json
+++ b/locale/pt-BR/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Iniciado",
"error.expired.text": "O link que você acessou expirou.",
"error.expired.title": "Expirado",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Desculpe, algo deu errado. Estamos trabalhando nisso e vamos corrigi-lo o mais rápido possível.",
"error.internalerror.title": "Oops, isso não era esperado…",
"error.pagenotfound.text": "O link que você acessou pode estar quebrado ou a página pode ter sido removida.",
diff --git a/locale/ru/client.json b/locale/ru/client.json
index e3fee23a3..c27df7a35 100644
--- a/locale/ru/client.json
+++ b/locale/ru/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Начато",
"error.expired.text": "Срок действия ссылки, по которой вы перешли, истёк.",
"error.expired.title": "Срок действия истёк",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Произошла ошибка, и мы уже работаем над её исправлением! В ближайшее время всё заработает.",
"error.internalerror.title": "Упс!",
"error.pagenotfound.text": "Кажется, ссылка, по которой вы перешли, недействительна. Возможно, эта страница была удалена.",
diff --git a/locale/sk/client.json b/locale/sk/client.json
index a3cdaaee4..a69f1a750 100644
--- a/locale/sk/client.json
+++ b/locale/sk/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Začaté",
"error.expired.text": "Platnosť odkazu, na ktorý ste klikli, vypršala.",
"error.expired.title": "Platnosť vypršala",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Vyskytla sa chyba a pracujeme na odstránení problému! Čoskoro budeme v prevádzke.",
"error.internalerror.title": "Tak toto je nečakané…",
"error.pagenotfound.text": "Odkaz, na ktorý ste klikli, môže byť nefunkčný alebo bola stránka odstránená.",
diff --git a/locale/sv-SE/client.json b/locale/sv-SE/client.json
index 194107fdc..562d4e151 100644
--- a/locale/sv-SE/client.json
+++ b/locale/sv-SE/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Startad",
"error.expired.text": "Länken du klickade på har gått ut.",
"error.expired.title": "Utgången",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Ett fel har inträffat och vi arbetar för att åtgärda problemet! Vi kommer att vara igång igen inom kort.",
"error.internalerror.title": "Sjutton också! Detta här var oväntat…",
"error.pagenotfound.text": "Länken du klickade på kan vara trasig eller så kan sidan ha tagits bort.",
diff --git a/locale/tr/client.json b/locale/tr/client.json
index 7b725d064..98c029f2b 100644
--- a/locale/tr/client.json
+++ b/locale/tr/client.json
@@ -20,6 +20,8 @@
"enum.poststatus.started": "Başlatıldı",
"error.expired.text": "Tıkladığınız bağlantının süresi doldu.",
"error.expired.title": "Süresi Bitmiş",
+ "error.forbidden.text": "",
+ "error.forbidden.title": "",
"error.internalerror.text": "Bir hata oluştu ama biz çözmek için üzerinde çalışıyoruz! Çok yakında tekrar hizmet vereceğiz.",
"error.internalerror.title": "Hay Allah! Bunu beklemiyorduk…",
"error.pagenotfound.text": "Tıkladığınız bağlantı bozuk veya sayfa kaldırılmış olabilir.",
diff --git a/public/pages/Error/Error401.page.tsx b/public/pages/Error/Error401.page.tsx
new file mode 100644
index 000000000..e6f6b8e6c
--- /dev/null
+++ b/public/pages/Error/Error401.page.tsx
@@ -0,0 +1,18 @@
+import React from "react"
+import { Trans } from "@lingui/macro"
+import { ErrorPageWrapper } from "./components/ErrorPageWrapper"
+
+const Error401 = () => {
+ return (
+ <ErrorPageWrapper id="p-error401" showHomeLink={true}>
+ <h1 className="text-display uppercase">
+ <Trans id="error.unauthorized.title">Unauthorized</Trans>
+ </h1>
+ <p>
+ <Trans id="error.unauthorized.text">You need to sign in before accessing this page.</Trans>
+ </p>
+ </ErrorPageWrapper>
+ )
+}
+
+export default Error401
diff --git a/public/pages/Error/Error403.page.tsx b/public/pages/Error/Error403.page.tsx
index 54e49dfea..92cbc67c4 100644
--- a/public/pages/Error/Error403.page.tsx
+++ b/public/pages/Error/Error403.page.tsx
@@ -6,10 +6,10 @@ const Error403 = () => {
return (
<ErrorPageWrapper id="p-error403" showHomeLink={true}>
<h1 className="text-display uppercase">
- <Trans id="error.unauthorized.title">Not Authorized</Trans>
+ <Trans id="error.forbidden.title">Forbidden</Trans>
</h1>
<p>
- <Trans id="error.unauthorized.text">You are not authorized to view this page.</Trans>
+ <Trans id="error.forbidden.text">You are not authorized to view this page.</Trans>
</p>
</ErrorPageWrapper>
)
diff --git a/public/services/http.ts b/public/services/http.ts
index 28c9f2835..f17d2e011 100644
--- a/public/services/http.ts
+++ b/public/services/http.ts
@@ -27,6 +27,8 @@ async function toResult<T>(response: Response): Promise<Result<T>> {
if (response.status === 500) {
notify.error("An unexpected error occurred while processing your request.")
+ } else if (response.status === 401) {
+ notify.error("You need to be authenticated to perform this operation.")
} else if (response.status === 403) {
notify.error("You are not authorized to perform this operation.")
}
diff --git a/public/ssr.tsx b/public/ssr.tsx
index c70b80aa1..3e8d3c09e 100644
--- a/public/ssr.tsx
+++ b/public/ssr.tsx
@@ -32,6 +32,7 @@ const pages: { [key: string]: any } = {
"Legal/Legal.page": require(`./pages/Legal/Legal.page`),
"DesignSystem/DesignSystem.page": require(`./pages/DesignSystem/DesignSystem.page`),
"Error/Maintenance.page": require(`./pages/Error/Maintenance.page`),
+ "Error/Error401.page": require(`./pages/Error/Error401.page`),
"Error/Error403.page": require(`./pages/Error/Error403.page`),
"Error/Error404.page": require(`./pages/Error/Error404.page`),
"Error/Error410.page": require(`./pages/Error/Error410.page`),