Пример #1
0
def get_review():
    if flask_praetorian.current_user().username is not None:
        userid = db.session.query(Reviews).filter(
            Reviews.username ==
            flask_praetorian.current_user().username).with_entities(
                Reviews.userid).first()
        if request.method == 'GET':
            revs = []
            for review in db.session.query(Reviews).filter(
                    Reviews.userid == userid).with_entities(
                        Reviews.rating, Reviews.business_id, Reviews.text,
                        Reviews.reviewid):
                print(review)
                rating, business_id, text, review_id = review
                revs.append({
                    'rating': rating,
                    'business_id': business_id,
                    'text': text,
                    'review_id': review_id
                })
            print(revs)
            #     revs.append(review.__dict__)
            # print(revs)
            # print(json.dumps(revs))
            return jsonify(revs)
Пример #2
0
    def post(self):
        """Create a organization"""
        req = request.get_json(force=True)
        u = current_user()
        try:
            org = models.Organization(name=req['name'])
            db.session.add(org)
        except KeyError:
            api.abort(400, "Required field not present")

        try:
            db.session.commit()
        except:
            db.session.rollback()
            api.abort(500, "Failed to commit to database")

        for r in org.org_roles:
            if r.type == "admin":
                r.users.append(current_user())

                try:
                    db.session.commit()
                except:
                    db.session.rollback()
                    api.abort(500, "failed to add user to role")

        return org
def update_goal():
    goal_data = request.json
    month, year, goal = extract_integers(goal_data, ["month", "year", "goal"])

    validate_goal(month, year, goal)

    reader_goal = ReaderGoal.query.filter_by(
        month=month, year=year, reader_id=flask_praetorian.current_user().id
    ).first()

    if reader_goal:
        # We are overwriting an existing goal
        reader_goal.goal = goal

        db.session.add(reader_goal)
        db.session.commit()

        return jsonify(goal_schema.dump(reader_goal))
    else:
        # We are creating a new goal
        new_goal = ReaderGoal(
            month=month,
            year=year,
            reader_id=flask_praetorian.current_user().id,
            goal=goal,
        )

        db.session.add(new_goal)
        db.session.commit()

        return jsonify(goal_schema.dump(new_goal))
    def post(self):
        """Create a tournament"""
        req = request.get_json(force=True)
        u = current_user()
        try:
            f = models.Tournament(name=req['name'])
            db.session.add(f)
        except KeyError:
            api.abort(400, "Required field not present")

        try:
            db.session.commit()
        except:
            db.session.rollback()
            api.abort(500, "Failed to commit to database")

        for r in f.roles:
            if r.type == "overlord":
                r.users.append(current_user())

                try:
                    db.session.commit()
                except:
                    db.session.rollback()
                    api.abort(500, "failed to add user to role")

        return f
Пример #5
0
def create_chat():
    req = request.get_json(force=True)
    sender_public_key = current_user().public_key
    username = current_user().username
    user_id = current_user().id

    sk_sym_1 = req.get("sk_sym_1", "")
    sk_sym_2 = req.get("sk_sym_2", "")
    receiver_username = req.get("receiver_username", "")
    receiver_public_key = req.get("receiver_public_key", "")

    # Safety check
    if ((len(username) > 32) or (len(receiver_username) > 32)
            or (len(sk_sym_1) > 500) or (len(sk_sym_2) > 500)):
        return jsonify(error="Unable to create chat.")
    if "" in [sk_sym_1, sk_sym_2, receiver_username, receiver_public_key]:
        return jsonify(error="Unable to create chat.")
    if receiver_username == username:
        return jsonify(error="Can not create a chat with yourself.")
    receiver = models.find_user_by_name(receiver_username)
    if (receiver is None) or (receiver.public_key != receiver_public_key):
        return jsonify(error="Unexpected error.")
    # Check if such a chat already exists
    existing_chat_id = models.find_chat_by_users(user_id, receiver.id)
    if existing_chat_id is not None:
        return jsonify(chat_id=existing_chat_id)
    # Chat does not already exist; must create new chat
    chat_id = models.create_chat(user_id, username, sk_sym_1, receiver.id,
                                 receiver.username, sk_sym_2)
    # Safety check
    if chat_id is None:
        return jsonify(error="Unable to create chat.")
    return jsonify(chat_id=chat_id)
