예제 #1
0
def query_user_create(user_name: str, user_email: str, user_password: str,
                      user_ip="0.0.0.0"):
    """
    :param user_name: user's unique nickname
    :param user_email: user's unique email
    :param user_password: user's password
    :param user_ip: user's ip address (default 0.0.0.0)
    :return: user object if succeeded
    """
    if type(user_name) != str or type(user_email) != str or type(
            user_password) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    if len(query_user_get_by_name(user_name)) > 0:
        raise MongoError(ErrorCode.MONGODB_USER_NAME_TAKEN)

    elif len(query_user_get_by_email(user_email)) > 0:
        raise MongoError(ErrorCode.MONGODB_USER_EMAIL_TAKEN)

    login = [
        UserLogin(user_login_ip=user_ip, user_login_time=get_time_now_utc())]

    # EmbeddedDocument must be included when creating
    # user_detail, user_reg_date
    user = User(user_name=user_name, user_email=user_email,
                user_password=user_password,
                user_detail=UserDetail(), user_status="private",
                user_thumbnail="",
                user_reg_date=get_time_now_utc(), user_login=login,
                user_following=[], user_follower=[])

    return user.save()
예제 #2
0
def query_user_add_follow(follower_id: str, following_id: str):
    """
    :param follower_id: follower user id
    :param following_id: uploader user_id
    :return: 1 if succeeded
    """
    if type(follower_id) != str or type(following_id) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    follower = query_user_get_by_id(follower_id)
    following = query_user_get_by_id(following_id)

    if len(follower) == 0:
        raise MongoError(ErrorCode.MONGODB_FOLLOWER_NOT_FOUND)

    if len(following) == 0:
        raise MongoError(ErrorCode.MONGODB_FOLLOWED_NOT_FOUND)

    if following_id in follower[0].user_following and follower_id in \
            following[0].user_follower:
        raise MongoError(ErrorCode.MONGODB_FOLLOW_REL_EXISTS)

    User.objects(id=follower_id).update(
        add_to_set__user_following=following_id)
    User.objects(id=following_id).update(
        add_to_set__user_follower=follower_id)

    return 1
예제 #3
0
def query_user_add_login(user_id: str, ip="0.0.0.0", time=get_time_now_utc()):
    """
    :param user_id: user's unique id
    :param ip: user's login ip address
    :param time: user's login time (utc, optional), default: current system
    time (utc)
    :return: 1 if succeeded
    """
    if type(user_id) != str or type(ip) != str or type(
            time) != datetime.datetime:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)
    users = query_user_get_by_id(user_id)
    if len(users) == 0:
        raise MongoError(ErrorCode.MONGODB_USER_NOT_FOUND)
    # only keep 10 login info
    login_history = users[0].user_login
    oldest = login_history[0]
    latest = login_history[-1]
    # TODO: update latest 10 login info method, some bugs for current version
    if len(login_history) >= 10:
        # Delete oldest history
        clean = UserLogin(
            user_login_ip=oldest.user_login_ip,
            user_login_time=oldest.user_login_time)
        print(User.objects(id=user_id).update_one(
            pull__user_login__user_login_time=clean.user_login_time))
    if time == latest:
        User.objects(id=user_id).update(
            pull__user_login__user_login_time=latest)
    new_login = {'user_login_ip': ip, 'user_login_time': time}
    User.objects(id=user_id).update(
        add_to_set__user_login=[new_login])
    return 1
예제 #4
0
def query_user_update_thumbnail(user_id: str, user_thumbnail: str):
    """
    :param user_id: user's id
    :param user_thumbnail: thumbnail URI
    :return: array of user Model
    """
    if type(user_id) != str or type(user_thumbnail) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    users = query_user_get_by_id(user_id)
    if len(users) == 0:
        raise MongoError(ErrorCode.MONGODB_USER_NOT_FOUND)

    User.objects(id=user_id).update(
        user_thumbnail=user_thumbnail)
def parse_data(fromUserId):
    # userId
    from_user = User.get_or_none(User.userId == fromUserId)

    # to_userId
    json_data = flask.request.json
    toUserId = json_data.get('userId')
    to_user = User.get_or_none(User.userId == toUserId)

    msg = "Success"
    code = 200

    if not to_user:
        msg = 'UserId \'%s\' does not exists' % toUserId
        code = 400
    return (from_user, to_user), msg, code
