From 1b8c71945a9d20d6ec7465a413fe57fdbc162df5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20ARNAUDEAU?= Date: Fri, 24 Mar 2017 14:57:20 +0100 Subject: [PATCH] TG-124 : Modifications de la Base et adapation du code --- API_Interfaces.txt | 14 +------ backend/OLA.mysql | 56 ++++++++++++--------------- backend/OLA_DATA.mysql | 24 ++++++++++++ backend/app/api/GroupAPI.py | 69 +++++++++++++++++++++++++++++++--- backend/app/api/UserAPI.py | 45 +++++++++++----------- backend/app/api/mailsModels.py | 54 ++++++++++++++++++++++---- backend/app/config.py.example | 3 -- backend/app/core.py | 8 ++-- backend/app/model.py | 50 ++++++++++++++---------- backend/app/urls.py | 3 +- 10 files changed, 219 insertions(+), 107 deletions(-) create mode 100644 backend/OLA_DATA.mysql diff --git a/API_Interfaces.txt b/API_Interfaces.txt index 7c43cb5..241c148 100644 --- a/API_Interfaces.txt +++ b/API_Interfaces.txt @@ -20,29 +20,20 @@ GET -> Get the current logged user, return None if no one is connected Out: 200 -> USER = |null : Dictionary containing user infos or null - -######################## -Redirect to cas auth (/login) -######################## -Redirect to cas auth - - ######################## UserAPI (api/user) ######################## POST -> Create a user if it not already exists In: - CASid = Login of the user caught from the CAS authentication (must be unique) + email = Email and login of the user (must be unique) role = Role of the user (can be concatenated with -) 1=secrétaire, 2=resp_formation, 3=tuteur_univ, 4=étudiant Out: 200 -> UID = : The user already exists with the id USER_ID 201 -> UID = : The user has been successfully created with the id USER_ID 400 -> ERROR = "One or more parameters are missing" : Bad request - 405 -> ERROR = "A user with this email already exists !" : A user with this email already exists PUT -> Modify an existing user In: (Suffix = /byuid/) - CASid = Login of the user caught from the CAS authentication (must be unique) role = Role of the user (can be concatenated with -) 1=secrétaire, 2=resp_formation, 3=tuteur_univ, 4=étudiant phone = Phone number of the user (00.00.00.00.00) email = Email of the user (must be unique) @@ -50,11 +41,10 @@ PUT -> Modify an existing user 200 -> UID = : The user has been modified sucessfully with the id USER_ID 400 -> ERROR = "One or more parameters are missing !" : Bad request 405 -> ERROR = "This user doesn't exists !" : Bad USER_ID provided - 405 -> ERROR = "A user with this CASid (login) already exists !" : A user with this login already exists 405 -> ERROR = "A user with this email already exists !" : A user with this email already exists GET -> Getting specified user infos - In: (Suffixes = /byuid/ | /bylogin/ | /byemail/) + In: (Suffixes = /byuid/ | /byemail/) Out: 200 -> USER = |null : Dictionary containing user infos or null diff --git a/backend/OLA.mysql b/backend/OLA.mysql index 7958fb2..79529a8 100644 --- a/backend/OLA.mysql +++ b/backend/OLA.mysql @@ -37,11 +37,13 @@ CREATE TABLE IF NOT EXISTS `GROUP` CREATE TABLE IF NOT EXISTS `USER` ( - id BIGINT NOT NULL AUTO_INCREMENT, - `login` VARCHAR(128) NOT NULL, - `role` VARCHAR(10) NOT NULL, - email VARCHAR(256) NOT NULL, - phone VARCHAR(15), + id BIGINT NOT NULL AUTO_INCREMENT, + `role` VARCHAR(10) NOT NULL, + email VARCHAR(128) NOT NULL, + name VARCHAR(128) NOT NULL, + psw VARCHAR(256) DEFAULT NULL, + hash VARCHAR(128), + phone VARCHAR(15), PRIMARY KEY(id) ) ENGINE = INNODB; @@ -56,19 +58,17 @@ CREATE TABLE IF NOT EXISTS TUTORSHIP CREATE TABLE IF NOT EXISTS LIVRET ( - id BIGINT NOT NULL AUTO_INCREMENT, - tutorship_id BIGINT, - etutor_name VARCHAR(128) NOT NULL, - etutor_email VARCHAR(256) NOT NULL, - etutor_phone VARCHAR(15) NOT NULL, + id BIGINT NOT NULL AUTO_INCREMENT, + tutorship_id BIGINT NOT NULL, + etutor_id BIGINT NOT NULL, company_name VARCHAR(256) NOT NULL, company_address VARCHAR(512) NOT NULL, - contract_type INT NOT NULL, - contract_start DATE NOT NULL, - contract_end DATE NOT NULL, + contract_type INT NOT NULL, + contract_start DATE NOT NULL, + contract_end DATE NOT NULL, ressources_dir VARCHAR(512), - opened TINYINT(1) NOT NULL, - expire DATE NOT NULL, + opened TINYINT(1) NOT NULL, + expire DATE NOT NULL, PRIMARY KEY(id) ) ENGINE = INNODB; @@ -85,14 +85,6 @@ CREATE TABLE IF NOT EXISTS PERIOD PRIMARY KEY (id) ) ENGINE = INNODB; -CREATE TABLE IF NOT EXISTS HASHTABLE -( - token VARCHAR(255) NOT NULL, - exipre DATE NOT NULL, - period_id BIGINT NOT NULL, - PRIMARY KEY(token) -) ENGINE = INNODB; - # Create FKs ALTER TABLE `GROUP` @@ -127,6 +119,10 @@ REFERENCES TUTORSHIP (id) ON DELETE CASCADE ON UPDATE CASCADE ; + +ALTER TABLE LIVRET + ADD FOREIGN KEY (etutor_id) +REFERENCES `USER` (id); ALTER TABLE LIVRET ADD FOREIGN KEY (tutorship_id) @@ -140,14 +136,10 @@ ALTER TABLE PERIOD REFERENCES LIVRET (id) ON DELETE CASCADE ON UPDATE CASCADE; - -ALTER TABLE HASHTABLE - ADD FOREIGN KEY (period_id) -REFERENCES PERIOD (id) - ON DELETE CASCADE - ON UPDATE CASCADE -; + # Create Indexes -CREATE INDEX tutor_email ON LIVRET(etutor_email); -CREATE INDEX user_login ON `USER`(`login`); +CREATE UNIQUE INDEX user_email + ON `USER` (`email`); +CREATE UNIQUE INDEX user_hash + ON `USER` (`hash`); diff --git a/backend/OLA_DATA.mysql b/backend/OLA_DATA.mysql new file mode 100644 index 0000000..53b4cc0 --- /dev/null +++ b/backend/OLA_DATA.mysql @@ -0,0 +1,24 @@ +USE OLA; +INSERT INTO SETTINGS VALUES ('URL_BASE_DIRECTORY', '/OLA_RESSOURCES/', 'Répertoire base pour le dépot des fichiers'); +INSERT INTO SETTINGS VALUES ('OLA_URL', 'ola.univ-tlse2.fr/', 'URL de l application'); + +INSERT INTO `USER` VALUES (1, '1', 'sec@univ-tlse2.fr', 'Secrétaire', DEFAULT, 'aZeRtYuIoP', '01.23.45.67.89'); +INSERT INTO `USER` VALUES (2, '4', 'etu1@univ-tlse2.fr', 'Etudiant 1', DEFAULT, 'qSdFgHjKlM', '01.23.45.67.89'); +INSERT INTO `USER` VALUES (3, '4', 'etu2@univ-tlse2.fr', 'Etudiant 2', DEFAULT, 'wXcVbN', '01.23.45.67.89'); +INSERT INTO `USER` VALUES (4, '4', 'etu3@univ-tlse2.fr', 'Etudiant 3', DEFAULT, 'pOiUyTrEzA', '01.23.45.67.89'); +INSERT INTO `USER` VALUES (5, '2-3', 'resp@univ-tlse2.fr', 'Responsable', DEFAULT, 'mLkJhGfDsQ', '01.23.45.67.89'); +INSERT INTO `USER` VALUES (6, '3', 'tut@univ-tlse2.fr', 'Tuteur Pédagogique', DEFAULT, 'nBvCxW', '01.23.45.67.89'); + +INSERT INTO `GROUP` VALUES + (1, 'M2_ICE_2016-2017_TEST', '2017', 'Master2 ICE', 'Master 2 Informatique Collaborative en Entreprise', + 'Sciences du chômage proffessionnel', 5, 1, + '/home/dan/PycharmProjects/OLA/backend/app/OLA_RESSOURCES/M2_ICE_2016-2017_TEST'); +INSERT INTO `GROUP` VALUES + (2, 'M1_ICE_2016-2017_TEST', '2017', 'Master1 ICE', 'Master 1 Informatique Collaborative en Entreprise', + 'Sciences du chômage proffessionnel', 5, 1, + '/home/dan/PycharmProjects/OLA/backend/app/OLA_RESSOURCES/M1_ICE_2016-2017_TEST'); + +INSERT INTO TUTORSHIP VALUES (DEFAULT, 1, 5, 2); +INSERT INTO TUTORSHIP VALUES (DEFAULT, 2, 5, 4); +INSERT INTO TUTORSHIP VALUES (DEFAULT, 1, 6, 3); + diff --git a/backend/app/api/GroupAPI.py b/backend/app/api/GroupAPI.py index 631ce1d..8482acc 100644 --- a/backend/app/api/GroupAPI.py +++ b/backend/app/api/GroupAPI.py @@ -24,7 +24,7 @@ class GroupAPI(Resource): department = args['department'] resp_id = args['resp_id'] sec_id = args['sec_id'] - res_dir = app.config['BASE_RESSOURCES_DIR'] + name + "/" + res_dir = getParam('URL_BASE_DIRECTORY') + name + "/" group = getGroup(name=name) if group is not None: @@ -34,6 +34,18 @@ class GroupAPI(Resource): if user is None: return {"ERROR": "The user with id " + str(resp_id) + " does not exists !"}, 400 else: + query = USER.select(USER.c.id == user["id"]) + rows = query.execute() + res = rows.first() + if res.hash is not None and len(res.hash) > 0: + mail = mailsModels.getMailContent("NEW_RESP_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL') + "registration/" + + res.hash}) + else: + mail = mailsModels.getMailContent("RESP_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL')}) + + send_mail(mail[0], user["email"], mail[1]) if "2" not in user['role'].split('-'): role = user['role'] + "-2" query = USER.update().values(role=role).where(USER.c.id == resp_id) @@ -43,6 +55,18 @@ class GroupAPI(Resource): if user is None: return {"ERROR": "The user with id " + str(sec_id) + " does not exists !"}, 400 else: + query = USER.select(USER.c.id == user["id"]) + rows = query.execute() + res = rows.first() + if res.hash is not None and len(res.hash) > 0: + mail = mailsModels.getMailContent("NEW_SEC_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL') + "registration/" + + res.hash}) + else: + mail = mailsModels.getMailContent("SEC_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL')}) + + send_mail(mail[0], user["email"], mail[1]) if "1" not in user['role'].split('-'): role = user['role'] + "-1" query = USER.update().values(role=role).where(USER.c.id == sec_id) @@ -59,14 +83,14 @@ class GroupAPI(Resource): if not checkParams(['name', 'year', 'class_short', 'class_long', 'department', 'resp_id', 'sec_id'], args): return {"ERROR": "One or more parameters are missing !"}, 400 - name = args['name'] + name = args['name'].replace(" ", "_").replace("/", "-") year = args['year'] class_short = args['class_short'] class_long = args['class_long'] department = args['department'] resp_id = args['resp_id'] sec_id = args['sec_id'] - res_dir = app.config['BASE_RESSOURCES_DIR'] + name + "/" + res_dir = getParam('URL_BASE_DIRECTORY') + name + "/" group = getGroup(gid=gid) if group is None: @@ -80,6 +104,18 @@ class GroupAPI(Resource): if user is None: return {"ERROR": "The user with id " + str(resp_id) + " does not exists !"}, 400 else: + query = USER.select(USER.c.id == user["id"]) + rows = query.execute() + res = rows.first() + if res.hash is not None and len(res.hash) > 0: + mail = mailsModels.getMailContent("NEW_RESP_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL') + "registration/" + + res.hash}) + else: + mail = mailsModels.getMailContent("RESP_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL')}) + + send_mail(mail[0], user["email"], mail[1]) if "2" not in user['role'].split('-'): role = user['role'] + "-2" query = USER.update().values(role=role).where(USER.c.id == resp_id) @@ -89,6 +125,18 @@ class GroupAPI(Resource): if user is None: return {"ERROR": "The user with id " + str(sec_id) + " does not exists !"}, 400 else: + query = USER.select(USER.c.id == user["id"]) + rows = query.execute() + res = rows.first() + if res.hash is not None and len(res.hash) > 0: + mail = mailsModels.getMailContent("NEW_SEC_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL') + "registration/" + + res.hash}) + else: + mail = mailsModels.getMailContent("SEC_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL')}) + + send_mail(mail[0], user["email"], mail[1]) if "1" not in user['role'].split('-'): role = user['role'] + "-1" query = USER.update().values(role=role).where(USER.c.id == sec_id) @@ -143,9 +191,18 @@ class GroupAPI(Resource): query = TUTORSHIP.insert().values(group_id=gid, student_id=p[0], ptutor_id=p[1]) query.execute() - mail = mailsModels.getMailContent("NEW_TO_GROUP", {"GROUP": group["name"], - "URL": "ola.univ-tlse2.fr/registration/" - + get_random_string()}) + + query = USER.select(USER.c.id == stud["id"]) + rows = query.execute() + res = rows.first() + if res.hash is not None and len(res.hash) > 0: + mail = mailsModels.getMailContent("NEW_STUD_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL') + "registration/" + + res.hash}) + else: + mail = mailsModels.getMailContent("STUD_OF_GROUP", {"GROUP": group["name"], + "URL": getParam('OLA_URL')}) + send_mail(mail[0], stud["email"], mail[1]) return {"RESULT": "Pairs added successfully"}, 200 diff --git a/backend/app/api/UserAPI.py b/backend/app/api/UserAPI.py index 24369e5..7fb77f8 100644 --- a/backend/app/api/UserAPI.py +++ b/backend/app/api/UserAPI.py @@ -1,7 +1,9 @@ +from hashlib import sha256 + from flask_restful import Resource, request from app.model import * -from app.utils import checkParams +from app.utils import checkParams, get_random_string class UserAPI(Resource): @@ -11,55 +13,54 @@ class UserAPI(Resource): def post(self): args = request.get_json(cache=False, force=True) - if not checkParams(['CASid', 'role'], args): + if not checkParams(['role', 'email', 'name'], args): return {"ERROR": "One or more parameters are missing !"}, 400 - CASid = args['CASid'] role = args['role'] - email = self.getEmailFromCAS(CASid) + email = args['email'] + name = args['name'] phone = None - user = getUser(login=CASid) + user = getUser(email=email) + hashpass = get_random_string() + while hashExists(hashpass): + hashpass = get_random_string() + if user is not None: return {"UID": user["id"]}, 200 - if getUser(email=email) is not None: - return {"ERROR": "A user with this email (" + email + ") already exists !"}, 405 - - query = USER.insert().values(login=CASid, email=email, role=role, phone=phone) + query = USER.insert().values(email=email, role=role, phone=phone, name=name, hash=hashpass) res = query.execute() return {"UID": res.lastrowid}, 201 def put(self, uid): args = request.get_json(cache=False, force=True) - if not checkParams(['CASid', 'role', 'email', 'phone'], args): + if not checkParams(['role', 'email', 'phone', 'name', 'password'], args): return {"ERROR": "One or more parameters are missing !"}, 400 - CASid = args['CASid'] role = args['role'] email = args['email'] phone = args['phone'] + name = args['name'] + psw = args['password'] + + if psw is None or len(psw) < 8: + return {"ERROR": "Password can't be empty or less than 8 characters !"}, 400 + + password = sha256(psw).hexdigest() if getUser(uid=uid) is None: return {"ERROR": "This user doesn't exists !"}, 405 - if getUser(login=CASid) is not None: - return {"ERROR": "A user with this CASid (login) already exists !"}, 405 - if getUser(email=email) is not None: return {"ERROR": "A user with this email already exists !"}, 405 - query = USER.update().values(login=CASid, email=email, role=role, phone=phone).where(USER.c.id == uid) + query = USER.update().values(email=email, role=role, phone=phone, name=name, psw=password, hash=None) \ + .where(USER.c.id == uid) query.execute() return {"UID": uid}, 200 - def get(self, uid=0, login="", email=""): + def get(self, uid=0, email=""): if uid > 0: return {'USER': getUser(uid=uid)}, 200 - elif login != "": - return {'USER': getUser(login=login)}, 200 elif email != "": return {'USER': getUser(email=email)}, 200 - - @staticmethod - def getEmailFromCAS(CASid): - return CASid + "@ola.com" diff --git a/backend/app/api/mailsModels.py b/backend/app/api/mailsModels.py index 71a3ddb..8f8c2c3 100644 --- a/backend/app/api/mailsModels.py +++ b/backend/app/api/mailsModels.py @@ -1,13 +1,53 @@ -_NEW_USER = ("Votre compte OLA a été créé !", "Bonjour,

