Skip to content

fix: redirect to login upon authentication error #9134

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 17, 2023
Prev Previous commit
Next Next commit
make check slightly more specific, and add tests to make sure it does…
…n't break
  • Loading branch information
aslilac committed Aug 17, 2023
commit afc8602715ca700e30de9363d4ec0847be3a7de0
3 changes: 3 additions & 0 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ func ExtractAPIKey(rw http.ResponseWriter, r *http.Request, cfg ExtractAPIKeyCon
}

// Checking if the key is expired.
// NOTE: The `RequireAuth` React component depends on this `Detail` to detect when
// the users token has expired. If you change the text here, make sure to update it
// in site/src/components/RequireAuth/RequireAuth.tsx as well.
if key.ExpiresAt.Before(now) {
return optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: SignedOutErrorMessage,
Expand Down
4 changes: 4 additions & 0 deletions coderd/httpmw/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
Expand Down Expand Up @@ -197,6 +198,9 @@ func TestAPIKey(t *testing.T) {
res := rw.Result()
defer res.Body.Close()
require.Equal(t, http.StatusUnauthorized, res.StatusCode)
out, _ := io.ReadAll(res.Body)
require.Contains(t, string(out))
require.True(t, strings.HasPrefix(string(out), "API key expired"))
})

t.Run("Valid", func(t *testing.T) {
Expand Down
6 changes: 5 additions & 1 deletion site/src/components/RequireAuth/RequireAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { embedRedirect } from "../../utils/redirect"
import { FullScreenLoader } from "../Loader/FullScreenLoader"
import { DashboardProvider } from "components/Dashboard/DashboardProvider"
import { ProxyProvider } from "contexts/ProxyContext"
import { getErrorDetail } from "api/errors"

export const RequireAuth: FC = () => {
const [authState, authSend] = useAuth()
Expand All @@ -22,7 +23,10 @@ export const RequireAuth: FC = () => {
// 401 Unauthorized
// If we encountered an authentication error, then our token is probably
// invalid and we should update the auth state to reflect that.
if (error.response.status === 401) {
if (
error.response.status === 401 &&
getErrorDetail(error)?.startsWith("API key expired")
) {
authSend("SIGN_OUT")
}

Expand Down