Esempio n. 1
0
def get_results(teacher_id):

    student_id = current_user_id()
    results = Result.query.filter(Result.student_id == student_id,
                                  Result.teacher_id == teacher_id).all()
    formatted_results = [result.format() for result in results]
    return jsonify({'results': formatted_results})
Esempio n. 2
0
def get_students():
    teacher_id = current_user_id()
    teacher = Teacher.query.get(teacher_id)
    students = teacher.students
    current_students = paginate_entities(request, students)

    return jsonify({'students': current_students})
Esempio n. 3
0
def make_log_string(r_data, code):

    """
    Логируем запрос, создаем запись в базу
    """

    r_uid = current_user_id()
    
    r_addr = flask.request.environ['REMOTE_ADDR']
    r_uri = flask.request.environ['REQUEST_URI']
    r_time = str(datetime.now())
    
    record_string = f"""
    ===========================
        Request info: 
        time: {r_time} 
        remote address: {r_addr}
        uri: {r_uri}
        user id: {r_uid}
        data: {r_data}
        host response: {code}
    ===========================    
    """

    Record.create_record(
        app=current_app,
        db=db,
        record_uri=r_uri,
        user_id=r_uid,
    )

    return record_string
Esempio n. 4
0
def setStats():
    data = request.get_json(force=True)
    reps = data.get("reps")
    calories = data.get("calories")
    sent_date = data.get("date")[0:10]  # Gets YYYY-MM-DD
    workout = Workout(reps=reps,
                      calories=calories,
                      user_id=current_user_id(),
                      timestamp=int(time.time()))
    activity_dates = current_user().activity_dates
    print(activity_dates)
    if len(current_user().activity_dates) != 0:
        last_exercised_date = \
            sorted([date(int(x[0:4]), int(x[5:7]), int(x[8:])) for x in current_user().activity_dates])[-1]

        if (date(int(sent_date[0:4]), int(sent_date[5:7]), int(sent_date[8:]))
                - last_exercised_date).days == 1:
            current_user().streak += 1
        elif (date(int(sent_date[0:4]), int(sent_date[5:7]), int(
                sent_date[8:])) - last_exercised_date).days > 1:
            current_user().streak = 1
    else:
        current_user().streak = 1

    activity_dates.add(sent_date)
    current_user().activity_dates = activity_dates
    db.session.add(workout)
    db.session.commit()

    return jsonify({
        'message': 'Workout added successfully',
        'successful': True
    })
Esempio n. 5
0
def delete_authenticator(id):
    authenticator = Authenticator.query.filter_by(
        id=id, user_id=current_user_id()
    ).first_or_404()

    db.session.delete(authenticator)
    db.session.commit()
    return "", 204
Esempio n. 6
0
def delete_like_beach():
    """Delete a like on beach"""
    req = request.get_json(force=True)
    beach_id = req["beach_id"]
    user_id = flask_praetorian.current_user_id()
    try:
        db.session.query(Likes).filter_by(beach_id=beach_id,
                                          user_id=user_id).delete()
        db.session.commit()
    except Exception as e:
        return {"Error", str(e)}, 500
    return jsonify(f"Like with id {beach_id} deleted success"), 200
Esempio n. 7
0
def get_resultes(student_id):

    teacher_id = current_user_id()
    current_student = Student.query.get(int(student_id))
    if current_student == None:
        abort(404)
    student_results = Result.query.filter_by(student_id=student_id,
                                             teacher_id=teacher_id).all()
    formatted_results = [result.format() for result in student_results]
    return jsonify({
        "student_results": formatted_results,
        "student_data": current_student.format2()
    })
Esempio n. 8
0
def gen_blog():
    user_id = flask_praetorian.current_user_id()

    if request.method == 'GET':
        pass

    elif request.method == 'PATCH':
        data = request.get_json()
        Post.update_batch(data)

    elif request.method == 'POST':
        Post.new(user_id)

    return jsonify(Post.get_all_private())
Esempio n. 9
0
def add_comment():
    """ Send a commentary to one beach"""
    req = request.get_json(force=True)
    beach_id = req["beach_id"]
    comment = req["comment"]
    user_id = flask_praetorian.current_user_id()
    try:
        db.session.add(
            Comments(comment=comment, user_id=user_id, beach_id=beach_id))
        db.session.commit()
    except Exception as e:
        return {"Error": str(e)}, 500
    comment_id = db.session.query(Comments.id).filter_by(
        user_id=user_id, beach_id=beach_id).first()
    return {"message": f"comment with id {comment_id} post correctly"}, 200
Esempio n. 10
0
def delete_like_comment():
    try:
        req = request.get_json(force=True)
        comment_id = req["comment_id"]
        user_id = flask_praetorian.current_user_id()
        try:
            db.session.query(LikesOfComment).filter_by(
                comment_id=comment_id, user_id=user_id).delete()
            db.session.commit()
        except:
            return {"Error": "Something was wrong with the delete"}, 500

        return {"message": f"Like with id {comment_id} deleted success"}, 200
    except Exception as e:
        return {"Error": str(e)}