Votre compte vient d'être créé dans l'Outil du " - "Livret de l'Alternant dans le groupe #GROUPE. Vous pouvez dès " +_NEW_STUD_OF_GROUP = ("Votre compte OLA a été créé !", "Bonjour,

Votre compte vient d'être créé dans l'Outil du " + "Livret de l'Alternant dans le groupe #GROUPE. Vous pouvez dès " + "maintenant l'activer, puis créer un livret en vous rendant à l'adresse :
" + "#URL

Bonne journée !

") + +_STUD_OF_GROUP = ( +"Vous avez été ajouté à un groupe OLA !", "Bonjour,

Votre compte vient d'être ajouté dans l'Outil du " + "Livret de l'Alternant au groupe #GROUPE. Vous pouvez dès " "maintenant créer un livret en vous rendant à l'adresse :
" "#URL

Bonne journée !

") +_NEW_RESP_OF_GROUP = ("Votre compte OLA a été créé !", "Bonjour,

Votre compte vient d'être créé dans l'Outil du " + "Livret de l'Alternant en tant que responsable du groupe #GROUPE. Vous pouvez dès " + "maintenant l'activer, en vous rendant à l'adresse :
" + "#URL

Bonne journée !

") + +_RESP_OF_GROUP = ( +"Vous avez été ajouté à un groupe OLA !", "Bonjour,

