Esempio n. 1
0
    def post(self):
        args = request.get_json(cache=False, force=True)
        if not checkParams(['email', 'password'], args):
            return {"ERROR": "One or more parameters are missing !"}, 400
        email = args['email']
        psw = args['password']
        password = sha256(psw.encode('utf-8')).hexdigest()

        if "user" in session and session["user"] is not None:
            return {'AUTH_RESULT': 'ALREADY_LOGGED'}, 201

        query = USER.select(USER.c.email == email)
        rows = query.execute()
        res = rows.first()

        if app.config['TESTING']:
            if res is not None and psw == email:
                user = getUser(uid=res.id)
                session['user'] = user
                return {'AUTH_RESULT': 'OK'}, 200
            else:
                session['user'] = None
                return {'AUTH_RESULT': 'AUTHENTICATION_FAILED'}, 401
        else:
            if res is not None and password != "" and password == res.psw:
                user = getUser(uid=res.id)
                session['user'] = user
                return {'AUTH_RESULT': 'OK'}, 200
            else:
                session['user'] = None
                return {'AUTH_RESULT': 'AUTHENTICATION_FAILED'}, 401
Esempio n. 2
0
    def test_login_logout(self):
        rv = self.login('*****@*****.**', '*****@*****.**')
        self.assertEqual(rv.status_code, 200, 'Login as admin Failed')

        rv = self.login('*****@*****.**', '*****@*****.**')
        self.assertEqual(rv.status_code, 201, 'Login as admin succeed but should have already been done')

        rv = self.getUserInfo()
        self.assertEqual(rv.status_code, 200, 'Getting user info failed')
        self.assertEqual({"id": getUser(login="******")["id"], "login": "******", "email": "*****@*****.**", "role": "4",
                          "phone": "00.00.00.00.00"}, json.loads(rv.data)['USER'], 'Invalid user info')

        rv = self.logout()
        self.assertEqual(rv.status_code, 200, 'Logout Failed')

        rv = self.login('*****@*****.**', '*****@*****.**')
        self.assertEqual(rv.status_code, 401, 'Authentication not failed for the invalid user!')

        rv = self.getUserInfo()
        self.assertEqual(rv.status_code, 200, 'Getting user info failed')
        self.assertIsNone(json.loads(rv.data)['USER'], 'User info should be None')

        rv = self.login('*****@*****.**', '*****@*****.**')
        self.assertEqual(rv.status_code, 401,
                         'Authenticationnot failed for the invalid password !')
Esempio n. 3
0
 def setUpClass(cls):
     if getUser(login="******") is None:
         query = USER.insert().values(login="******", email="*****@*****.**", role="4", phone="00.00.00.00.00")
         res = query.execute()
         cls.uid = res.lastrowid
         query = GROUP.insert().values(name="test", year="2017", class_long="classe toto", class_short="toto",
                                       department="plop", ressources_dir="/plop/toto", resp_id=cls.uid,
                                       sec_id=cls.uid)
         res = query.execute()
         cls.gid = res.lastrowid
         query = TUTORSHIP.insert().values(student_id=cls.uid, ptutor_id=cls.uid, group_id=cls.gid)
         res = query.execute()
         cls.tid = res.lastrowid
Esempio n. 4
0
    def options(self, gid):
        args = request.get_json(cache=False, force=True)
        if not checkParams(['pairs'], args):
            return {"ERROR": "One or more parameters are missing !"}, 400

        pairs = args["pairs"]

        group = getGroup(gid=gid)
        if group is None:
            return {"ERROR": "This group does not exists !"}, 405

        for p in pairs:
            try:
                stud = getUser(uid=p[0])
                if stud is None:
                    return {
                        "ERROR":
                        "The user with id " + str(p[0]) + " does not exists !"
                    }, 400
                elif stud['role'] != str(Roles.etudiant):
                    return {
                        "ERROR": "A student must have the 'student' role !"
                    }, 400

                tutor = getUser(uid=p[1])
                if tutor is None:
                    return {
                        "ERROR":
                        "The user with id " + str(p[1]) + " does not exists !"
                    }, 400
                elif tutor['role'] == str(Roles.etudiant):
                    return {"ERROR": "A student can't be a tutor !"}, 400
                elif "3" not in tutor['role'].split('-'):
                    role = tutor['role'] + "-" + str(Roles.tuteur_univ)
                    query = USER.update().values(role=role).where(
                        USER.c.id == p[1])
                    query.execute()
            except IndexError:
                return {"ERROR": "Pairs are incorrectly formed !"}, 409

            query = TUTORSHIP.insert().values(group_id=gid,
                                              student_id=p[0],
                                              ptutor_id=p[1])
            query.execute()

            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