예제 #6
0
def signup():
    data = flask.request.json
    if not data['name']:
        return flask.jsonify({"msg": "Missing name"}), 400
    if not data['email']:
        return flask.jsonify({"msg": "Missing email"}), 400
    if not data['password']:
        return flask.jsonify({"msg": "Missing password"}), 400

    user = User(name=data['name'], email=data['email'], pw=data['password'])
    if user.save() and len(user.errors) == 0:
        access_token = create_access_token(identity=user.email)
        user_dict = user.as_dict()
        user_dict['access_token'] = access_token
        return flask.jsonify(user_dict), 200
    else:
        return flask.jsonify({'msg': user.errors[0]}), 400
예제 #7
0
 def test_user_model_load(self):
     temp_user = self.data['temp_user'][2]
     user = User(**temp_user)
     self.assertEqual(user.user_name, temp_user['user_name'])
     self.assertEqual(user.user_detail.user_first_name,
                      temp_user['user_detail']['user_first_name'])
     self.assertEqual(user.user_login[0].user_login_time,
                      temp_user['user_login'][0]['user_login_time'])
     self.assertEqual(user.user_follower, temp_user['user_follower'])
예제 #8
0
def query_user_get_by_id(user_id: str):
    """
    :param user_id: user id
    :return: an array of such User (len == 0 or 1), len == 0 if no such
    user_id, len == 1 if found
    """
    if type(user_id) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    return User.objects(id=user_id)
예제 #9
0
def query_user_get_by_name(user_name: str):
    """
    :param user_name: user name
    :return: an array of such User, len == 0 if no such user_name, len == 1
    if found
    """
    if type(user_name) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    return User.objects(user_name=user_name)
예제 #10
0
def util_tests_clean_database():

    data = util_tests_load_data()

    for user in data['temp_user']:
        User.objects(user_name=user['user_name']).delete()

    for video in data['temp_video']:
        Video.objects(video_title=video['video_title']).delete()
        Video.objects(user_id=video['user_id']).delete()

    for video in data['const_video']:
        VideoOp.objects(video_id=video['_id']['$oid']).delete()

    Video.objects(user_id=data['const_user'][1]['_id']['$oid']).delete()
    Video.objects(video_title="new title").delete()
    Video.objects(video_title="").delete()
    VideoOp.objects(user_id=data['const_user'][1]['_id']['$oid']).delete()
    vop = data['const_video_op'][0]
    VideoOp(**vop).save()
예제 #11
0
def edit_image(userId):
    if "image" not in flask.request.files:
        return flask.jsonify({'msg': 'No \'image\' key in request.files'}), 400

    file = flask.request.files['image']
    print(file)
    if file.filename == '':
        return flask.jsonify(
            {'msg': 'No file is found in \'image\' in request.files'}), 400

    if file and storage.allowed_file(file.filename):
        print("here")
        file.filename = "user{}-profile-{}{}".format(
            userId, datetime.strftime(datetime.now(), "%y%m%d%H%M%S"),
            os.path.splitext(file.filename)[1])
        upload_error = storage.upload_file_to_s3(file)
        if not upload_error:
            User.update(imgName=file.filename).where(
                User.userId == userId).execute()

    return flask.jsonify({'msg': 'Success'}), 200
예제 #12
0
def query_user_delete_by_name(user_name: str, silent=False):
    """
    :param user_name: user's name
    :param silent: delete user regardless of existence
    :return: 1 if succeeded
    """
    if type(user_name) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    users = query_user_get_by_name(user_name)
    if len(users) == 0 and silent is False:
        raise MongoError(ErrorCode.MONGODB_USER_NOT_FOUND)

    return User.objects(user_name=user_name).delete()
예제 #13
0
def query_user_delete_follow(follower_id: str, following_id: str):
    """
    :param follower_id: follower user id
    :param following_id: uploader user_id
    :return: 1 if succeeded
    """

    if type(follower_id) != str or type(following_id) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    follower = query_user_get_by_id(follower_id)
    following = query_user_get_by_id(following_id)

    if len(follower) == 0:
        raise MongoError(ErrorCode.MONGODB_FOLLOWER_NOT_FOUND)
    if len(following) == 0:
        raise MongoError(ErrorCode.MONGODB_FOLLOWED_NOT_FOUND)

    User.objects(id=follower_id).update(
        pull__user_following=following_id)
    User.objects(id=following_id).update(
        pull__user_follower=follower_id)

    return 1