Votre compte vient d'être ajouté dans l'Outil du " + "Livret de l'Alternant en tant que responsable du groupe #GROUPE. Vous pouvez dès " + "maintenant y accéder en vous rendant à l'adresse :
" + "#URL

Bonne journée !

") + +_NEW_SEC_OF_GROUP = ("Votre compte OLA a été créé !", "Bonjour,

Votre compte vient d'être créé dans l'Outil du " + "Livret de l'Alternant en tant que secrétaire du groupe #GROUPE. Vous pouvez dès " + "maintenant l'activer, en vous rendant à l'adresse :
" + "#URL

Bonne journée !

") + +_SEC_OF_GROUP = ( +"Vous avez été ajouté à un groupe OLA !", "Bonjour,

Votre compte vient d'être ajouté dans l'Outil du " + "Livret de l'Alternant en tant que secrétaire du groupe #GROUPE. Vous pouvez dès " + "maintenant y accéder en vous rendant à l'adresse :
" + "#URL

Bonne journée !

") + def getMailContent(mail_type, args): - mail = None - if mail_type == "NEW_USER": - mail = _NEW_USER - for key, value in args: - mail[1].replace("#" + key, value) + if mail_type == "NEW_STUD_OF_GROUP": + mail = _NEW_STUD_OF_GROUP + elif mail_type == "STUD_OF_GROUP": + mail = _STUD_OF_GROUP + elif mail_type == "NEW_RESP_OF_GROUP": + mail = _NEW_RESP_OF_GROUP + elif mail_type == "RESP_OF_GROUP": + mail = _RESP_OF_GROUP + elif mail_type == "NEW_SEC_OF_GROUP": + mail = _NEW_SEC_OF_GROUP + elif mail_type == "SEC_OF_GROUP": + mail = _SEC_OF_GROUP + else: + raise Exception("Unknown mail type !") + + for key, value in args: + mail[1].replace("#" + key, value) return mail diff --git a/backend/app/config.py.example b/backend/app/config.py.example index aa04823..bcc853d 100644 --- a/backend/app/config.py.example +++ b/backend/app/config.py.example @@ -31,7 +31,6 @@ class Config: CAS_LOGIN_ROUTE = "/login" CAS_LOGOUT_ROUTE = "/logout" CAS_VALIDATE_ROUTE = "/serviceValidate" - BASE_RESSOURCES_DIR = "/OLA_RESSOURCES/" MAILER = True @@ -44,7 +43,6 @@ class Debug(Config): DEBUG = True SESSION_COOKIE_SECURE = False SQLALCHEMY_DATABASE_URI = 'mysql://ola:XXX@localhost/OLA' - BASE_RESSOURCES_DIR = os.path.abspath(os.path.dirname(__file__))+"/OLA_RESSOURCES/" class Test(Config): @@ -52,5 +50,4 @@ class Test(Config): BASE_DIR = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_DATABASE_URI = \ 'sqlite:///' + os.path.join(BASE_DIR, '../test.db') - BASE_RESSOURCES_DIR = os.path.abspath(os.path.dirname(__file__))+"/OLA_RESSOURCES/" MAILER = False diff --git a/backend/app/core.py b/backend/app/core.py index 39dab01..2b1ac28 100644 --- a/backend/app/core.py +++ b/backend/app/core.py @@ -1,16 +1,16 @@ import importlib from datetime import timedelta -from flask_cas import CAS - -from app.config import Config from flask import Flask, session, redirect +from flask_cas import CAS from flask_restful import Api from flask_sqlalchemy import SQLAlchemy from sqlalchemy import MetaData from sqlalchemy import create_engine from sqlalchemy.ext.automap import automap_base +from app.config import Config + # initialization Flask app = Flask(__name__) app.config.from_object(Config.ACTIVE_CONFIG) @@ -20,6 +20,7 @@ app.permanent_session_lifetime = \ minutes=app.config['SESSION_VALIDITY_DURATION_WITHOUT_ACTIVITY_MIN'] ) + @app.before_request def before_request(): session.modified = True @@ -37,6 +38,7 @@ api = Api(app) # Cas Flask cas = CAS(app) + @app.route('/redirect') def after_login(): return redirect("/api/login") diff --git a/backend/app/model.py b/backend/app/model.py index 7923f50..8f405e4 100644 --- a/backend/app/model.py +++ b/backend/app/model.py @@ -1,11 +1,10 @@ from sqlalchemy import Table -from sqlalchemy import or_ +from sqlalchemy import and_ -from app.core import meta, db, Base +from app.core import meta, Base USER = Table('USER', meta, autoload=False) SETTINGS = Table('SETTINGS', meta, autoload=False) -HASHTABLE = Table('HASHTABLE', meta, autoload=False) GROUP = Table('GROUP', meta, autoload=False) TUTORSHIP = Table('TUTORSHIP', meta, autoload=False) PERIOD = Table('PERIOD', meta, autoload=False) @@ -13,17 +12,22 @@ LIVRET = Table('LIVRET', meta, autoload=False) user_class = Base.classes.USER settings_class = Base.classes.SETTINGS -hashtable_class = Base.classes.HASHTABLE group_class = Base.classes.GROUP tutorship_class = Base.classes.TUTORSHIP period_class = Base.classes.PERIOD livret_class = Base.classes.LIVRET -def getUser(uid=0, login="", email=""): +def getParam(key): + query = SETTINGS.select(SETTINGS.c.key == key) + rows = query.execute() + return rows.first().value + + +def getUser(uid=0, email=""): res = None - if uid == 0 and login == "" and email == "": + if uid == 0 and email == "": raise Exception("getUser must be called with one argument !") else: if uid != 0: @@ -31,34 +35,22 @@ def getUser(uid=0, login="", email=""): rows = query.execute() res = rows.first() - elif login != "": - query = USER.select(USER.c.login == login) - rows = query.execute() - res = rows.first() - elif email != "": query = USER.select(USER.c.email == email) rows = query.execute() res = rows.first() if res is not None: - return {"id": res.id, "login": res.login, "email": res.email, "role": res.role, "phone": res.phone} + return {"id": res.id, "email": res.email, "role": res.role, "phone": res.phone, "name": res.name} else: return None -def isUserAllowed(uid): - query = db.session.query(group_class, tutorship_class).join(tutorship_class) \ - .filter(or_(tutorship_class.student_id == uid, group_class.resp_id == uid)) - res = query.all() - return res is not None and len(res) > 0 - - def getGroup(gid=0, name=""): res = None if gid == 0 and name == "": - raise Exception("getUser must be called with one argument !") + raise Exception("getGroup must be called with one argument !") else: if gid != 0: query = GROUP.select(GROUP.c.id == gid) @@ -76,3 +68,21 @@ def getGroup(gid=0, name=""): "sec_id": getUser(uid=res.sec_id), "ressources_dir": res.ressources_dir} else: return None + + +def getTutorshipForStudent(gid, student): + query = TUTORSHIP.select(and_(TUTORSHIP.c.group_id == gid, TUTORSHIP.c.student_id == student)) + rows = query.execute() + res = rows.first() + if res is not None: + return {"id": res.id, "group_id": getGroup(gid=res.group_id), "student_id": getUser(uid=res.student_id), + "ptutor_id": getUser(uid=res.ptutor_id)} + else: + return None + + +def hashExists(test): + query = USER.select(USER.c.hash == test) + rows = query.execute() + res = rows.first() + return res is not None diff --git a/backend/app/urls.py b/backend/app/urls.py index 7c9afc6..d46618a 100644 --- a/backend/app/urls.py +++ b/backend/app/urls.py @@ -9,6 +9,5 @@ from app.core import api api.add_resource(SomeApi, '/api/someapi', '/api/someapi/') api.add_resource(LoginAPI, '/api/login') api.add_resource(UserInfoAPI, '/api/userInfo') -api.add_resource(UserAPI, '/api/user', '/api/user/byuid/', '/api/user/bylogin/', - '/api/user/byemail/') +api.add_resource(UserAPI, '/api/user', '/api/user/byuid/', '/api/user/byemail/') api.add_resource(GroupAPI, '/api/group', '/api/group/bygid/', '/api/group/byname/')