Esempio n. 5
0
    def post(self):
        args = request.get_json(cache=False, force=True)
        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']
        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 = getParam('BASE_DIRECTORY') + name + "/"
        mails = []

        group = getGroup(name=name)
        if group is not None:
            return {"GID": group["id"]}, 200

        user = getUser(uid=resp_id)
        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": name,
                        "URL": getParam('OLA_URL') + "registration/" + res.hash
                    })
            else:
                mail = mailsModels.getMailContent("RESP_OF_GROUP", {
                    "GROUP": name,
                    "URL": getParam('OLA_URL')
                })

            mails.append((user["email"], mail))
            if str(Roles.resp_formation) not in user['role'].split('-'):
                role = user['role'] + "-" + str(Roles.resp_formation)
                query = USER.update().values(role=role).where(
                    USER.c.id == resp_id)
                query.execute()

        user = getUser(uid=sec_id)
        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": name,
                        "URL": getParam('OLA_URL') + "registration/" + res.hash
                    })
            else:
                mail = mailsModels.getMailContent("SEC_OF_GROUP", {
                    "GROUP": name,
                    "URL": getParam('OLA_URL')
                })

            mails.append((user["email"], mail))
            if str(Roles.secretaire) not in user['role'].split('-'):
                role = user['role'] + "-" + str(Roles.secretaire)
                query = USER.update().values(role=role).where(
                    USER.c.id == sec_id)
                query.execute()

        query = GROUP.insert().values(name=name,
                                      year=year,
                                      class_short=class_short,
                                      class_long=class_long,
                                      department=department,
                                      resp_id=resp_id,
                                      sec_id=sec_id,
                                      ressources_dir=res_dir)
        res = query.execute()
        os.mkdir(res_dir)

        for m in mails:
            addr = m[0]
            mail = m[1]
            send_mail(mail[0], addr, mail[1])

        return {"GID": res.lastrowid}, 201
Esempio n. 6
0
    def post(self):
        args = request.get_json(cache=False, force=True)
        if not checkParams([
                'group_id', 'etutor_id', 'company_name', 'company_address',
                'contract_type', 'contract_start', 'contract_end',
                'description'
        ], args):
            return {"ERROR": "One or more parameters are missing !"}, 400

        user = session.get("user")
        group_id = args['group_id']
        etutor_id = args['etutor_id']
        company_name = args['company_name']
        company_address = args['company_address']
        contract_type = int(args['contract_type'])
        contract_start = datetime.strptime(args['contract_start'], "%d-%m-%Y")
        contract_end = datetime.strptime(args['contract_end'], "%d-%m-%Y")
        description = args['description']
        mails = []

        group = getGroup(gid=group_id)
        if group is None:
            return {
                "ERROR":
                "This group with id " + str(group_id) + "does not exists !"
            }, 405

        tutorship = getTutorship(gid=group_id, student=user["id"])

        if tutorship is None:
            return {
                "ERROR":
                "The current student is not registered in the group" +
                str(group_id) + " !"
            }, 405

        tutorship_id = tutorship["id"]

        livret = getLivret(group_id=group_id, student_id=user["id"])
        if livret is not None:
            return {"LID": livret["id"]}, 200

        # On vérifie que l'utilisateur actuel a le droit de modifier ce livret
        if user["id"] != livret["tutorship_id"]["student_id"]:
            return {"ERROR": "UNAUTHORIZED"}, 401

        user2 = getUser(uid=etutor_id)
        if user2 is None:
            return {
                "ERROR":
                "The user with id " + str(etutor_id) + " does not exists !"
            }, 400
        else:
            query = USER.select(USER.c.id == user2["id"])
            rows = query.execute()
            res = rows.first()
            if res.hash is not None and len(res.hash) > 0:
                mail = mailsModels.getMailContent(
                    "NEW_ETUTOR_ADDED", {
                        "GROUPE": group["name"],
                        "URL": getParam('OLA_URL') + "registration/" + res.hash
                    })
            else:
                mail = mailsModels.getMailContent("ETUTOR_ADDED", {
                    "GROUPE": group["name"],
                    "URL": getParam('OLA_URL')
                })

            mails.append((user2["email"], mail))
            if str(Roles.tuteur_entreprise) not in user2['role'].split('-'):
                return {
                    "ERROR":
                    "The user with id " + str(etutor_id) +
                    " doesn't have the 'etutor' role (" +
                    str(Roles.tuteur_entreprise) + ") !"
                }, 400

        if contract_start > contract_end:
            return {
                "ERROR": "The contract start can't be after its end !"
            }, 400

        res_dir = group["ressources_dir"] + "/" + str(user['id']) + "/"
        expire = datetime.now() + timedelta(days=365)

        query = LIVRET.insert().values(tutorship_id=tutorship_id,
                                       etutor_id=etutor_id,
                                       company_name=company_name,
                                       company_address=company_address,
                                       contract_type=contract_type,
                                       contract_start=contract_start,
                                       contract_end=contract_end,
                                       description=description,
                                       ressources_dir=res_dir,
                                       opened='1',
                                       expire=expire)
        res = query.execute()
        os.mkdir(res_dir)

        for m in mails:
            addr = m[0]
            mail = m[1]
            send_mail(mail[0], addr, mail[1])

        return {"LID": res.lastrowid}, 201
