コード例 #1
0
def login():
    data = request.get_json()
    missing_fields = UserValidator().login_fields(data)

    if missing_fields:
        return make_response(jsonify(missing_fields), 400)

    validate_user = UserValidator(data)
    reg_email = re.compile(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$")

    if not re.match(reg_email, str(data['email'])):
        return make_response(jsonify({"error": validate_user.valid_email()}),
                             422)

    credentials = {"email": data['email'], "password": data['password']}

    # if auth:
    log_user = User().log_in_user(credentials)

    if isinstance(log_user, int):
        auth_token = User().encode_auth_token(log_user)
        return make_response(
            jsonify({
                "status":
                201,
                "auth_token":
                auth_token.decode('utf-8'),
                "message":
                "{} has been successfully logged in".format(data['email'])
            }), 201)
    else:
        return make_response(log_user)
コード例 #2
0
    def post(self):
        '''Sign up a user'''
        data = request.get_json()
        if not new_user_validator(data):
            check_exists = get_user_by_email(data['email'])
            check_exists2 = get_user_by_username(data['username'])
            if check_exists:
                return {'Status': 409, 'Message':"Email already exists!"},409
            if check_exists2:
                return {'Status': 409, 'Message':"Username already exists!"},409
            isAdmin = False
            create_user = User(data['firstname'],
							data['lastname'],  
							data['email'],
                            data['phoneNumber'],
                            data['username'],
							data['password'],
							isAdmin)
            if len(data['password']) < 6:
                return {"Status":400, 'Message': 'Password should be at least 6 characters'}, 400
            create_user.add_new_user()
            user = create_user.user_data()

            return {'Status': 201, 'Message': "User registered successfully", 'User': user}, 201
        return new_user_validator(data)
コード例 #3
0
    def setUp(self):

        self.user_item = dict(
            first_name="David",
            last_name="Mwangi",
            othername="Dave",
            email="*****@*****.**",
            phoneNumber="0729710290",
            username="******",
            password="******",
        )

        self.user = User(self.user_item, os.getenv('TEST_DATABASE_URI'))
        self.user.base_model.database.create_tables()
コード例 #4
0
def get():
    users = User().fetch_all_users()
    users_list = []

    for user in users:
        users_list.append(user[0])

    return make_response(jsonify({"status": 200, "users": users_list}), 200)
コード例 #5
0
def del_account(userId):

    remove_user = User().delete_user(userId)
    if isinstance(remove_user, dict):
        return make_response(jsonify(remove_user))
    else:
        return make_response(
            jsonify(
                {"message": f"user with id '{userId}' deleted successfully"}))
コード例 #6
0
def post_a_question(meetupId, userId):
    data = request.get_json()

    if QuestionValidator().question_fields(data):
        return make_response(
            jsonify(QuestionValidator().question_fields(data)), 400)
    else:
        validate_question = QuestionValidator(data)
        validation_methods = [
            validate_question.valid_que, validate_question.data_exists
        ]

        for error in validation_methods:
            if error():
                return make_response(jsonify({"error": error()}), 422)

        meetup = Meetup().fetch_specific_meetup('id', f"id = {meetupId}")
        user = User().fetch_specific_user('id', f"id = {userId}")

        question = {
            "authorId": userId,
            "title": data['title'],
            "body": data['body'],
            "meetupId": meetupId
        }

        if meetup and user:

            question_model = Question(question)
            question_model.save_question()

            return make_response(
                jsonify({
                    "status":
                    201,
                    "message":
                    "You have successfully posted a question",
                    "data": [{
                        "title": data['title'],
                        "body": data['body'],
                        "meetup": meetupId,
                        "user": userId
                    }]
                }), 201)
        elif not meetup:
            return make_response(
                jsonify({
                    "error": "Meetup not found or does not exist!",
                    "status": 404
                }), 404)
        elif not user:
            return make_response(
                jsonify({
                    "error": "Please create an account first!",
                    "status": 403
                }), 403)
コード例 #7
0
def post_a_meetup(adminId):
    data = request.get_json()

    if MeetupValidator().meetup_fields(data):
        return make_response(jsonify(MeetupValidator().meetup_fields(data)),
                             400)
    else:
        # Validate user
        validate_question = MeetupValidator(data)
        validation_methods = [
            validate_question.data_exists, validate_question.valid_description,
            validate_question.valid_location, validate_question.valid_tags,
            validate_question.valid_title
        ]

        for error in validation_methods:
            if error():
                return make_response(
                    jsonify({
                        "error": error(),
                        "status": 422
                    }), 422)

        meetup = {
            "topic": data['title'],
            "description": data['description'],
            "location": data['location'],
            "images": data['images'],
            "happeningOn": data['happeningOn'],
            "tags": data['tags'],
            "id": adminId
        }

        meetup_model = Meetup(meetup=meetup)
        meetup_model.save_meetup()

        User().make_admin(adminId)

        return make_response(
            jsonify({
                "status":
                201,
                "message":
                "You have successfully posted a meetup",
                "data": [{
                    "topic": data['title'],
                    "location": data['location'],
                    "images": data['images'],
                    "happeningOn": data['happeningOn'],
                    "tags": data['tags'],
                }],
            }), 201)
コード例 #8
0
def comment_on_question(questionId, userId):
    data = request.get_json()

    try:
        data['comment']
    except:
        return jsonify({
            "error": 'You missed the {} key, value pair'.format(data['comment'])
        })
        
    question = Question().fetch_specific_question('id', f"id = {questionId}")
    user = User().fetch_specific_user('id', f"id = {userId}")

    if question and user:
    
        comment = {
            "authorId": userId,
            "comment": data['comment'],
            "questionId": questionId,
        }

        comment_model = Comment(comment)

        comment_model.save_comment()
    
        return make_response(jsonify({
            "status": 201,
            "message": "You have successfully commented on this question",
            "data": [{
                "question": questionId,
                "comment": comment['comment']
            }]
        }), 201)
    elif not question:
        return make_response(jsonify({
            "error": "Question not found or does not exist",
            "status": 404
        }), 404)
    elif not user:
        return make_response(jsonify({
            "error": "User not found or does not exist",
            "status": 404
        }), 404)
コード例 #9
0
def delete_meetup(meetupId):

    try:
        User().fetch_specific_user('isAdmin', "isAdmin = True")
        remove_meetup = Meetup().delete_meetup(meetupId)
        if isinstance(remove_meetup, dict):
            return make_response(jsonify(remove_meetup))
        else:
            return make_response(
                jsonify({
                    "message":
                    f"meetup with id '{meetupId}' deleted successfully"
                }))
    except:
        return make_response(
            jsonify({
                "error": "This resource is accessible by admins only",
                "status": 403
            }))
コード例 #10
0
def registration():
    data = request.get_json()

    # Validate user
    validate_user = UserValidator(data)
    validation_methods = [
        validate_user.valid_email, validate_user.valid_name,
        validate_user.valid_phoneNumber, validate_user.validate_password,
        validate_user.matching_password
    ]

    for error in validation_methods:
        if error():
            return make_response(jsonify({
                "error": error(),
                "status": 422
            }), 422)

    # Register user
    user_data = {
        "first_name": data['first_name'],
        "last_name": data['last_name'],
        "othername": data['othername'],
        "email": data['email'],
        "phoneNumber": data['phoneNumber'],
        "username": data['username'],
        "password": data['password']
    }

    reg_user = User(user_data)
    if reg_user.save_user():
        return make_response(jsonify(reg_user.save_user()), 409)
    else:
        id = reg_user.fetch_user_id(user_data['username'])
        auth_token = reg_user.encode_auth_token(id[0])
        return make_response(
            jsonify({
                "status":
                201,
                "message":
                "{} registered successfully".format(data['email']),
                "username":
                data['username'],
                "auth_token":
                auth_token.decode('utf-8')
            }), 201)
コード例 #11
0
def update_account(userId):
    data = request.get_json()

    if UserValidator().signup_fields(data):
        return make_response(jsonify(UserValidator().signup_fields(data)), 400)
    else:
        # Validate user
        validate_user = UserValidator(data)
        validation_methods = [
            validate_user.valid_email, validate_user.valid_name,
            validate_user.valid_phoneNumber, validate_user.validate_password,
            validate_user.matching_password
        ]

        for error in validation_methods:
            if error():
                return make_response(jsonify({"error": error()}), 422)

    user_data = {
        "first_name": data['first_name'],
        "last_name": data['last_name'],
        "othername": data['othername'],
        "email": data['email'],
        "phoneNumber": data['phoneNumber'],
        "username": data['username'],
        "password": data['password']
    }

    update_user = User().update_user(userId, user_data)
    if isinstance(update_user, dict):
        return make_response(jsonify(update_user))
    else:
        return make_response(
            jsonify(
                {"message":
                 f"user {user_data['email']} updated successfully"}))
コード例 #12
0
def edit_meetup(adminId, meetupId):
    data = request.get_json()

    if MeetupValidator().meetup_fields(data):
        return make_response(jsonify(MeetupValidator().meetup_fields(data)),
                             400)
    else:
        # Validate user
        validate_question = MeetupValidator(data)
        validation_methods = [
            validate_question.valid_date, validate_question.data_exists,
            validate_question.valid_description,
            validate_question.valid_location, validate_question.valid_tags,
            validate_question.valid_title
        ]

        for error in validation_methods:
            if error():
                return make_response(
                    jsonify({
                        "error": error(),
                        "status": 422
                    }), 422)

        updates = {
            "topic": data['title'],
            "description": data['description'],
            "location": data['location'],
            "images": data['images'],
            "happeningOn": data['happeningOn'],
            "tags": data['tags']
        }

        try:
            userId = Meetup().fetch_specific_meetup('authorId',
                                                    f"id = {meetupId}")[0]
            user = User().fetch_specific_user('id', f"id = {userId}")[0]

            if adminId == user:

                if isinstance(Meetup().update_meetup(meetupId, updates), dict):

                    return make_response(
                        Meetup().update_meetup(meetupId, updates), 404)
                else:
                    return make_response(
                        jsonify({
                            "status":
                            200,
                            "message":
                            f"Meetup with id {meetupId} was updated"
                        }), 200)
            else:
                return make_response(
                    jsonify({
                        "error":
                        "Sorry! Only admins are authorized to access this resource.",
                        "status": 403
                    }), 403)
        except:

            return make_response(Meetup().update_meetup(meetupId, updates),
                                 404)
コード例 #13
0
class TestBaseModel(unittest.TestCase):

    def setUp(self):

        self.user_item = dict(
            first_name="David",
            last_name="Mwangi",
            othername="Dave",
            email="*****@*****.**",
            phoneNumber="0729710290",
            username="******",
            password="******",
        )

        self.user = User(self.user_item, os.getenv('TEST_DATABASE_URI'))
        self.user.base_model.database.create_tables()


    def test_save_user(self):
        """ Test that save user method works correctly """

        # add item
        self.user.save_user()
        user = self.user.fetch_specific_user('username', "username = '******'")
        self.assertTrue(user)


    def test_fetch_user_id(self):
        """ Test fetch user id method works correctly """

        self.user.save_user()
        self.assertTrue(self.user.fetch_user_id('dave'))
        self.assertFalse(self.user.fetch_user_id('mash'))


    def test_fetch_all_users(self):
        """ Test fetch all users method works correctly """

        users = self.user.fetch_all_users()

        # zero users
        self.assertFalse(users)

        # one user
        self.user.save_user()
        self.assertTrue(self.user.fetch_all_users())


    def test_fetch_specific_user(self):
        """ Test fetch specific user method works correctly """

        self.user.save_user()
        self.assertTrue(self.user.fetch_specific_user('id', "username = '******'"))


    def test_log_in_user(self):
        """ Test log in user method works correctly """

        self.user.save_user()
        user = {
            "email": self.user_item['email'],
            "password": self.user_item['password']
        }
        self.assertEqual(self.user.log_in_user(user), 1)

    
    def test_make_admin(self):
        """ Test make admin method works correctly """

        self.user.save_user()
        admin = self.user.fetch_specific_user('isAdmin', "username = '******'")[0]
        self.assertEqual(admin, False)
        # self.user.make_admin(1)
        # self.assertEqual(admin, True)
        # self.assertTrue(self.user.make_admin(1))
        

    def tearDown(self):
        """ This method destroys the test tables """

        self.user.base_model.database.drop_tables()
コード例 #14
0
async def add_user_method(request):
    user = User(request.json, strict=True)
    user.validate()
    user = await db_api.add_user(user.to_native())
    return json(user, status=201)
コード例 #15
0
async def update_user_by_id_method(request, user_id):
    user_id = UserById({'user_id': user_id}).user_id
    user = User(request.json, strict=True)
    user.validate()
    user = db_api.update_user_by_id(user_id, user.to_native())
    return json(user, status=200)
コード例 #16
0
def post_RSVP(meetupId, userId):
    data = {}

    try:
        meetup_id = Meetup().fetch_specific_meetup('id', f"id = {meetupId}")[0]
        meetup = Meetup().fetch_specific_meetup('topic', f"id = {meetupId}")[0]
        user_id = User().fetch_specific_user('id', f"id = {userId}")[0]

        try:
            data = request.get_json()
            data['status']
        except:
            return make_response(
                jsonify({
                    "error": 'You missed the status key, value pair',
                    "status": 400
                }), 400)

        rsvp = dict(userId=user_id, meetupId=meetup_id, status=data['status'])

        responses = {
            "yes":
            f"You have successfully RSVP'd on meetup '{meetup.upper()}'",
            "no":
            f"You have confirmed you're not attending meetup '{meetup.upper()}'",
            "maybe":
            f"You have confirmed you might attend '{meetup.upper()}' meetup"
        }

        def confirm(res):
            str(res).lower()
            if res == 'yes' or res == 'no' or res == 'maybe':
                return responses[res]
            else:
                return False

        if not confirm(rsvp['status']):
            return make_response(
                jsonify({
                    "error": "Invalid response! Respond with YES/NO/MAYBE",
                    "status": 400
                }))
        else:
            rsvp_tuple = Meetup().fetch_rsvps('(userId, meetupId)',
                                              f'True = True')
            incoming_rsvp = [(f'({userId},{meetupId})', )]

            if incoming_rsvp[0] in rsvp_tuple:

                return make_response(
                    jsonify({
                        "status": 400,
                        "error": "You've already RSVPd on this meetup!"
                    }))
            else:
                Meetup().rsvp_meetup(rsvp)

                return jsonify({
                    "status": 200,
                    "message": confirm(rsvp['status']),
                    "data": rsvp
                }), 201
    except:
        return jsonify({
            "error": 'Meetup not found or does not exist',
            "status": 404
        }), 404
コード例 #17
0
    def vote_on_question(self, userId, questionId, vote):
        """ This method votes on a question """

        # check that user exists
        if not User().fetch_specific_user('id', f"id = {userId}"):
            return {"error": "User not found or does'nt exist", "status": 404}
        elif not Question().fetch_specific_question('id',
                                                    f"id = {questionId}"):
            return {
                "error": "Question not found or does'nt exist",
                "status": 404
            }

        # Array --> [(['1', '1', '2'],)]

        updateVote = self.fetch_specific_question('totalVotes',
                                                  f"id = {questionId}")[0]
        if vote == "upvote":
            updateVote += 1
        elif vote == "downvote":
            updateVote -= 1

        voters_list = self.fetch_questions('voters',
                                           f"questionId = {questionId}",
                                           'votes')

        # fetch user & question
        user = {User().fetch_specific_user('id', f"id = {userId}")[0]}
        user_id = {userId}
        question = Question().fetch_specific_question('id',
                                                      f"id = {questionId}")[0]

        # votes item
        fields = dict(voters=str(user), questionId=question)

        keys = ", ".join(fields.keys())
        values = tuple(fields.values())

        if voters_list:
            # Check if user has already voted on question
            if str(userId) in voters_list[0][0]:
                return {
                    "error": "Sorry, You can only vote once!",
                    "status": 403
                }
            else:
                question_id = self.base_model.grab_items_by_name(
                    'questionId', f"questionId = {questionId}", 'votes')

                # check if questionId exists in votes table
                if question_id:
                    self.base_model.update_item(
                        f"voters = array_cat(voters, '{user_id}')",
                        f"questionId = {questionId}", 'votes')
                    return self.base_model.update_item(
                        f"totalVotes = {updateVote}", f"id = {questionId}")
                else:
                    self.base_model.add_item(keys, values, 'votes')
                    return self.base_model.update_item(
                        f"totalVotes = {updateVote}", f"id = {questionId}")
        else:
            self.base_model.add_item(keys, values, 'votes')
            return self.base_model.update_item(f"totalVotes = {updateVote}",
                                               f"id = {questionId}")