Skip to content

Commit

Permalink
clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
jacquesfize committed Jul 5, 2024
1 parent 86ed433 commit 3d08a99
Show file tree
Hide file tree
Showing 9 changed files with 85 additions and 192 deletions.
13 changes: 6 additions & 7 deletions src/pypnusershub/auth/auth_manager.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from .authentication import Authentication
from .providers import DefaultConfiguration
from pypnusershub.db.models import Provider
import importlib

import sqlalchemy as sa
from pypnusershub.db.models import Provider
from pypnusershub.env import db

from .authentication import Authentication
from .providers import DefaultConfiguration


class AuthManager:
"""
Expand Down Expand Up @@ -66,16 +68,13 @@ def add_provider(

def init_app(self, app, prefix: str = "/auth") -> None:
"""
Initializes the Flask application with the AuthManager.
Initializes the Flask application with the AuthManager. In addtion, it registers the authentification module blueprint.
Parameters
----------
app : Flask
The Flask application instance.
Returns
-------
None
"""
from pypnusershub.routes import routes

Expand Down
25 changes: 21 additions & 4 deletions src/pypnusershub/auth/authentication.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from typing import Any, Union
import logging

from pypnusershub.db import models
from typing import Any, Union

from marshmallow import Schema, fields
from pypnusershub.db import models

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -143,12 +142,30 @@ def revoke(self) -> Any:
log.warn("Revoke is not implemented.")
pass

def configure(self, configuration: Union[dict, Any] = {}):
def configure(self, configuration: Union[dict, Any] = {}) -> None:
"""
Configure the authentication provider based on data in the configuration file.
Parameters
----------
configuration : Union[dict, Any], optional
The configuration parameters.
Default is an empty dictionary.
"""
self.id_provider = configuration["id_provider"]
for field in ["label", "logo", "login_url", "logout_url", "group_mapping"]:
if field in configuration:
setattr(self, field, configuration[field])

@staticmethod
def configuration_schema() -> ProviderConfigurationSchema:
"""
Returns the marshmallow schema used to configure this authentication provider.
Returns
-------
ProviderConfigurationSchema
The schema used to configure this authentication provider.
"""
return ProviderConfigurationSchema
49 changes: 9 additions & 40 deletions src/pypnusershub/auth/providers/cas_inpn_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,10 @@
from typing import Any, Optional, Tuple, Union

import xmltodict
from flask import (
Response,
current_app,
make_response,
redirect,
render_template,
request,
)
from marshmallow import fields
from flask import Response, current_app, redirect, render_template, request
from geonature.utils import utilsrequests
from geonature.utils.errors import GeonatureApiError
from marshmallow import fields
from pypnusershub.auth import Authentication, ProviderConfigurationSchema
from pypnusershub.db import db, models
from pypnusershub.routes import insert_or_update_organism, insert_or_update_role
Expand All @@ -25,30 +18,6 @@ class CasAuthentificationError(GeonatureApiError):
pass


AUTHENTIFICATION_CONFIG = {
"PROVIDER_NAME": "inpn",
"EXTERNAL_PROVIDER": True,
}

CAS_AUTHENTIFICATION = True
CAS_PUBLIC = dict(
URL_LOGIN="https://inpn.mnhn.fr/auth/login",
URL_LOGOUT="https://inpn.mnhn.fr/auth/logout",
URL_VALIDATION="https://inpn.mnhn.fr/auth/serviceValidate",
)

CAS_USER_WS = dict(
URL="https://inpn.mnhn.fr/authentication/information",
BASE_URL="https://inpn.mnhn.fr/authentication/",
ID="change_value",
PASSWORD="change_value",
)
USERS_CAN_SEE_ORGANISM_DATA = False

ID_USER_SOCLE_1 = 1
ID_USER_SOCLE_2 = 2


class AuthenficationCASINPN(Authentication):
name = "CAS_INPN_PROVIDER"
label = "INPN"
Expand Down Expand Up @@ -157,16 +126,14 @@ def insert_user_and_org(self, info_user, id_provider):
"email": info_user["email"],
"active": True,
}
user = insert_or_update_role(
models.User(**user_info), provider_name=self.id_provider
)
user = insert_or_update_role(models.User(**user_info), provider_instance=self)
if not user.groups:
if not USERS_CAN_SEE_ORGANISM_DATA or organism_id is None:
if not self.USERS_CAN_SEE_ORGANISM_DATA or organism_id is None:
# group socle 1
group_id = ID_USER_SOCLE_1
group_id = self.ID_USER_SOCLE_1
else:
# group socle 2
group_id = ID_USER_SOCLE_2
group_id = self.ID_USER_SOCLE_2
group = db.session.get(models.User, group_id)
user.groups.append(group)
return user
Expand All @@ -187,11 +154,13 @@ class CASINPNConfiguration(ProviderConfigurationSchema):
)
WS_ID = fields.String(required=True)
WS_PASSWORD = fields.String(required=True)
USERS_CAN_SEE_ORGANISM_DATA = fields.Boolean(load_default=False)
ID_USER_SOCLE_1 = fields.Integer(load_default=7)
ID_USER_SOCLE_2 = fields.Integer(load_default=6)

return CASINPNConfiguration

def configure(self, configuration: Union[dict, Any]):
super().configure(configuration)
print(configuration)
for key in configuration:
setattr(self, key, configuration[key])
16 changes: 4 additions & 12 deletions src/pypnusershub/auth/providers/github_provider.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
from typing import Union

from authlib.integrations.flask_client import OAuth
from flask import (
Response,
current_app,
url_for,
)
from flask import Response, current_app, url_for
from pypnusershub.auth import Authentication
from pypnusershub.db import models, db
from pypnusershub.db import db, models
from pypnusershub.routes import insert_or_update_role


oauth = OAuth(current_app)
oauth.register(
name="github",
Expand All @@ -32,6 +27,7 @@ class GitHubAuthProvider(Authentication):
login_url = "http://127.0.0.1:8000/auth/login/github"
logout_url = ""
logo = '<i class="fa fa-github"></i>'
name = "GITHUB_PROVIDER_CONFIG"

def authenticate(self, *args, **kwargs) -> Union[Response, models.User]:
redirect_uri = url_for(
Expand All @@ -52,15 +48,11 @@ def authorize(self):
"prenom_role": prenom,
"nom_role": nom,
"active": True,
"provider": "github",
}
user_info = insert_or_update_role(new_user)
user_info = insert_or_update_role(new_user, self)
user = db.session.get(models.User, user_info["id_role"])
if not user.groups:
group = db.session.get(models.User, 2) # ADMIN for test
user.groups.append(group)
db.session.commit()
return user


# Accueil : https://ginco2-preprod.mnhn.fr/ (URL publique) + http://ginco2-preprod.patnat.mnhn.fr/ (URL privée)
73 changes: 0 additions & 73 deletions src/pypnusershub/auth/providers/google_provider.py

This file was deleted.

31 changes: 20 additions & 11 deletions src/pypnusershub/auth/providers/openid_provider.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import requests

from authlib.integrations.flask_client import OAuth
from marshmallow import Schema, fields
from typing import Any, Optional, Tuple, Union
from flask import Response, current_app, url_for, session
from werkzeug.exceptions import Unauthorized
from typing import Optional, Tuple, Union

import requests
from flask import Response, current_app, session, url_for
from marshmallow import fields
from pypnusershub.auth import Authentication, ProviderConfigurationSchema, oauth
from pypnusershub.db import models, db
from pypnusershub.db import db, models
from pypnusershub.routes import insert_or_update_role
from pypnusershub.auth.auth_manager import auth_manager
from werkzeug.exceptions import Unauthorized


class OpenIDProvider(Authentication):
"""
OpenID provider authentication class.
This class handle the authentication process with an OpenID provider.
"""

name = "OPENID_PROVIDER_CONFIG"
logo = '<i class="fa fa-sign-in"></i>'
is_uh = False
login_url = ""
logout_url = ""
"""
Name of the fields in the OpenID token that contains the groups info
"""
Expand Down Expand Up @@ -93,6 +95,13 @@ class OpenIDProviderConfiguration(ProviderConfigurationSchema):


class OpenIDConnectProvider(OpenIDProvider):
"""
OpenID Connect provider authentication class.
This class handle the authentication process with an OpenID Connect provider.
"""

name = "OPENID_CONNECT_PROVIDER_CONFIG"

def revoke(self):
Expand Down
18 changes: 9 additions & 9 deletions src/pypnusershub/auth/providers/usershub_provider.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import requests
from typing import Any, Optional, Tuple, Union

from marshmallow import Schema, fields

from flask import request, Response, url_for, current_app, redirect
from werkzeug.exceptions import Unauthorized
from sqlalchemy import select
from typing import Optional, Tuple

from geonature.utils.env import db
import requests
from flask import request
from marshmallow import fields
from pypnusershub.auth import Authentication, ProviderConfigurationSchema
from pypnusershub.db.models import User
from pypnusershub.routes import insert_or_update_role
from werkzeug.exceptions import Unauthorized


class ExternalUsersHubAuthProvider(Authentication):
"""
Authentication provider for Flask application using UsersHub-authentification-module.
"""

name = "EXTERNAL_USERSHUB_PROVIDER_CONFIG"
logo = '<i class="fa fa-users"></i>'

Expand Down
Loading

0 comments on commit 3d08a99

Please sign in to comment.