diff --git a/pkg/models/api_tokens.go b/pkg/models/api_tokens.go index 00ae5b747..6552d14eb 100644 --- a/pkg/models/api_tokens.go +++ b/pkg/models/api_tokens.go @@ -20,6 +20,7 @@ import ( "crypto/sha256" "crypto/subtle" "encoding/hex" + "slices" "time" "code.vikunja.io/api/pkg/db" @@ -169,6 +170,15 @@ func (t *APIToken) Delete(s *xorm.Session, a web.Auth) (err error) { return err } +// HasCaldavAccess checks whether the token has the caldav access permission. +func (t *APIToken) HasCaldavAccess() bool { + perms, has := t.APIPermissions["caldav"] + if !has { + return false + } + return slices.Contains(perms, "access") +} + // GetTokenFromTokenString returns the full token object from the original token string. func GetTokenFromTokenString(s *xorm.Session, token string) (apiToken *APIToken, err error) { lastEight := token[len(token)-8:] diff --git a/pkg/models/api_tokens_test.go b/pkg/models/api_tokens_test.go index e0ebca8d6..6677c09fa 100644 --- a/pkg/models/api_tokens_test.go +++ b/pkg/models/api_tokens_test.go @@ -95,6 +95,36 @@ func TestAPIToken_Create(t *testing.T) { }) } +func TestAPIToken_HasCaldavAccess(t *testing.T) { + t.Run("has caldav access", func(t *testing.T) { + token := &APIToken{ + APIPermissions: APIPermissions{"caldav": {"access"}}, + } + assert.True(t, token.HasCaldavAccess()) + }) + t.Run("no caldav group", func(t *testing.T) { + token := &APIToken{ + APIPermissions: APIPermissions{"tasks": {"read_all"}}, + } + assert.False(t, token.HasCaldavAccess()) + }) + t.Run("caldav group but wrong permission", func(t *testing.T) { + token := &APIToken{ + APIPermissions: APIPermissions{"caldav": {"read_all"}}, + } + assert.False(t, token.HasCaldavAccess()) + }) + t.Run("caldav access among other permissions", func(t *testing.T) { + token := &APIToken{ + APIPermissions: APIPermissions{ + "tasks": {"read_all", "update"}, + "caldav": {"access"}, + }, + } + assert.True(t, token.HasCaldavAccess()) + }) +} + func TestAPIToken_GetTokenFromTokenString(t *testing.T) { t.Run("valid token", func(t *testing.T) { s := db.NewSession()