Esempio n. 11
0
def add_like_comment():
    """Add like on a comment"""
    req = request.get_json(force=True)
    comment_id = req["comment_id"]
    user_id = flask_praetorian.current_user_id()

    if db.session.query(LikesOfComment).filter_by(
            user_id=user_id, comment_id=comment_id).count() > 0:
        return jsonify("comment already exists"), 500

    try:
        db.session.add(LikesOfComment(user_id=user_id, comment_id=comment_id))
        db.session.commit()
    except Exception as e:
        return {"Error", str(e)}, 500
    like_on_comment_id = db.session.query(LikesOfComment.id).filter_by(
        comment_id=comment_id, user_id=user_id).first()
    return {"message": f"Like with id {like_on_comment_id} added success"}, 200
Esempio n. 12
0
def get_profile_favorites_beaches(type: int):
    """
    Get user likes beaches if type == 0 return favorite beaches else most comments beaches"""
    try:
        user_id = flask_praetorian.current_user_id()
        if int(type) == 0:
            beaches_id = db.session.query(Likes.beach_id).filter_by(user_id=user_id).all()
        elif int(type) == 1:
            beaches_id = db.session.query(Comments.beach_id).filter_by(user_id=user_id).all()
        else:
            return {"Error":"not supported option"}, 410

        ids = [row[0] for row in beaches_id]
        beaches = db.session.query(Beach).filter(Beach.id.in_(ids)).all()
        return jsonify([beach.convert_to_json() for beach in beaches]), 200

    except Exception as e:
        return {"Error": str(e)}
Esempio n. 13
0
def add_like_beach():
    """Add beach like"""
    req = request.get_json(force=True)
    beach_id = req["beach_id"]
    user_id = flask_praetorian.current_user_id()

    if db.session.query(Likes).filter_by(user_id=user_id,
                                         beach_id=beach_id).count() > 0:
        return {"Error": "Comment already exists"}, 500

    try:
        db.session.add(Likes(user_id=user_id, beach_id=beach_id))
        db.session.commit()
    except Exception as e:
        return {"Error", str(e)}, 500

    new_like_id = db.session.query(Likes.id).filter_by(
        user_id=user_id, beach_id=beach_id).first()
    return jsonify(f"Like with id {new_like_id} added correctly"), 200
Esempio n. 14
0
def sp_blog(id):
    user_id = flask_praetorian.current_user_id()

    if request.method == 'GET':
        return Post.get_by_id(id)

    elif request.method == 'PUT':
        # must return the saved object
        data = request.get_json()
        new_Post = Post.update_by_id(id, data)
        return new_Post

    elif request.method == 'POST':
        Post.new_by_order(id, user_id)

    elif request.method == 'DELETE':
        Post.delete(id)

    return jsonify(Post.get_all_private())
Esempio n. 15
0
def register():
    claims = current_custom_claims()
    if not claims.get("is_registration", False):
        return "", 401

    data = RegisterSchema().load(request.get_json())

    response = webauthn.WebAuthnRegistrationResponse(
        rp_id=app.config["WEBAUTHN_RP_ID"],
        origin=app.config["WEBAUTHN_ORIGIN"],
        registration_response=data,
        challenge=claims["challenge"],
        none_attestation_permitted=True,
    )

    try:
        credential = response.verify()
    except Exception as exc:
        return {"error": str(exc)}, 400

    user = User(
        id=UUID(current_user_id()), email=claims["email"], name=claims["name"],
    )

    authenticator = Authenticator(
        name=data["name"],
        credential_id=str(credential.credential_id, "utf-8"),
        public_key=str(credential.public_key, "utf-8"),
        sign_count=credential.sign_count,
    )

    user.authenticators = [authenticator]
    db.session.add(user)

    try:
        db.session.commit()
    except IntegrityError:
        return "", 409

    return "", 201
Esempio n. 16
0
def get_teachers():

    student_id = current_user_id()
    student = Student.query.get(int(student_id))
    teachers = student.teachers
    active_exams = student.exams
    formatted_exams = []
    if len(active_exams) != 0:
        formatted_exams += [exam.format3() for exam in active_exams]

    if len(teachers) == 0:
        raise CustomError(
            {
                "message": "Not Found",
                "description": "This student dosn't have any teachers!"
            }, 404)

    formmated_teachers = [teacher.format() for teacher in teachers]
    return jsonify({
        "current_student": student.format(),
        "student_teachers": formmated_teachers,
        "active_exams": formatted_exams
    })
Esempio n. 17
0
def submit_exam(exam_id):

    data = request.get_json()
    grade = data.get('grade')
    student_id = current_user_id()

    current_exam = Exam.query.get(int(exam_id))
    if current_exam == None:
        abort(404)

    teacher = current_exam.exam_owner
    current_student = Student.query.get(int(student_id))

    result = Result.query.filter_by(exam_id=exam_id,
                                    student_id=student_id).one_or_none()
    if result == None:
        abort(404)

    result.title = current_exam.title
    result.start_date = current_exam.start_date
    result.student_grade = grade
    result.total_grade = current_exam.total_grade
    result.teacher = teacher
    result.update()

    room = ExamRoom.query.filter_by(student_id=student_id,
                                    exam_id=exam_id).one_or_none()
    room.delete()
    if current_student.exams_num == 1:
        current_student.exams_num = 0
        current_student.has_exam = False
    else:
        current_student.exams_num -= 1
    current_student.update()

    return 'Your data has been submited successfully!'
Esempio n. 18
0
def list_authenticators():
    schema = AuthenticatorSchema()
    authenticators = Authenticator.query.filter(
        Authenticator.user_id == UUID(current_user_id())
    ).order_by(Authenticator.created_at)
    return jsonify(schema.dump(authenticators, many=True)), 200