예제 #14
0
def parse_data(userId):
    json_data = flask.request.json

    user = User.get_or_none(User.userId == userId)

    recipeId = json_data.get('recipeId')
    recipe = Recipe.get_or_none(Recipe.id == recipeId)

    msg = "Success"
    code = 200

    if not recipe:
        msg = 'RecipeId \'%s\' does not exists' % recipeId
        code = 400

    return (user, recipe), msg, code
예제 #15
0
def query_user_update_status(user_id: str, user_status: str):
    """
    :param user_id: user's unique id
    :param user_status: user's new status
    :return: array of User Model
    """
    if type(user_id) != str or type(user_status) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    if len(query_user_get_by_id(user_id)) == 0:
        raise MongoError(ErrorCode.MONGODB_USER_NOT_FOUND)

    if user_status not in VALID_USER_STATUS:
        raise MongoError(ErrorCode.MONGODB_USER_INVALID_STATUS)

    return User.objects(id=user_id).update(
        user_status=user_status)
예제 #16
0
 def create_user(self, **kwargs):
     """
     Method to create user
     :param kwargs:
     :return:
     """
     user = User(username=kwargs.get('usr'),
                 password=self._create_password_hash(kwargs.get('pwd')))
     try:
         self._SESSSION.add(user)
         self._SESSSION.commit()
         print("User saved in database.\n")
     except IntegrityError:
         print("Username already exist! Please try again.\n")
         self._SESSSION.rollback()
     except InvalidRequestError:
         self._SESSSION.rollback()
예제 #17
0
def query_user_update_password(user_id: str, user_password: str):
    """
    :param user_id: user's id
    :param user_password: user's password
    :return: array of User Model
    """
    if type(user_id) != str or type(user_password) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    users = query_user_get_by_id(user_id)
    if len(users) == 0:
        raise MongoError(ErrorCode.MONGODB_USER_NOT_FOUND)

    old_password = users[0].user_password
    if util_hash_encode(user_password) == old_password:
        raise MongoError(ErrorCode.MONGODB_UPDATE_SAME_PASS)

    return User.objects(id=user_id).update(
        user_password=util_hash_encode(user_password))
예제 #18
0
def query_user_update_name(user_id: str, user_name: str):
    """
    :param user_id: user's id
    :param user_name: user's name
    :return: array of User Model
    """
    if type(user_id) != str or type(user_name) != str:
        raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    users = query_user_get_by_id(user_id)
    if len(users) == 0:
        raise MongoError(ErrorCode.MONGODB_USER_NOT_FOUND)

    old_name = users[0].user_name
    if user_name == old_name:
        raise MongoError(ErrorCode.MONGODB_UPDATE_SAME_NAME)

    if len(query_user_get_by_name(user_name)) > 0:
        raise MongoError(ErrorCode.MONGODB_USER_NAME_TAKEN)

    return User.objects(id=user_id).update(user_name=user_name)
예제 #19
0
def add_recipe():
    json_data = flask.request.json

    # userId
    userId = json_data.get('userId')
    user = User.get_or_none(User.userId == userId)
    if not user:
        return flask.jsonify({'msg': 'Must provide valid userId'}), 400

    # name
    name = json_data.get('name')
    if not name:
        return flask.jsonify({'msg': 'Must provide non-empty name'}), 400

    # name
    serving = json_data.get('serving')
    if not serving:
        return flask.jsonify({'msg': 'Must provide non-empty serving'}), 400

    # name
    preparation_time = json_data.get('preparation_time')
    if not preparation_time:
        return flask.jsonify(
            {'msg': 'Must provide non-empty preparation_time'}), 400

    # name
    cooking_time = json_data.get('cooking_time')
    if not cooking_time:
        return flask.jsonify({'msg':
                              'Must provide non-empty cooking_time'}), 400

    recipe = Recipe(user=user,
                    name=name,
                    serving=serving,
                    preparation_time=preparation_time,
                    cooking_time=cooking_time)
    if not recipe.save():
        return flask.jsonify({'msg': 'Error in saving data'}), 400
    return flask.jsonify({'msg': 'Success'}), 200