Пример #6
0
    def post(self, id):
        """ Updates a User """
        if (flask_praetorian.current_user().id == id
                or 'admin' in flask_praetorian.current_user().roles):
            update_dict = {}
            req = request.get_json(force=True)
            for param in list(req.keys()):
                if "username" in param:
                    # Don't allow username change to an existing username
                    name_check = User.query.filter_by(
                        username=req.get(param)).first()
                    if name_check:
                        return 'User Already Exists', 409
                if "password" in param:
                    update_dict[param] = guard.encrypt_password(req.get(param))
                else:
                    update_dict[param] = req.get(param)

                User.query.filter_by(id=id).update(update_dict)

                db.session.commit()

            user = User.query.filter_by(id=id).first()

            resp = jsonify(user.as_dict())
            resp.status_code = 200
            return resp

        else:
            return 'UNAUTHORIZED', 401
Пример #7
0
def chat(id):
    username = current_user().username
    user_id = current_user().id
    # Check that this chat exists and user is valid participant
    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Chat not found"), 404)
    chat_id = chat.id
    active_chats[user_id] = chat_id

    # Get the 'other' user in the chat
    other_userid = chat.user1_id
    other_username = chat.user1_name
    encrypted_symmetric_key = chat.user2_sk_sym
    if user_id == chat.user1_id:
        other_userid = chat.user2_id
        other_username = chat.user2_name
        encrypted_symmetric_key = chat.user1_sk_sym
    # Get messages for this chat and render the chat view
    messages = [message.to_dict() for message in models.get_chat_messages(id)]
    return jsonify(
        chat_id=chat_id,
        enc_sym_key=encrypted_symmetric_key,
        messages=messages,
        user_id=user_id,
        username=username,
        other_user=other_username,
    )
Пример #8
0
    def delete(self, id):
        """ Delete a User """
        if (flask_praetorian.current_user().id == id
                or 'admin' in flask_praetorian.current_user().roles):
            User.query.filter_by(id=id).delete()
            db.session.commit()
            return 'User Deleted', 204

        return 'UNAUTHORIZED', 401
Пример #9
0
def jobPostings():
    user_id = flask_praetorian.current_user().identity
    if request.method == 'GET' and user_id:
        if (flask_praetorian.current_user().rolenames[0] == 'recruiter'):
            return JobPostingHandler().getJobPostingsByUserId(user_id)
        else:
            view = JobPostingHandler().getAllJobPostings()
            return view
    else:
        return jsonify(Error="Method not allowed"), 405
Пример #10
0
def reauth_user():
    if current_user():
        user = User.query.get(current_user().id)
        token = guard.read_token_from_header()
        try:
            new_token = guard.refresh_jwt_token(token)
            return jsonify({'username': user.username, 'id': user.id, 'token': new_token})
        except:
            pass
        return jsonify({'user': {'username': user.username, 'id': user.id}, 'token': token})
Пример #11
0
def protected():
    """
    A protected endpoint. The auth_required decorator will require a header
    containing a valid JWT
    .. example::
       $ curl http://localhost:5000/api/protected -X GET \
         -H "Authorization: Bearer <your_token>"
    """
    return {
        'User': flask_praetorian.current_user().username,
        'Roles': flask_praetorian.current_user().rolenames
    }
Пример #12
0
 def delete(self, product_id):
     """
     Delete product
     """
     product = Product.query.get(product_id)
     if not product:
         abort(404, message='Product not found')
     if product.owner_id != flask_praetorian.current_user().user_id and \
             flask_praetorian.current_user().role != 'admin':
         abort(400, message='You are not owner of this product')
     db.session.delete(product)
     db.session.commit()
Пример #13
0
def favorite():
    if flask_praetorian.current_user().username is not None:
        # userid = user_id(flask_praetorian.current_user().username)
        # userid = my_random_string(flask_praetorian.current_user().username)
        userid = db.session.query(User).filter(
            User.username ==
            flask_praetorian.current_user().username).with_entities(
                User.id).first()
        userid = userid[0]

        # Should query from User table instead
        # Apply a hashed username to

        if request.method == 'POST':
            req = request.get_json(force=True)

            business_id = req.get('businessid', None)
            option = req.get('addFavorite', None)

            if option == 'add':
                if db.session.query(Favorites).filter(
                        Favorites.userid == userid,
                        Favorites.business_id == business_id).count() == 0:
                    data = Favorites(userid, business_id)
                    db.session.add(data)
                    db.session.commit()

                    return {'Status': 'Success'}
                else:
                    return {'Status': 'Failed'}
            else:
                if db.session.query(Favorites).filter(
                        Favorites.userid == userid, Favorites.business_id
                        == business_id).count() != 0:
                    db.session.delete(
                        db.session.query(Favorites).filter(
                            Favorites.userid == userid,
                            Favorites.business_id == business_id).first())
                    db.session.commit()
                    return {'Status': 'Success'}
                else:
                    return {'Status': 'Failed'}
        else:
            business_id = request.args.get('business_id')

            if db.session.query(Favorites).filter(
                    Favorites.userid == userid,
                    Favorites.business_id == business_id).count() == 0:
                return json.dumps({'Status': 'Success', 'favorite': False})
            else:
                return json.dumps({'Status': 'Success', 'favorite': True})
    else:
        return {'Status': 'Failed'}
Пример #14
0
 def post(self, product_id):
     product = Product.query.get_or_404(product_id)
     existing_upvote = ProductUpvote.query.filter_by(product_id=product.id,
                                                     user_id=flask_praetorian.current_user().id).first()
     if existing_upvote:
         product.upvotes_count = Product.upvotes_count - 1
         db.session.delete(existing_upvote)
     else:
         product_upvote = ProductUpvote(
             product_id=product.id, user_id=flask_praetorian.current_user().id)
         product.upvotes_count = Product.upvotes_count + 1
         db.session.add(product_upvote)
     db.session.commit()
     return {"hello": "world"}
Пример #15
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
    })
Пример #16
0
    def delete(self, id):
        """ Delete a Scrimmage """
        # If I am an admin, OR one of the presenters, I can delete
        user_id = flask_praetorian.current_user().id
        user = User.query.filter_by(id=user_id).first()
        scrimmage = Scrimmage.query.filter_by(id=id).first()

        if (user in scrimmage.presenters
                or 'admin' in flask_praetorian.current_user().roles):
            Scrimmage.query.filter_by(id=id).delete()
            db.session.commit()
            return 'Scrimmage Deleted', 204

        return 'UNAUTHORIZED', 401
Пример #17
0
 def put(self):
     """Updates current user profile info"""
     logger.info("UserProfile.put() user_id: %s", str(current_user().id))
     try:
         user_id = current_user().id
         content = json.loads(request.form['data'])
         photo = request.files.get('photo', None)
         photo_url = cloudinary_uploader.upload(
             photo)['url'] if photo else None
         User.update_user_profile_info(user_id, content, photo_url)
         return 'User profile info has been updated', 200
     except Exception as e:
         logger.exception("UserProfile.put(): %s", str(e))
         return "Couldn't update user profile info", 500
Пример #18
0
def applications():
    user_id = flask_praetorian.current_user().identity
    if request.method == 'GET' and user_id:
        application = ApplicationsHandler().getApplicationsByUserId(user_id)
        return application
    else:
        return jsonify(Error="Method not allowed"), 405
Пример #19
0
def delete_chat(id):
    user_id = current_user().id
    chat = models.get_chat(id)
    if not chat or (user_id != chat.user1_id and user_id != chat.user2_id):
        return make_response(jsonify(error="Chat not found"), 404)
    models.delete_chat(id)
    return jsonify(success=f"Chat {id} deleted successfully")
Пример #20
0
    def patch(self, id):
        """
        Patch a Favourite by id
        """
        req = api.payload

        favourite = Favourite.query.filter_by(id=id).first()
        if favourite is None:
            return { 'message': 'Favourite does not exist'}, 404

        # Check User permission
        current_user = flask_praetorian.current_user()
        if favourite.user_id != current_user.id:
            return { 'message': 'Unauthorized to edit Favourite'}, 401
            
        # Validate        
        try:
            edit_favourite = favourite_patch_schema.load(req)
        except ValidationError as err:
            return { 'error': err.messages }

        try:
            db.session.commit()
        except Exception:
            return { 'message': 'Unable to edit Favourite'}, 500

        return { 'message': 'Favourite updated successfully' }
Пример #21
0
    def post(self, id):
        post = Post.query.get(id)

        data = marshal(request.get_json(), new_comment_marshal_model)
        content = data['content']

        content = bleach.clean(
            content,
            tags=[
                'p',
                'h1',
                'h2',
                'br',
                's',
                'u',
                *bleach.sanitizer.ALLOWED_TAGS
            ],
            strip=True
        )

        content = bleach.linkify(
            content
        )

        comment = Comment(content=content,
                          post=post,
                          author=current_user())

        db.session.add(comment)
        db.session.commit()

        return post, 201
Пример #22
0
def get_watchlist():
    user = current_user()

    unwatched = list(filter(lambda m: m.watched_at == None, user.watchlist))
    response = list(m.movie.serialize() for m in unwatched)

    return jsonify(response)
