add anonymouse principal

gitness-public-repo-testing
atefeh 2024-05-01 20:10:04 -07:00
parent 3f7ca795eb
commit 3471bf806d
4 changed files with 34 additions and 15 deletions

View File

@ -15,7 +15,6 @@
package authn
import (
"errors"
"net/http"
"github.com/harness/gitness/app/api/render"
@ -52,11 +51,6 @@ func performAuthentication(
session, err := authenticator.Authenticate(r)
if err != nil {
if !errors.Is(err, authn.ErrNoAuthData) {
// log error to help with investigating any auth related errors
log.Warn().Err(err).Msg("authentication failed")
}
if required {
render.Unauthorized(ctx, w)
return

30
app/auth/anonymouse.go Normal file
View File

@ -0,0 +1,30 @@
// Copyright 2023 Harness, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth
import (
"github.com/harness/gitness/types"
"github.com/harness/gitness/types/enum"
)
// Anonymouse is an in-memory principal for users with no auth data.
// Authorizer is in charge of handling public access.
func Anonymouse() *types.Principal {
return &types.Principal{
ID: -1,
UID: "ALL_USERS",
Type: enum.PrincipalTypeUser,
}
}

View File

@ -15,25 +15,18 @@
package authn
import (
"errors"
"net/http"
"github.com/harness/gitness/app/auth"
)
var (
// ErrNoAuthData that is returned if the authorizer doesn't find any data in the request that can be used for auth.
ErrNoAuthData = errors.New("the request doesn't contain any auth data that can be used by the Authorizer")
)
// Authenticator is an abstraction of an entity that's responsible for authenticating principals
// that are making calls via HTTP.
type Authenticator interface {
/*
* Tries to authenticate the acting principal if credentials are available.
* Returns:
* (session, nil) - request contains auth data and principal was verified
* (nil, ErrNoAuthData) - request doesn't contain any auth data
* (session, nil) - request contains auth data and principal was verified or is anonymouse
* (nil, err) - request contains auth data but verification failed
*/
Authenticate(r *http.Request) (*auth.Session, error)

View File

@ -56,7 +56,9 @@ func (a *JWTAuthenticator) Authenticate(r *http.Request) (*auth.Session, error)
str := extractToken(r, a.cookieName)
if len(str) == 0 {
return nil, ErrNoAuthData
return &auth.Session{
Principal: *auth.Anonymouse(),
}, nil
}
var principal *types.Principal