예제 #20
0
def login():
    data = flask.request.json

    if not data['email']:
        return flask.jsonify({"msg": "Missing email"}), 400
    if not data['password']:
        return flask.jsonify({"msg": "Missing password"}), 400

    user = User.get_or_none(User.email == data['email'])
    successful_login = check_password_hash(user.pw_hash,
                                           data['password']) if user else False

    if successful_login:
        access_token = create_access_token(identity=user.email)
        user_dict = user.as_dict()
        user_dict['access_token'] = access_token
        return flask.jsonify(user_dict), 200

    else:
        if user is None: msg = "Email does not exists in database"
        elif successful_login is False: msg = "Wrong password is provided"
        else: msg = ''
        return flask.jsonify({'msg': msg}), 400
예제 #21
0
def edit_user(userId: str):
    json_data = flask.request.json
    user = User.get(User.userId == userId)
    isEdited = False

    # name
    name = json_data.get('name')
    if name:
        if user.name != name:
            isEdited = True
            user.name = name

    # email
    email = json_data.get('email')
    if email:
        if user.email != email:
            isEdited = True
            user.email = email

    if isEdited:
        if not user.save():
            return flask.jsonify({'msg': 'Error in saving data'}), 400
    return flask.jsonify({'msg': 'Success'}), 200
예제 #22
0
def add_comment():
    json_data = flask.request.json

    # userId
    userId = json_data.get('userId')
    user = User.get_or_none(User.userId == userId)
    if not user:
        return flask.jsonify({'msg': 'Must provide valid userId'}), 400

    # recipeId
    recipeId = json_data.get('recipeId')
    recipe = Recipe.get_or_none(Recipe.id == recipeId)
    if not recipe:
        return flask.jsonify({'msg': 'Must provide valid recipeId'}), 400

    # text
    text = json_data.get('text')
    if not text:
        return flask.jsonify({'msg': 'Must provide non-empty text'}), 400

    comment = Comment(user=user, recipe=recipe, text=text)
    if not comment.save():
        return flask.jsonify({'msg': 'Error in saving data'}), 400
    return flask.jsonify({'msg': 'Success'}), 200
예제 #23
0
    data = dict(name=name, email=email, password=password)
    return test_url(url, method="POST", data=data, auth=False)


def test_login(email='', password=''):
    url = 'http://*****:*****@gmail.com'
    password = "******"

    existing_user = User.get_or_none(User.email == email)
    if existing_user:
        existing_user.delete_instance()

    # Must Fail (Sign Up)
    assert_msg(test_signup(name="", email=email, password=password),
               "Missing name")  # Empty Name
    assert_msg(test_signup(name=name, email="", password=password),
               "Missing email")  # Empty Email
    assert_msg(test_signup(name=name, email=email, password=''),
               "Missing password")  # Empty Password
    assert_msg(
        test_signup(name=name,
                    email='*****@*****.**',
                    password=password),
        "This email has been registered! Try another email!")  # Taken Email
예제 #24
0
def userExists():
    userId = flask.request.args.get('userId')
    user = User.get_or_none(User.userId == userId)
    return flask.jsonify(user is not None), 200
예제 #25
0
 def likes(self):
     from models.relation_like import LikeRelation
     return User.select().join(
         LikeRelation,
         pw.JOIN.LEFT_OUTER).where(LikeRelation.recipe == self)
예제 #26
0
def query_user_update_details(**kw):
    """
    Update user details
    :param kw:
        :key "user_id": user unique id, required
        :key "user_first_name": (```str```, optional) new user first name
        :key "user_last_name": (```str```, optional) new user last name
        :key "user_phone": (```str```, optional) new user phone
        :key "user_street1": (```str```, optional) new user street1
        :key "user_street2": (```str```, optional) new user street2
        :key "user_city": (```str```, optional) new user city
        :key "user_state": (```str```, optional) new user state
        :key "user_country": (```str```, optional) new user country
        :key "user_zip": (```str```, optional) new user zip
    \nAt least one key must be provided
    :return: 1 if succeeded
    """
    if 'user_id' not in kw:
        raise MongoError(ErrorCode.MONGODB_MISSING_USER_ID)
    for arg in kw:
        if type(kw[arg]) != str:
            raise MongoError(ErrorCode.MONGODB_STR_EXPECTED)

    users = query_user_get_by_id(kw['user_id'])
    if len(users) == 0:
        raise MongoError(ErrorCode.MONGODB_USER_NOT_FOUND)

    id = kw['user_id']

    if 'user_first_name' in kw:
        User.objects(id=id).update(
            set__user_detail__user_first_name=kw['user_first_name'])
    if 'user_last_name' in kw:
        User.objects(id=id).update(
            set__user_detail__user_last_name=kw['user_last_name'])
    if 'user_phone' in kw:
        User.objects(id=id).update(
            set__user_detail__user_phone=kw['user_phone'])
    if 'user_street1' in kw:
        User.objects(id=id).update(
            set__user_detail__user_street1=kw['user_street1'])
    if 'user_street2' in kw:
        User.objects(id=id).update(
            set__user_detail__user_street2=kw['user_street2'])
    if 'user_city' in kw:
        User.objects(id=id).update(
            set__user_detail__user_city=kw['user_city'])
    if 'user_state' in kw:
        User.objects(id=id).update(
            set__user_detail__user_state=kw['user_state'])
    if 'user_country' in kw:
        User.objects(id=id).update(
            set__user_detail__user_country=kw['user_country'])
    if 'user_zip' in kw:
        User.objects(id=id).update(set__user_detail__user_zip=kw['user_zip'])

    return 1
