Skip to content

Authentication and Authorization - #104

Merged
eadwinCode merged 17 commits into
mainfrom
auth_shield
Jul 18, 2023
Merged

Authentication and Authorization#104
eadwinCode merged 17 commits into
mainfrom
auth_shield

Conversation

@eadwinCode

@eadwinCode eadwinCode commented Jun 29, 2023

Copy link
Copy Markdown
Collaborator

New Feature

  • Session Middleware - Abstracted session middleware actions to a service.
  • Resolving Middleware instances with DI
  • Added Authentication Service
  • Added Authorization Service to manage users Role-based permissions and Claim-based permissions

Setup

import base64
import pickle
import typing as t

from ellar.auth.handlers import HeaderAPIKeyAuthenticationHandler
from ellar.auth.identity import UserIdentity
from ellar.common import AnonymousIdentity, Identity, IHostContext
from ellar.di import injectable
from ellar.auth import BasePolicyHandler


@injectable
class SimpleHeaderAuthHandler(HeaderAPIKeyAuthenticationHandler):
    async def authentication_handler(
        self, context: IHostContext, key: str
    ) -> t.Optional[Identity]:
        data = pickle.loads(base64.b64decode(key))
        if isinstance(data, dict):
            return UserIdentity(auth_type="token", **data)
        return AnonymousIdentity()



@injectable
class CheckUserFirstName(BasePolicyHandler):
    async def handle(self, context: IHostContext) -> bool:
        return context.user.first_name == 'ellar'

Controller

from ellar.auth import Authorization, AuthorizationGuard, Policy
from ellar.common import Controller, get

from .requirement import CheckUserFirstName


@Controller("/article")
@UseGuards(AuthorizationGuard)
class ArticleController:
    @get("/create")
    @CheckPolicies(RequiredClaimsPolicy("article", "create", "publish"))
    async def create_and_publish(self):
        return "Accessible to user with article claim of values 'create' or 'publish'"

    @get("/admin-only")
    @CheckPolicies(RequiredRolePolicy("admin"))
    async def admin_only(self):
        return "Endpoint is accessible to only admins"

    @get("/staff-only")
    @CheckPolicies(RequiredRolePolicy("admin") | RequiredRolePolicy("staff"))
    async def staff_only(self):
        return "Endpoint is accessible to both staff and admin users"

    @get("/ellar-first-name")
    @CheckPolicies(CheckUserFirstName])
    async def ellar_first_name(self):
        return "Accessible to user with first name == ellar"

## Server
app = AppFactory.create_application()
app.add_authentication_schemes(SimpleHeaderAuthHandler)

@eadwinCode eadwinCode closed this Jun 30, 2023
@eadwinCode eadwinCode reopened this Jul 2, 2023
@codecov-commenter

codecov-commenter commented Jul 2, 2023

Copy link
Copy Markdown

Codecov Report

Merging #104 (c93a8a7) into main (06de9fd) will increase coverage by 0.58%.
The diff coverage is 99.47%.

❗ Your organization is not using the GitHub App Integration. As a result you may experience degraded service beginning May 15th. Please install the Github App Integration for your organization. Read more.

@@            Coverage Diff             @@
##             main     #104      +/-   ##
==========================================
+ Coverage   97.83%   98.41%   +0.58%     
==========================================
  Files         238      269      +31     
  Lines        6733     7209     +476     
==========================================
+ Hits         6587     7095     +508     
+ Misses        146      114      -32     
Impacted Files Coverage Δ
ellar/common/__init__.py 100.00% <ø> (ø)
ellar/common/decorators/__init__.py 100.00% <ø> (ø)
ellar/common/exceptions/api/base.py 100.00% <ø> (+8.69%) ⬆️
ellar/common/helper/importer.py 100.00% <ø> (+26.82%) ⬆️
ellar/common/helper/module_loading.py 100.00% <ø> (+9.09%) ⬆️
ellar/common/interfaces/controller_factory.py 0.00% <ø> (ø)
ellar/common/interfaces/exceptions.py 100.00% <ø> (+5.55%) ⬆️
ellar/common/params/args/base.py 100.00% <ø> (ø)
ellar/common/params/args/extra_args.py 100.00% <ø> (+7.14%) ⬆️
ellar/common/routing/mount.py 97.36% <0.00%> (-0.04%) ⬇️
... and 74 more

... and 4 files with indirect coverage changes

@eadwinCode
eadwinCode merged commit 97bdfe9 into main Jul 18, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants