Beispiel #1
0
    def post(self):
        request_json = request.get_json(silent=True)
        username: str = request_json.get("username")
        password: str = request_json.get("password")

        # lookup by username
        if not username or not password:
            err_msg = "Please check the credentials."
            return {"message": err_msg}, 400
        if UserRepository.get(username):
            current_user = UserRepository.get(username)
        else:
            err_msg = f"User {username} doesn't exist"
            return {"message": err_msg}, 404

        if not current_user.get("active"):
            err_msg = "User was deleted. Please contact the admin."
            return {"message": err_msg}, 404

        if UserRepository.verify_hash(password, current_user.get("password")):
            access_token = create_access_token(identity=username)
            refresh_token = create_refresh_token(identity=username)
            msg = "Logged in as {}".format(current_user.get("username"))
            response = {
                "message": msg,
                "access_token": access_token,
                "refresh_token": refresh_token,
            }
            return response, 200
        else:
            return {"message": "Wrong password"}, 401
Beispiel #2
0
    def auth_wrapper(*args, **kwargs):
        try:
            auth_header = request.headers['Authorization']
            token = auth_header.split(' ')[1]
            id_info = id_token.verify_oauth2_token(token, requests.Request(),
                                                   config.GOOGLE_CLIENT_ID)
            oid = id_info["sub"]
            picture = id_info["picture"]
            name = id_info["name"]
            email = id_info["email"]
            user = UserRepository.get(oid)
            if user:
                user = UserRepository.update(oid, email, picture, name)
            else:
                user = UserRepository.create(oid, email, picture, name)

            if 'oid' in kwargs:
                if kwargs['oid'] != user.oid:
                    return render_error(
                        "You don't have right access to this page", 403)

            kwargs.update({'user': user})
            return method(*args, **kwargs)

        except Exception as exc:
            return render_error(str(exc), 401)
Beispiel #3
0
    def get():
        username = get_jwt_identity()
        user = UserRepository.get(username)
        if user is None:
            abort(400, msg="fatal error, not recognised user")

        if user.user_type == "admin":
            tasks = user.tasks
            tasks = [{
                "id":
                task.id,
                "name":
                task.name,
                "total":
                task.total,
                "assignees": [{
                    "name": job.user.name,
                    "id": job.user.id
                } for job in task.jobs],
            } for task in tasks]
            return tasks
        else:
            jobs = user.jobs
            tasks = [{
                "id": job.task.id,
                "name": job.task.name,
                "total": job.task.total
            } for job in jobs]
            return tasks
Beispiel #4
0
 def get(last_name, first_name):
     """
     Return an user key information based on his name
     ---
     tags:
       - user
     parameters:
       - name: last_name
         in: path
         type: string
         description: the last name of the user
       - name: first_name
         in: path
         type: string
         description: the last name of the user
     responses:
       200:
         description: The user's information were successfully retrieved
         schema:
           example:
             user:
               last_name: Doe
               first_name: John
               age: 30
     """
     user = UserRepository.get(last_name=last_name, first_name=first_name)
     return jsonify({'user': user.json})
Beispiel #5
0
    def post(name, task_file, mode):
        """ Create a task based on the uploaded file """
        username = get_jwt_identity()
        user = UserRepository.get(username)
        if user is None:
            abort(400, msg="fatal error, not recognised user")
        if user.user_type != "admin":
            abort(400, msg="only admin user can create task")

        if len(task_file) == 0:
            abort(400, msg="no task file specified")

        file = task_file[0]
        filename = secure_filename(file.filename)
        filename = os.path.splitext(os.path.basename(filename))[0]

        if not filename:
            abort(400, msg="invalid filename")

        file_path = os.path.join(TASK_DATA_PATH, filename + ".txt")
        file.save(file_path)

        if not TaskRepository.create(name, user, 0, file_path, mode):
            # os.remove(file_path)
            abort(400, msg="failed to create task")

        return {"msg": "successuflly created"}
Beispiel #6
0
    def test_update(self):
        """ The PUT on `/user` should update an user's info"""
        user = UserRepository.create(first_name="John", last_name="Doe")
        response = self.client.put(
            "/application/user/{}".format(user.id),
            content_type="application/json",
            data=json.dumps(
                dict(first_name="John",
                     last_name="Doe",
                     emails=["*****@*****.**"],
                     phone_numbers=["+491424324435"])),
        )

        self.assertEqual(response.status_code, 200)
        response_json = json.loads(response.data.decode("utf-8"))
        self.assertEqual(
            response_json,
            {
                "user":
                dict(user_id=user.id,
                     first_name="John",
                     last_name="Doe",
                     emails=["*****@*****.**"],
                     phone_numbers=["+491424324435"])
            },
        )
        user = UserRepository.get(user_id=user.id)
        self.assertEqual(user.first_name, "John")
Beispiel #7
0
    def put(self):
        request_json = request.get_json(silent=True)
        username = get_jwt_identity()

        if not request_json:
            err_msg = "Body should not be empty"
            return {"message": err_msg}, 400

        old_password: str = request_json.get('old_password')
        new_password: str = request_json.get('new_password')
        confirm_password: str = request_json.get('confirmation_password')

        if not old_password or not new_password or not confirm_password:
            err_msg = "Please check password fields."
            return {"message": err_msg}, 400

        current_user = UserRepository.get(username)
        current_password = current_user.get("password")

        if not current_password:
            err_msg = "Can't retrieve previous password."
            return {"message": err_msg}, 400
        if not UserRepository.verify_hash(old_password, current_password):
            err_msg = "Wrong old password value."
            return {"message": err_msg}, 400
        if new_password != confirm_password:
            err_msg = "New password doesn't match with confirmation password."
            return {"message": err_msg}, 400
        if not new_password:
            err_msg = "New password is empty. Update didn't pass"
            return {"message": err_msg}, 400

        user = UserRepository.update_password(username, new_password)
        return user, 200
Beispiel #8
0
 def get(username):
     """ Return an user key information based on his name """
     ensure_user(user_type="admin")
     user = UserRepository.get(username=username)
     if user is not None:
         return user.json
     else:
         abort(404, msg="User not found")
Beispiel #9
0
    def post(username, password, name, type):
        ensure_user(user_type="admin")
        if UserRepository.get(username) is not None:
            abort(400, msg="existing user")

        user = UserRepository.create(username, password, name, type)
        user_json = user.json
        del user_json["password"]
        return user_json, 200
Beispiel #10
0
    def get():
        username = get_jwt_identity()
        user = UserRepository.get(username)
        if user is None:
            abort(400, msg="fatal error, not recognised user")

        jobs = JobRepository.find_all_by_user(user)
        jobs = [{"task": job.task.name} for job in jobs]
        return jobs
Beispiel #11
0
    def get(taskId, idx):
        username = get_jwt_identity()
        user = UserRepository.get(username)
        if user is None:
            abort(400, msg="fatal error, not recognised user")

        task = TaskRepository.get(taskId)
        if task is None:
            abort(400, msg="Unknown task.")

        job = JobRepository.find(user, task)
        if job is None:
            abort(400, msg="Unknown job.")

        if os.path.exists(task.path):
            with open(task.path, "r") as f:
                sentences = f.readlines()

        idx = int(idx)
        if idx >= len(sentences):
            abort(400,
                  msg="Invalid index of sentence with the specified task.")

        sentence = sentences[idx]

        # if with_weight:
        # from class_service import ClassificationService
        from service.class_service import ClassificationService

        if True:
            words = sentence.strip().split()
            scores = ClassificationService.instance().word_score(words)
            words = [{
                "token": word,
                "weight": float(weight[1])
            } for word, weight in zip(words, scores)]
        else:
            words = [[{
                "token": w,
                "weight": 0
            } for w in s.strip().split()] for s in sentences]

        sentence_score = float(
            ClassificationService.instance().sent_score(sentence)[1])

        changes = []
        for history in job.historys:
            # print (history.sentence_id)
            # print (idx)
            # print (type(history.sentence_id))
            # print (type(idx))
            if history.sentence_id == idx:
                changes = json.loads(history.changes)
                break

        return {"words": words, "score": sentence_score, "changes": changes}
Beispiel #12
0
 def get(username):
     """ Return an user key information based on his name """
     m = UserRepository.get(username=username)
     d = {}
     d['username'] = m.username
     d['age'] = m.age
     d['films'] = []
     for l in m.notes : 
         d['films'].append(l.name)
     return(jsonify(d))          
Beispiel #13
0
def ensure_user(user_type=None):
    username = get_jwt_identity()
    user = UserRepository.get(username)
    if user is None:
        abort(400, msg="fatal error, not recognised user")

    if user_type and user.user_type != user_type:
        abort(400, msg="current user is not allowed to access")

    return user
Beispiel #14
0
    def post(self):
        request_json = request.get_json(silent=True)
        username: str = request_json["username"]
        password: str = request_json.get("password")
        # lookup by username
        if UserRepository.get(username):
            current_user = UserRepository.get(username)
        else:
            return {"message": "User {} doesn't exist".format(username)}, 404

        if UserRepository.verify_hash(password, current_user["password"]):
            access_token = create_access_token(identity=username)
            refresh_token = create_refresh_token(identity=username)
            return {
                "message": "Logged in as {}".format(current_user["username"]),
                "access_token": access_token,
                "refresh_token": refresh_token,
            }, 200
        else:
            return {"message": "Wrong password"}, 401
Beispiel #15
0
 def post(last_name, first_name, age):
     """ Create an user based on the sent information """
     existing_user = UserRepository.get(last_name=last_name,
                                        first_name=first_name)
     if existing_user:
         return bad_request('user already in database')
     user = UserRepository.create(last_name=last_name,
                                  first_name=first_name,
                                  age=age)
     if user:
         return jsonify({'user': user.json})
     return bad_request('unable to create user')
Beispiel #16
0
    def get(id, with_weight):
        """ Return a task key information based on task name """
        with_weight = bool(with_weight)

        username = get_jwt_identity()
        user = UserRepository.get(username)
        if user is None:
            abort(400, msg="fatal error, not recognised user")

        task = TaskRepository.get(id=id)
        if task is None:
            abort(400, msg="unknown task")

        if os.path.exists(task.path):
            with open(task.path, "r") as f:
                sentences = f.readlines()
        else:
            abort(400, msg='fatal error, task file does not exist.')

        if with_weight:
            print(with_weight, type(with_weight))
            # from class_service import ClassificationService
            from service.class_service import ClassificationService

            records = []
            for sent in sentences:
                words = sent.strip().split()
                scores = ClassificationService.instance().word_score(words)
                records.append([{
                    "token": word,
                    "weight": float(weight[1])
                } for word, weight in zip(words, scores)])
            words = records
        else:
            words = [[{
                "token": w,
                "weight": 0
            } for w in s.strip().split()] for s in sentences]

        if user.user_type == "admin":
            return {"data": words}
        else:
            job = JobRepository.find(user, task)
            if job is None:
                abort(400, msg="Unknown job.")
            annotated = [
                h.sentence_id for h in job.historys if len(h.changes) > 2
            ]
            annotation_status = [
                i in set(annotated) for i in range(len(words))
            ]
            return {"data": words, "annotation_status": annotation_status}
Beispiel #17
0
 def post(self):
     """
     Sign In
     """
     request_json = request.get_json(silent=True)
     name: str = request_json["username"]
     password: str = request_json["password"]
     try:
         user = UserRepository.get(name)
         if check_password_hash(user["password"], password):
             token = jwt.encode(
                 {
                     "id":
                     user["id"],
                     "username":
                     user["name"],
                     "exp":
                     datetime.datetime.utcnow() +
                     datetime.timedelta(minutes=30),
                 },
                 "SECRET",
             )
             response = {
                 "data": {
                     "user": user,
                     "csrf_token": token
                 },
                 "code": 200,
                 "messages": [{
                     "content": "Success",
                     "type": 4
                 }],
             }
             status_code = 200
             return response, status_code, {
                 "Content-Type": "json; charset=utf-8"
             }
         else:
             raise Exception
     except Exception as e:
         print(e)
         response = {
             "data": {},
             "code": 400,
             "messages": [{
                 "content": "Fail",
                 "type": 1
             }],
         }
         return response, 400, {"Content-Type": "json; charset=utf-8"}
Beispiel #18
0
    def test_update(self):
        """ The PUT on `/user` should update an user's age """
        UserRepository.create(first_name='John', last_name='Doe', age=25)
        response = self.client.put(
            '/application/user/Doe/John',
            content_type='application/json',
            data=json.dumps({
                'age': 30
            })
        )

        self.assertEqual(response.status_code, 200)
        response_json = json.loads(response.data.decode('utf-8'))
        self.assertEqual(response_json, {'user': {'age': 30, 'first_name': 'John', 'last_name': 'Doe'}})
        user = UserRepository.get(first_name='John', last_name='Doe')
        self.assertEqual(user.age, 30)
Beispiel #19
0
    def test_update(self):
        """ The PUT on `/user` should update an user's age """
        UserRepository.create(first_name="John", last_name="Doe", age=25)
        response = self.client.put(
            "/application/user/Doe/John",
            content_type="application/json",
            data=json.dumps({"age": 30}),
        )

        self.assertEqual(response.status_code, 200)
        response_json = json.loads(response.data.decode("utf-8"))
        self.assertEqual(
            response_json,
            {"user": {"age": 30, "first_name": "John", "last_name": "Doe"}},
        )
        user = UserRepository.get(first_name="John", last_name="Doe")
        self.assertEqual(user.age, 30)
Beispiel #20
0
    def get(id):
        username = get_jwt_identity()
        user = UserRepository.get(username)
        if user is None:
            abort(400, msg="fatal error, not recognised user.")

        job = JobRepository.get(id=id)
        if job is None:
            abort(400, msg="Unknown job.")

        job = {
            "id": job.id,
            "user_id": job.user.id,
            "task_id": job.task.id,
            "history": [h.changes for h in job.historys],
        }

        return job
Beispiel #21
0
    def get():
        """ Return an user key information based on his name """
        if 'Authorization' not in request.headers:
            return abort(403, description='Authorization header is missing!')
        authorization = request.headers['Authorization']
        _, enconded_auth = authorization.split(' ')
        username, hashed_password = base64.b64decode(enconded_auth).decode(
            "utf-8").split(':')
        try:
            user = UserRepository.get(username=username,
                                      hashed_password=hashed_password)
        except NoResultFound:
            abort(403, "Usuário não encontrado!")

        if not user:
            return abort(403,
                         description='Username or Password are incorrect!')

        access_token = create_access_token(identity=username)
        return jsonify({"access_token": access_token})
Beispiel #22
0
    def post(taskId, sentIdx, changes):
        username = get_jwt_identity()
        user = UserRepository.get(username)
        if user is None:
            abort(400, msg="fatal error, not recognised user.")

        task = TaskRepository.get(taskId)
        if task is None:
            abort(400, msg="fatal error, not recognised task.")

        job = JobRepository.find(user, task)
        if job is None:
            abort(400, msg="Unknown job.")

        # import pdb; pdb.set_trace();

        # collate the format, as somehow the parser mistakenly converts " to '
        # changes = changes.replace("'", "\'")
        changes = json.dumps(changes)
        JobRepository.push_history(job, sentIdx, changes)
        return {"msg": "Successfully added history to given job."}
Beispiel #23
0
 def get(id):
     """ Return an user key information based on his name """
     user = UserRepository.get(id=id)
     if user:
         return jsonify({"user": user.json})
     return {}, 404
 def get(oid, **_kwargs):
     """ Return an user key information based on his name """
     return render_resource(UserRepository.get(oid))
Beispiel #25
0
 def delete(user_id):
     """ Delete an user based on his id """
     user = UserRepository.get(user_id=user_id)
     return jsonify({"user": user.json})
Beispiel #26
0
 def get(user_id):
     """ Return an user key information based on his id """
     user = UserRepository.get(user_id=user_id)
     return jsonify({"user": user.json})
Beispiel #27
0
 def get(last_name, first_name):
     """ Return an user key information based on his name """
     user = UserRepository.get(last_name=last_name, first_name=first_name)
     return jsonify({'user': user.json})
Beispiel #28
0
 def get(self, email):
     """Get user by email"""
     item = UserRepository.get(email)
     if not item:
         abort(404, message='Item not found.')
     return item
    def post(answer_id, trivia_id, question_id, user, **_kwargs):
        """ Return an user key information based on his name """
        answer = SubmittedAnswer(
            answer_id=answer_id, trivia_id=trivia_id, user_id=user.oid, question_id=question_id
        ).save()
        trivia = Trivia.query.filter_by(id=trivia_id).one()
        achievement = AchievementRepository.get(trivia.achievement_id)

        if achievement:
            if len(trivia.submitted_answers) == len(achievement.questions):
                trivia.completed = True
                trivia.save()
                achieved = True

                for answer in trivia.submitted_answers:
                    if not answer.answer.is_right:
                        achieved = False
                        break

                if achieved:
                    user.achievements_rate = user.achievements_rate + 50
                    user.save()
                    try:
                        UserRepository.obtain(user, achievement)
                    except sqlalchemy.orm.exc.FlushError:
                        pass
        elif len(trivia.submitted_answers) == len(trivia.questions) * 2:
            trivia.completed = True
            trivia.save()

            players_score = {trivia.user_id: 0, trivia.second_player_id: 0}

            answers_checked = []

            for answer in trivia.submitted_answers:
                if answer.id in answers_checked:
                    continue
                for aanswer in trivia.submitted_answers:
                    if aanswer.id in answers_checked:
                        continue
                    if aanswer.id == answer.id:
                        continue
                    if aanswer.question_id != answer.question_id:
                        continue
                    if aanswer.answer.is_right and answer.answer.is_right:
                        if aanswer.created_at < answer.created_at:
                            players_score[aanswer.user_id] += 1
                        else:
                            players_score[answer.user_id] += 1
                    elif aanswer.answer.is_right:
                        players_score[aanswer.user_id] += 1
                    elif answer.answer.is_right:
                        players_score[answer.user_id] += 1

                    answers_checked.append(answer.id)
                    answers_checked.append(aanswer.id)

            first_player_id, first_player_score = players_score.popitem()
            second_player_id, second_player_score = players_score.popitem()

            if trivia.user_id != first_player_id:
                first_player_id, first_player_score, second_player_id, second_player_score = (
                    second_player_id, second_player_score, first_player_id, first_player_score
                )

            if first_player_score == second_player_score:
                user = UserRepository.get(first_player_id)
                user.trivia_rate = user.trivia_rate + 20
                user.save()

                user = UserRepository.get(second_player_id)
                user.trivia_rate = user.trivia_rate + 20
                user.save()

                trivia.first_player_score = 20
                trivia.second_player_score = 20
                trivia.save()
            elif first_player_score > second_player_score:
                user = UserRepository.get(first_player_id)
                user.trivia_rate = user.trivia_rate + 45
                user.save()

                trivia.first_player_score = 45
                trivia.second_player_score = 0
                trivia.save()
            else:
                user = UserRepository.get(second_player_id)
                user.trivia_rate = user.trivia_rate + 45
                user.save()

                trivia.first_player_score = 0
                trivia.second_player_score = 45
                trivia.save()

        return render_resource(answer)
Beispiel #30
0
 def get(self, username: str):
     user = UserRepository.get(username)
     return user, 200