Skip to content

Commit

Permalink
Merge branch 'main' into docker-ci
Browse files Browse the repository at this point in the history
  • Loading branch information
Pipazoul committed Nov 27, 2023
2 parents 8bc44eb + 7304ad2 commit a2e6015
Show file tree
Hide file tree
Showing 20 changed files with 455 additions and 634 deletions.
6 changes: 3 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
FROM python:3.8
FROM python:3.8-slim
ENV TZ=Europe/Paris
RUN mkdir -p /var/www
RUN apt update
RUN apt install ffmpeg libglu1-mesa libsm6 libxext6 libxmu6 -y
RUN apt install ffmpeg libglu1-mesa libsm6 libxext6 libxmu6 -y && rm -rf /var/lib/apt/lists/*
COPY . /var/www/back/
WORKDIR /var/www/back/
RUN pip3 install --no-cache-dir -r requirements.txt
ENTRYPOINT ["python", "run.py"]
ENTRYPOINT ["python", "run.py", "-e", "[email protected]", "-p", "Dev"]
2 changes: 2 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def my_expired_token_callback(expired_token, jwt_payload):
from .docs.views import docs as docs_bp
from .modules.authentications.views import authentications as authentications_bp
from .modules.users.views import users as users_bp
from .modules.documents.views import documents as documents_bp

from .modules.projects.views import projects as projects_bp
from .modules.datas.views import datas as datas_bp
Expand All @@ -100,6 +101,7 @@ def my_expired_token_callback(expired_token, jwt_payload):
app.register_blueprint(docs_bp, url_prefix="/api/docs")
app.register_blueprint(authentications_bp, url_prefix="/api/auth")
app.register_blueprint(users_bp, url_prefix="/api/users")
app.register_blueprint(documents_bp, url_prefix="/api/documents")


app.register_blueprint(projects_bp, url_prefix="/api/projects")
Expand Down
102 changes: 46 additions & 56 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@
from os import environ, path
from dotenv import load_dotenv
from loguru import logger as errorLogger
from app.utils.methods import hashStringWithSaltB64
import argparse

# Get app base directory
basedir = path.abspath(path.join(path.dirname(__file__), ".."))
# loading env vars from .env file
load_dotenv()


parser = argparse.ArgumentParser("run.py")
parser.add_argument('-e', '--email', help="The email you want to use for the demo account", type=str)
parser.add_argument('-p', '--password', help="The password you want to use for the demo account", type=str)
args = parser.parse_args()

class BaseConfig(object):
"""Base config class."""

Expand Down Expand Up @@ -65,6 +72,27 @@ class Production(BaseConfig):
"production": Production,
}

def dbchecker(conn, check):
exists = False
try:
cur = conn.cursor()
cur.execute(check)
exists = cur.fetchone()[0]
cur.close()
except psycopg2.Error as e:
errorLogger.error(e)
return exists

def sql_execute(conn, commands, f):
try:
cur = conn.cursor()
if f:
cur.execute(open(commands, "r").read())
else:
cur.execute(commands)
cur.close()
except psycopg2.Error as e:
errorLogger.error(e)

class ConfigDb(BaseConfig):
config_user = environ.get("BDD_CONFIG_USER")
Expand Down Expand Up @@ -92,66 +120,28 @@ class ConfigDb(BaseConfig):
+ config_db
)
SQLALCHEMY_TRACK_MODIFICATIONS = False

try:
conn = psycopg2.connect(
f"dbname='{config_db}' user='{config_user}' host='{config_host}' password='{config_pwd}' port='{config_port}'"
)
conn.close()
except:
errorLogger.error(
"ERROR: Fail to connect to DB with "
+ " "
+ config_db
+ " "
+ config_user
+ " "
+ config_host
+ " "
+ config_pwd
+ " "
+ config_port
)
sys.exit(1)
elif config_user and config_port and config_host and config_db:
# conf SQLALCHEMY for manage pool queue
POOL_PRE_PING = True
POOL_SIZE = 32
MAX_OVERFLOW = 64
# DB conf for SQLALCHEMY
SQLALCHEMY_DATABASE_URI = (
"postgresql+psycopg2://"
+ config_user
+ ":"
+ config_pwd
+ "@"
+ config_host
+ ":"
+ config_port
+ "/"
+ config_db
)
SQLALCHEMY_TRACK_MODIFICATIONS = False


try:
conn = psycopg2.connect(
f"dbname='{config_db}' user='{config_user}' host='{config_host}' password='{config_pwd}' port='{config_port}'"
)
conn.close()
except:
errorLogger.error(
"ERROR: Fail to connect to DB with "
+ " "
+ config_db
+ " "
+ config_user
+ " "
+ config_host
+ " "
+ config_pwd
+ " "
+ config_port
)
conn.autocommit = True
if not dbchecker(conn,"select exists(select relname from pg_class where relname='authentications')"):
sql_execute(conn,"sql/create-tables.sql", True)
cmd = "INSERT INTO base.authentications (email, password, role, status) VALUES ('%s', '%s', 'SUPERADMIN', 'ACTIVE');" % (args.email, hashStringWithSaltB64(args.password))
sql_execute(conn,cmd, False)
uid = dbchecker(conn,"SELECT id FROM base.authentications WHERE email = '" + args.email + "'")
sql_execute(conn,"INSERT INTO base.users (firstname, lastname, authentication_id) VALUES ('Démo', 'Métropole', '" + str(uid) + "');", False)
conn.close()
else:
if not dbchecker(conn,"select exists(select email from base.authentications where email='" + args.email + "')"):
cmd = "INSERT INTO base.authentications (email, password, role, status) VALUES ('%s', '%s', 'SUPERADMIN', 'ACTIVE');" % (args.email, hashStringWithSaltB64(args.password))
sql_execute(conn,cmd, False)
uid = dbchecker(conn,"SELECT id FROM base.authentications WHERE email = '" + args.email + "'")
sql_execute(conn,"INSERT INTO base.users (firstname, lastname, authentication_id) VALUES ('Démo', 'Métropole', '" + str(uid) + "');", False)
conn.close()
except psycopg2.Error as e:
errorLogger.error(e)
sys.exit(1)
else:
print(f'config_user="{config_user}"')
Expand Down
2 changes: 1 addition & 1 deletion app/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from app.utils.methods import *
from app.utils.generatePdf import *

# Create Blueprint & get logger
# Create Blueprint
core = Blueprint("core", __name__)


Expand Down
2 changes: 1 addition & 1 deletion app/docs/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from app.utils.constants import *
from app.utils.methods import *

# Create Blueprint & get logger
# Create Blueprint
docs = Blueprint("docs", __name__)


Expand Down
43 changes: 39 additions & 4 deletions app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,35 @@ def __str__(self):
+ '">'
)

class Documents(db.Model):
__table_args__ = {"schema": schema}

# fields
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
date_create = db.Column(db.Date)
type = db.Column(db.String)
title = db.Column(db.String)
file_name = db.Column(db.String)
data = db.Column(db.String)

# foreign keys
user_id = db.Column(db.Integer, db.ForeignKey(schema + ".users.id"))

# objects links
user = db.relationship("Users", foreign_keys=user_id)


def __str__(self):
return (
"<Documents id="
+ str(self.id)
+ ' title="'
+ self.title
+ '" type="'
+ self.type
+ '">'
)

class Users(db.Model):
__table_args__ = {"schema": schema}

Expand All @@ -45,7 +73,6 @@ class Users(db.Model):
firstname = db.Column(db.String)
date_archived = db.Column(db.Date)
lastname = db.Column(db.String)
phone = db.Column(db.String, nullable=True, default=None)

# foreign keys
authentication_id = db.Column(
Expand All @@ -57,7 +84,6 @@ class Users(db.Model):
)

def __str__(self):
phonePart = "NULL" if (self.phone == None) else str(self.phone)

return (
"<Users id="
Expand All @@ -66,8 +92,6 @@ def __str__(self):
+ self.firstname
+ '" lastname="'
+ str(self.lastname)
+ '" phone='
+ phonePart
+ ">"
)

Expand All @@ -86,6 +110,13 @@ class Projects(db.Model):

# foreign keys
user_id = db.Column(db.Integer, db.ForeignKey(schema + ".users.id"))
model_id = db.Column(db.Integer, db.ForeignKey(schema + ".documents.id"))
csv_id = db.Column(db.Integer, db.ForeignKey(schema + ".documents.id"))

# Object links
user = db.relationship("Users", foreign_keys=user_id)
model = db.relationship("Documents", foreign_keys=model_id, viewonly=True)
csv = db.relationship("Documents", foreign_keys=csv_id, viewonly=True)

def __str__(self):
return (
Expand All @@ -105,6 +136,10 @@ def __str__(self):
+ str(self.ratio)
+ '" user_id="'
+ str(self.user_id)
+ '" model_id="'
+ str(self.model_id)
+ '" csv_id="'
+ str(self.csv_id)
+ '">'
)

Expand Down
12 changes: 5 additions & 7 deletions app/modules/authentications/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@

# Content mails import

# Create Blueprint & get logger
# Create Blueprint
authentications = Blueprint("authentications", __name__)
logger = LocalProxy(lambda: current_app.logger)


@authentications.before_request
Expand Down Expand Up @@ -124,7 +123,7 @@ def loginAuth():
identity=userIdentity, expires_delta=expires
)

response = jsonify({"token": access_token})
response = jsonify({"token": access_token, "firstname": user.firstname, "lastname": user.lastname})
response.status_code = 200
# add token to response headers - so SwaggerUI can use it
response.headers.extend({"jwt-token": access_token})
Expand Down Expand Up @@ -179,7 +178,6 @@ def getUserDatas():
"id_user": userDB.id,
"firstname": userDB.firstname,
"lastname": userDB.lastname,
"phone": userDB.phone,
}

return jsonify({"user": authUser}), 200
Expand Down Expand Up @@ -420,7 +418,7 @@ def create():
server = ServerSMTP()
sender = str(os.getenv("SMTP_SENDER"))
to = [str(newAuth.email)]
subject = "[Exo-Dev] Bienvenue dans le boilerplate !"
subject = "Bienvenue dans le projet Maquette!"
codage = "UTF-8"
typetext = "html"

Expand Down Expand Up @@ -529,7 +527,7 @@ def resetPassword():
server = ServerSMTP()
sender = str(os.getenv("SMTP_SENDER"))
to = [str(authDB.email)]
subject = "[Exo-Dev] Processus de réinitialisation de mot de passe"
subject = "Processus de réinitialisation de mot de passe"
codage = "UTF-8"
typetext = "html"

Expand Down Expand Up @@ -767,7 +765,7 @@ def resendMailsValidAccount(id):
server = ServerSMTP()
sender = str(os.getenv("SMTP_SENDER"))
to = [str(authentication.email)]
subject = "[Exo-Dev] Invitation à activer son compte"
subject = "Invitation à activer son compte"
codage = "UTF-8"
typetext = "html"

Expand Down
3 changes: 1 addition & 2 deletions app/modules/dataprocess/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@
debug_mode = environ.get("DEBUG_MODE")


# Create Blueprint & get logger
# Create Blueprint
dataprocess = Blueprint("dataprocess", __name__)
logger = LocalProxy(lambda: current_app.logger)


def voxelize(tempfile):
Expand Down
3 changes: 1 addition & 2 deletions app/modules/datas/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
data_schema = DatasSchema()
datas_schema = DatasSchema(many=True)

# Create Blueprint & get logger
# Create Blueprint
datas = Blueprint("datas", __name__)
logger = LocalProxy(lambda: current_app.logger)



Expand Down
Loading

0 comments on commit a2e6015

Please sign in to comment.