Пример #23
0
def mark_as_watched():
    movie_id = request.args.get('movieId')
    house_id = request.args.get('houseId')

    if not movie_id or not house_id:
        raise CustomError("Movie ID or House ID not provided")

    user = current_user()
    user_movie_to_patch = next(
        filter(lambda m: m.movie_id == int(movie_id), user.watchlist), None)
    movie = Movie.query.get(movie_id)
    house = House.query.get(house_id)
    turns = house.get_current_and_next_turns()

    # Check if it's actually the current user's turn
    if turns['current_turn']['id'] != user.id:
        raise CustomError(f"It is not {user.username}'s turn to choose")

    if user_movie_to_patch is None:
        raise CustomError("Movie could not be found", 404)

    try:
        user_movie_to_patch.watched_at = db.func.current_timestamp()
        db.session.add(HouseTurns(user=user, movie=movie, house=house))
        db.session.commit()
        data = {'message': 'Movie marked as watched'}

        return make_response(jsonify(data), 201)
    except Exception as e:
        payload = {'meta': str(e)}
        raise CustomError("Unable to update movie as watched", 500, payload)
Пример #24
0
def add_vote():
    req = request.get_json(force=True)
    user_id = req.get('user_id', None)
    game_id = req.get('game_id', None)
    team_id = req.get('team_id', None)
    if current_user().id != user_id:
        abort(403)
    game = Game.query.get(game_id)
    if not game:
        return bad_request('Game not found')
    team = Team.query.get(team_id)
    if not team:
        return bad_request('Team not found')
    if game.home_team != team and game.away_team != team:
        return bad_request('Team not playing in game')
    vote = Vote.query.filter_by(user_id=user_id, game_id=game_id).first()
    if not vote:
        vote = Vote(user_id=user_id, game_id=game_id, team_id=team_id)
        db.session.add(vote)
        db.session.commit()
    elif vote.team != team:
        vote.team = team
        db.session.commit()
    vote_schema = VoteSchema()
    output = vote_schema.dump(vote).data
    return jsonify({'vote': output})
Пример #25
0
def jobPostingForm():
    user_id = flask_praetorian.current_user().identity
    if request.method == 'POST' and user_id:
        return JobPostingHandler().createJobPosting(
            request.get_json(force=True), user_id)
    else:
        return jsonify(Error="Method not allowed"), 405
Пример #26
0
    def patch(self, id):
        """
        Update a Recommendation
        """
        with db.session.no_autoflush:
            req = api.payload

            # Fetch Recommendation
            recommendation = Recommendation.query.filter_by(id=id).first()

            if recommendation is None:
                return {'message': 'Recommendation does not exist'}, 404

            # Check User permission
            current_user = flask_praetorian.current_user()
            if recommendation.user_id != current_user.id:
                return {'message': 'Unauthorized to edit Recommendation'}, 401

            # Validate
            try:
                edit_recommendation = recommendation_patch_schema.load(req)
            except ValidationError as err:
                return {'error': err.messages}

            # Edit Recommendation
            recommendation.content = edit_recommendation.content

            try:
                db.session.commit()
            except Exception:
                return {'message': 'Unable to edit Recommendation'}, 500

            return {'message': 'Recommendation updated successfully'}
Пример #27
0
 def get(self):  # On a Get Request
     try:
         user = UserModel.get_by_id(
             record_id=flask_praetorian.current_user().id)
         return user, 200
     except Exception as e:
         rp_api.abort(400, e)
Пример #28
0
def parse_resume():
    if request.method == 'POST':
        print(request.files, file=sys.stderr)
        if 'file' not in request.files:
            return jsonify(Error="File error")
        file = request.files['file']
        if file.filename == '':
            return jsonify(Error="File error")
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            if filename:
                resume = BytesIO(file.read())
                resume.name = filename
                return ResumeHandler().parse_resume(
                    resume_file=resume,
                    resume_filename=filename,
                    skills_file='./resume_parser/skills_dataset.csv')
            return jsonify(Error="Filename not secure")
    if request.method == 'GET':
        resume = ResumeHandler().getResumeByUserId(
            flask_praetorian.current_user().user_id)
        if resume:
            #just send the essentials
            b64Data = base64.b64encode(resume['resume_data'].tobytes())
            data = b64Data.decode('utf-8')
            ext = resume['resume_extension']
            applicantResume = {'resume_data': data, 'resume_extension': ext}
            return applicantResume
        return jsonify(Error="Resource not found")
    return jsonify(Error="Method not allowed"), 405
Пример #29
0
def get_user(id):
    if current_user().id != id:
        abort(403)
    one_user = User.query.get_or_404(id)
    user_schema = UserSchema()
    output = user_schema.dump(one_user).data
    return jsonify({'user' : output})
Пример #30
0
def userDetail():
    if request.method == 'GET':
        current_user = flask_praetorian.current_user()
        user = UserHandler().getUsersById(current_user.user_id)
        return user
    else:
        return jsonify(Error="Method not allowed"), 405