Skip to content

Commit

Permalink
Merge branch 'develop' into fix/various
Browse files Browse the repository at this point in the history
  • Loading branch information
jpm-cbna committed Mar 21, 2022
2 parents 7e9020f + aae10bd commit 8a460a6
Show file tree
Hide file tree
Showing 57 changed files with 896 additions and 2,942 deletions.
4 changes: 4 additions & 0 deletions .flaskenv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
FLASK_APP=app.app:create_app
FLASK_RUN_PORT=5001
FLASK_ENV=development
FLASK_DEBUG=1
9 changes: 8 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,11 @@ fontawesome*

*.php

app/templates/mails/sign_up_confirmation.html
app/templates/mails/sign_up_confirmation.html

/docs/changelog.html

*.swp
*.swo

*.egg-info/
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "dependencies/UsersHub-authentification-module"]
path = dependencies/UsersHub-authentification-module
url = https://github.com/PnX-SI/UsersHub-authentification-module
4 changes: 4 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
include VERSION
include LICENSE
include README.rst
include requirements.in
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2.1.4.dev0
2.2.2
142 changes: 142 additions & 0 deletions app/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""
Serveur de l'application UsersHub
"""

import os
import sys
import json
from pkg_resources import iter_entry_points
from urllib.parse import urlsplit

from flask import (
Flask, redirect, url_for,
request, session, render_template,
g
)
from werkzeug.middleware.proxy_fix import ProxyFix
from sqlalchemy.exc import ProgrammingError
from flask_migrate import Migrate

from app.env import db

from pypnusershub.db.models import Application


migrate = Migrate()


@migrate.configure
def configure_alembic(alembic_config):
"""
This function add to the 'version_locations' parameter of the alembic config the
'migrations' entry point value of the 'gn_module' group for all modules having such entry point.
Thus, alembic will find migrations of all installed geonature modules.
"""
version_locations = alembic_config.get_main_option('version_locations', default='').split()
for entry_point in iter_entry_points('alembic', 'migrations'):
_, migrations = str(entry_point).split('=', 1)
version_locations += [ migrations.strip() ]
alembic_config.set_main_option('version_locations', ' '.join(version_locations))
return alembic_config


def create_app():
app = Flask(__name__)
app.config.from_pyfile("../config/config.py")
app.config['APPLICATION_ROOT'] = urlsplit(app.config['URL_APPLICATION']).path or '/'
if 'SCRIPT_NAME' not in os.environ and app.config['APPLICATION_ROOT'] != '/':
os.environ['SCRIPT_NAME'] = app.config['APPLICATION_ROOT']
app.config["URL_REDIRECT"] = "{}/{}".format(app.config["URL_APPLICATION"], "login")
app.secret_key = app.config["SECRET_KEY"]
app.wsgi_app = ProxyFix(app.wsgi_app, x_host=1)

db.init_app(app)
app.config["DB"] = db

migrate.init_app(app, db, directory='app/migrations')

with app.app_context():
app.jinja_env.globals["url_application"] = app.config["URL_APPLICATION"]

try:
uh_app = Application.query.filter_by(code_application='UH').one()
except ProgrammingError:
logging.warning("Warning: unable to find UsersHub application, database not yet initialized?")
else:
app.config["ID_APP"] = uh_app.id_application

if app.config["ACTIVATE_APP"]:
@app.route("/")
def index():
""" Route par défaut de l'application """
return redirect(url_for("user.users"))

@app.route("/constants.js")
def constants_js():
""" Route des constantes javascript """
return render_template("constants.js")

@app.after_request
def after_login_method(response):
"""
Fonction s'exécutant après chaque requete
permet de gérer l'authentification
"""
if not request.cookies.get("token"):
session["current_user"] = None

if request.endpoint == "auth.login" and response.status_code == 200: # noqa
current_user = json.loads(response.get_data().decode("utf-8"))
session["current_user"] = current_user["user"]
return response

@app.context_processor
def inject_user():
return dict(user=getattr(g, "user", None))

from pypnusershub import routes

app.register_blueprint(routes.routes, url_prefix="/pypn/auth")

from app.t_roles import route

app.register_blueprint(route.route, url_prefix="/")

from app.bib_organismes import route

app.register_blueprint(route.route, url_prefix="/")

from app.groupe import route

app.register_blueprint(route.route, url_prefix="/")

from app.liste import route

app.register_blueprint(route.route, url_prefix="/")

from app.t_applications import route

app.register_blueprint(route.route, url_prefix="/")

from app.t_profils import route

app.register_blueprint(route.route, url_prefix="/")

from app.login import route

app.register_blueprint(route.route, url_prefix="/")

from app.temp_users import routes

app.register_blueprint(routes.routes, url_prefix="/temp_users")

from app.api import route

app.register_blueprint(route.route, url_prefix="/api")

if app.config['ACTIVATE_API']:
from app.api import route_register

app.register_blueprint(route_register.route, url_prefix="/api_register") # noqa

return app
5 changes: 3 additions & 2 deletions app/env.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@

import os
from flask_sqlalchemy import SQLAlchemy


"""
Création de la base avec sqlalchemy
"""

db = SQLAlchemy()
os.environ['FLASK_SQLALCHEMY_DB'] = 'app.env.db'
db = SQLAlchemy()
8 changes: 1 addition & 7 deletions app/login/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,4 @@

@route.route('login', methods=['GET'])
def login():
t_app = TApplications.get_all(
columns=["id_application"],
params=[{'col': 'code_application', 'filter': 'UH'}],
recursif=False
)
ID_APP = t_app[0]['id_application']
return render_template('login.html', id_app=ID_APP)
return render_template('login.html', id_app=current_app.config['ID_APP'])
1 change: 1 addition & 0 deletions app/migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
File renamed without changes.
47 changes: 47 additions & 0 deletions app/migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

version_locations = %(here)s/versions


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
96 changes: 96 additions & 0 deletions app/migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
from __future__ import with_statement

import logging
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
target_metadata = current_app.extensions['migrate'].db.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')

connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions app/migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""upgrade utilisateurs schema
Revision ID: 6ec215fe023e
Revises: 9445a69f2bed
Create Date: 2021-09-30 16:29:25.531376
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '6ec215fe023e'
down_revision = '9445a69f2bed'
branch_labels = None
depends_on = (
'951b8270a1cf', # utilisateurs
)


def upgrade():
pass


def downgrade():
pass
Loading

0 comments on commit 8a460a6

Please sign in to comment.