예제 #27
0
def get_user(userId: str):
    user = User.get_or_none(User.userId == userId)
    return flask.jsonify({'msg': 'Success', 'data': user.as_dict()}), 200
예제 #28
0
def get_users():
    query = User.select()

    users = [c for c in query]
    user_dicts = [c.as_dict() for c in users]
    return flask.jsonify({'msg': 'Success', 'data': user_dicts}), 200
예제 #29
0
 def wrapper(userId, *args, **kwargs):
     user = User.get_or_none(User.userId == userId)
     if user:
         return func(userId, *args, **kwargs)
     else:
         return flask.jsonify({'msg': 'User does not exists'}), 400
예제 #30
0
def query_user_search_by_pattern(**kw):
    """
    search user by pattern (re.Pattern)
    :param kw: keyword arguments
        :key "user_name": (optional) single keyword of username to be searched
        :key "user_email": (optional) single keyword of email to be searched
        :key "user_first_name": (optional) single keyword of first name to be
        searched
        :key "user_last_name": (optional) single keyword of last name to be
        searched
        :key "user_phone": (optional) single keyword of phone to be searched
        :key "user_street1": (optional) single keyword of street1 to be
        searched
        :key "user_street2": (optional) single keyword of street2 to be
        searched
        :key "user_city": (optional) single keyword of city to be searched
        :key "user_state": (optional) single keyword of state to be searched
        :key "user_country": (optional) single keyword of country to be
        searched
        :key "user_zip": (optional) single keyword of zip to be searched
        :key "user_status": (optional) single keyword of status to be searched
    \nAt least one key must be provided
    :return: array of searching results (User Model)
    """
    # Check input param
    if len(kw) == 0:
        raise MongoError(ErrorCode.MONGODB_EMPTY_PARAM)

    for arg in kw:
        if type(kw[arg]) != re.Pattern:
            raise MongoError(ErrorCode.MONGODB_RE_PATTERN_EXPECTED)

    if 'pattern_name' in kw:
        return User.objects(user_name=kw['pattern_name'])
    elif 'pattern_email' in kw:
        return User.objects(user_email=kw['pattern_email'])
    elif 'pattern_first_name' in kw:
        return User.objects(
            user_detail__user_first_name=kw['pattern_first_name'])
    elif 'pattern_last_name' in kw:
        return User.objects(
            user_detail__user_last_name=kw['pattern_last_name'])
    elif 'pattern_phone' in kw:
        return User.objects(user_detail__user_phone=kw['pattern_phone'])
    elif 'pattern_street1' in kw:
        return User.objects(user_detail__user_street1=kw['pattern_street1'])
    elif 'pattern_street2' in kw:
        return User.objects(user_detail__user_street2=kw['pattern_street2'])
    elif 'pattern_city' in kw:
        return User.objects(user_detail__user_city=kw['pattern_city'])
    elif 'pattern_state' in kw:
        return User.objects(user_detail__user_state=kw['pattern_state'])
    elif 'pattern_country' in kw:
        return User.objects(user_detail__user_country=kw['pattern_country'])
    elif 'pattern_zip' in kw:
        return User.objects(user_detail__user_zip=kw['pattern_zip'])
    elif 'pattern_status' in kw:
        return User.objects(user_status=kw['pattern_status'])

    raise MongoError(ErrorCode.MONGODB_INVALID_SEARCH_PARAM)