github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/services/permissions/enforce.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package permissions
    19  
    20  import (
    21  	"github.com/aacfactory/errors"
    22  	"github.com/aacfactory/fns/commons/bytex"
    23  	"github.com/aacfactory/fns/context"
    24  	"github.com/aacfactory/fns/runtime"
    25  	"github.com/aacfactory/fns/services"
    26  	"github.com/aacfactory/fns/services/authorizations"
    27  )
    28  
    29  var (
    30  	ErrForbidden = errors.Forbidden("forbidden")
    31  )
    32  
    33  func EnforceContext(ctx context.Context) (err error) {
    34  	authorization, has, loadErr := authorizations.Load(ctx)
    35  	if loadErr != nil {
    36  		err = authorizations.ErrUnauthorized.WithCause(loadErr)
    37  		return
    38  	}
    39  	if !has {
    40  		err = authorizations.ErrUnauthorized
    41  		return
    42  	}
    43  	if !authorization.Validate() {
    44  		err = authorizations.ErrUnauthorized
    45  		return
    46  	}
    47  	r := services.LoadRequest(ctx)
    48  	endpoint, fn := r.Fn()
    49  	ok, enforceErr := Enforce(ctx, EnforceParam{
    50  		Account:  authorization.Account,
    51  		Endpoint: bytex.ToString(endpoint),
    52  		Fn:       bytex.ToString(fn),
    53  	})
    54  	if enforceErr != nil {
    55  		err = errors.Warning("permissions: enforce failed").WithCause(enforceErr)
    56  		return
    57  	}
    58  	if !ok {
    59  		err = ErrForbidden
    60  		return
    61  	}
    62  	return
    63  }
    64  
    65  func Enforce(ctx context.Context, param EnforceParam) (ok bool, err error) {
    66  	rt := runtime.Load(ctx)
    67  	response, handleErr := rt.Endpoints().Request(
    68  		ctx,
    69  		endpointName, enforceFnName,
    70  		param,
    71  	)
    72  	if handleErr != nil {
    73  		err = handleErr
    74  		return
    75  	}
    76  	ok, err = services.ValueOfParam[bool](response)
    77  	if err != nil {
    78  		err = errors.Warning("permissions: enforce failed").WithCause(err)
    79  		return
    80  	}
    81  	return
    82  }