refactor(handler/default): minor cleanups for loginstatus

This commit is contained in:
Trong Huu Nguyen
2022-07-18 16:48:01 +02:00
parent bece03c94e
commit 81fa96ccb8
3 changed files with 69 additions and 5 deletions

View File

@@ -19,12 +19,12 @@ func (h *Handler) Default(w http.ResponseWriter, r *http.Request) {
if hasAccessToken {
// add authentication if session cookie and token checks out
isAuthenticated = true
}
// force new authentication if loginstatus is enabled and cookie isn't set
if h.Cfg.Wonderwall().Loginstatus.Enabled && !h.Loginstatus.HasCookie(r) {
isAuthenticated = false
logentry.LogEntry(r).Info("default: loginstatus was enabled, but no matching cookie was found; state is now unauthenticated")
}
// force new authentication if loginstatus is enabled and cookie isn't set
if h.Loginstatus.NeedsLogin(r) {
isAuthenticated = false
logentry.LogEntry(r).Info("default: loginstatus was enabled, but no matching cookie was found; state is now unauthenticated")
}
if h.AutoLogin.NeedsLogin(r, isAuthenticated) {

View File

@@ -23,6 +23,7 @@ type Client interface {
HasCookie(r *http.Request) bool
ClearCookie(w http.ResponseWriter, opts cookie.Options)
CookieOptions(opts cookie.Options) cookie.Options
NeedsLogin(r *http.Request) bool
}
func NewClient(config config.Loginstatus, httpClient *http.Client) Client {
@@ -100,6 +101,14 @@ func (c client) CookieOptions(opts cookie.Options) cookie.Options {
WithPath("/")
}
func (c client) NeedsLogin(r *http.Request) bool {
if c.config.Enabled && !c.HasCookie(r) {
return true
}
return false
}
func request(ctx context.Context, url string, token string) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {

View File

@@ -174,6 +174,61 @@ func TestClient_CookieOptions(t *testing.T) {
}
}
func TestClient_NeedsLogin(t *testing.T) {
for _, test := range []struct {
name string
enabled bool
hasCookie bool
expected bool
}{
{
name: "not enabled, no cookie",
enabled: false,
hasCookie: false,
expected: false,
},
{
name: "not enabled, has cookie",
enabled: false,
hasCookie: true,
expected: false,
},
{
name: "enabled, no cookie",
enabled: true,
hasCookie: false,
expected: true,
},
{
name: "enabled, has cookie",
enabled: true,
hasCookie: true,
expected: false,
},
} {
t.Run(test.name, func(t *testing.T) {
cfg := newCfg("https://some-server")
cfg.Enabled = test.enabled
client := loginstatus.NewClient(cfg, http.DefaultClient)
opts := client.CookieOptions(cookieOpts)
c := cookie.Make(cfg.CookieName, "some-value", opts)
r := httptest.NewRequest(http.MethodGet, "/", nil)
if test.hasCookie {
r.AddCookie(c.Cookie)
}
if test.expected {
assert.True(t, client.NeedsLogin(r))
} else {
assert.False(t, client.NeedsLogin(r))
}
})
}
}
func newCfg(serverURL string) config.Loginstatus {
return config.Loginstatus{
Enabled: true,