Esempio n. 7
0
    def put(self, lid):
        args = request.get_json(cache=False, force=True)
        if not checkParams([
                'etutor_id', 'company_name', 'company_address',
                'contract_type', 'contract_start', 'contract_end',
                'description'
        ], args):
            return {"ERROR": "One or more parameters are missing !"}, 400

        etutor_id = args['etutor_id']
        company_name = args['company_name']
        company_address = args['company_address']
        contract_type = int(args['contract_type'])
        contract_start = datetime.strptime(args['contract_start'], "%d-%m-%Y")
        contract_end = datetime.strptime(args['contract_end'], "%d-%m-%Y")
        description = args['description']
        mails = []

        livret = getLivret(lid=lid)
        if livret is None:
            return {"ERROR": "This livret does not exists !"}, 405

        # On vérifie que l'utilisateur actuel a le droit de modifier ce livret
        user = session.get("user")
        if user["id"] != livret["tutorship_id"]["student_id"]:
            return {"ERROR": "UNAUTHORIZED"}, 401

        user = getUser(uid=etutor_id)
        if user is None:
            return {
                "ERROR":
                "The user with id " + str(etutor_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_ETUTOR_ADDED", {
                        "GROUPE": livret["tutorship_id"]["group_id"]["name"],
                        "URL": getParam('OLA_URL') + "registration/" + res.hash
                    })
            else:
                mail = mailsModels.getMailContent(
                    "ETUTOR_ADDED", {
                        "GROUPE": livret["tutorship_id"]["group_id"]["name"],
                        "URL": getParam('OLA_URL')
                    })

            mails.append((user["email"], mail))
            if str(Roles.tuteur_entreprise) not in user['role'].split('-'):
                return {
                    "ERROR":
                    "The user with id " + str(etutor_id) +
                    " doesn't have the 'etutor' role (" +
                    str(Roles.tuteur_entreprise) + ") !"
                }, 400

        if contract_start > contract_end:
            return {
                "ERROR": "The contract start can't be after its end !"
            }, 400

        query = LIVRET.update().values(etutor_id=etutor_id, company_name=company_name,
                                       company_address=company_address, contract_type=contract_type,
                                       contract_start=contract_start, contract_end=contract_end,
                                       description=description) \
            .where(LIVRET.c.id == lid)
        query.execute()

        for m in mails:
            addr = m[0]
            mail = m[1]
            send_mail(mail[0], addr, mail[1])

        return {"LID": lid}, 200
Esempio n. 8
0
    def post(self):
        args = request.get_json(cache=False, force=True)
        if not checkParams(['group_id', 'period_type', 'start', 'end'], args):
            return {"ERROR": "One or more parameters are missing !"}, 400

        group_id = args['group_id']
        period_type = args['period_type']
        start = datetime.strptime(args['start'], "%d-%m-%Y")
        end = datetime.strptime(args['end'], "%d-%m-%Y")

        # On vérifie que le groupe existe
        group = getGroup(gid=group_id)
        if group is None:
            return {
                "ERROR":
                "This group with id " + str(group_id) + "does not exists !"
            }, 405

        if start > end:
            return {
                "ERROR": "The period's start can't be after its end !"
            }, 400

        # On vérifie que l'utilisateur actuel a le droit de modifier ce groupe
        user = session.get("user")
        if user["id"] != group["resp_id"]:
            return {"ERROR": "UNAUTHORIZED"}, 401

        # On récupère tous les livrets de ce groupe
        query = select([LIVRET.c.id, TUTORSHIP.c.student_id]).where(
            and_(TUTORSHIP.c.id == LIVRET.c.tutorship_id,
                 TUTORSHIP.c.group_id == group_id))
        res = query.execute()

        # Pour chaque livret du groupe on ajoute la période et on prévient l'étudiant
        for row in res:
            # On crée un répertoire avec un nom aléatoire
            res_dir = group["ressources_dir"] + "/" + str(
                row.student_id) + "/" + get_random_string() + "/"
            while os.path.exists(res_dir):
                res_dir = group["ressources_dir"] + "/" + str(
                    row.student_id) + "/" + get_random_string() + "/"

            # Enregistrement des infos en base
            query = PERIOD.insert().values(livret_id=row.id,
                                           type=period_type,
                                           start=start,
                                           end=end,
                                           ressources_dir=res_dir)
            query.execute()
            os.mkdir(res_dir)

            # Envoi d'un mail
            mail = mailsModels.getMailContent(
                "NEW_PERIOD", {
                    "GROUPE": group["name"],
                    "URL": getParam('OLA_URL') + "mon_livret"
                })
            send_mail(mail[0], getUser(row.student_id)["email"], mail[1])

        return {"RESULT": "OK"}, 201