Esempio n. 1
0
def satisfy_wish(wid):
    """
    向他人赠送书籍
    :param wid: 心愿id
    :return:
    """
    uid = getattr(g, REQUEST_USER_ID)
    wish = Wish.query.get_or_404(wid)
    wisher = User.query.filter(User.id == wish.user_id,
                               User.is_deleted == False).first_or_404()
    gift = Gift.query.filter_by(user_id=uid, isbn=wish.isbn).first()
    if not gift:
        return ErrorResponse(SATISFY_WISH_ERROR).make()
    current_wish = Wish.query.filter_by(user_id=wisher.id,
                                        launched=False,
                                        isbn=wish.isbn).first()
    if not current_wish:
        return ErrorResponse(SATISFY_WISHER_ERROR).make()
    can = wisher.can_send_drift()
    if not can:
        return ErrorResponse(USER_CANNOT_DRIFT).make()
    gifter = User.query.filter(User.id == gift.user_id,
                               User.is_deleted == False).first()
    drift_url = config.FRONT_DRIFT_URL
    send_email(wisher.email,
               '有人想送你一本书',
               'email/satisify_wish.html',
               wisher=wisher,
               gifter=gifter,
               gift=gift,
               drift_url=drift_url,
               wish=wish)
    return SuccessResponse(data=SATISFY_WISH_MSG)()
Esempio n. 2
0
def login():
    schema = LoginValSchema(strict=True).load(request.get_json())
    data = schema.data
    user = User.query.filter_by(email=data['email']).first()
    if not user:
        return ErrorResponse(USER_NOT_EXIST).make()
    if user.check_password(data['password']):
        token = generate_token(user.id, login_token_key, config.LOGIN_TOKEN_EXPIRE_TIME)
        data = {'token': token, 'nickname': user.nickname}
        return SuccessResponse(data=data)()
    else:
        return ErrorResponse(USER_PASSWORD_ERROR).make()
Esempio n. 3
0
def drift(gid):
    uid = getattr(g, REQUEST_USER_ID)
    current_user = User.query.get_or_404(uid)
    current_gift = Gift.query.get_or_404(gid)
    if current_gift.is_yourself_gift(uid):
        # 不能自己给自己发起鱼漂
        return ErrorResponse(SEND_DRIFT_IS_YOURSELF).make()
    # 检验当前用户能否发起鱼漂请求
    can = current_user.can_send_drift(current_gift.isbn)
    if not can:
        return ErrorResponse(USER_CANNOT_DRIFT).make()
    user_from_gift = User.query.get_or_404(current_gift.user_id).summary
    user_from_gift.update({'user_beans': str(current_user.beans)})
    return SuccessResponse(data=user_from_gift)()
Esempio n. 4
0
 def wrapper(*args, **kwargs):
     token = request.headers.get('token', None)
     if token:
         payload = decode_token(token)
         uid = payload['uid']
         key = login_token_key.format(uid)
         token_from_redis = redis.get(key)
         if check_token(token, token_from_redis):
             if not check_user_valid(uid):
                 return ErrorResponse(USER_NOT_EXIST).make()
             redis.setex(key, token, time=config.LOGIN_TOKEN_EXPIRE_TIME)
             setattr(g, REQUEST_USER_ID, uid)
         else:
             return ErrorResponse(TOKEN_INVALID).make()
     return func(*args, **kwargs)
Esempio n. 5
0
def change_password():
    uid = getattr(g, REQUEST_USER_ID, None)
    if uid:
        schema = ChangePasswordValSchema(strict=True)
        data = schema.load(request.get_json()).data
        old_password = data['old_password']
        new_password = data['new_password']
        user = User.query.filter_by(id=uid).first()
        if not user:
            return ErrorResponse(USER_NOT_EXIST).make()
        if not user.check_password(old_password):
            return ErrorResponse(USER_RAWPASSWORD_ERROR).make()
        User.reset_password(user.id, new_password)
        return SuccessResponse(NotContent)()
    else:
        return ErrorResponse(NOT_LOGIN).make()
Esempio n. 6
0
def logout():
    uid = getattr(g, REQUEST_USER_ID, None)
    if uid:
        key = login_token_key.format(uid)
        redis.delete(key)
        return SuccessResponse(NotContent)()
    else:
        return ErrorResponse(NOT_LOGIN).make()
Esempio n. 7
0
def personal_center():
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.filter_by(id=uid).first()
    if not user:
        return ErrorResponse(USER_NOT_EXIST).make()
    schema = UserPersonalSchema()
    data = schema.dump(user.summary).data
    return SuccessResponse(data=data)()
Esempio n. 8
0
def request_error(e):
    logger.error(e)
    error_messages_list = []
    for k, v in e.messages.items():
        for k in v:
            error_messages_list.append(k)
    if len(error_messages_list) != 0:
        VALIDATE_ERROR.message = error_messages_list
    return ErrorResponse(VALIDATE_ERROR).make()
Esempio n. 9
0
def save_to_wish(isbn):
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.filter_by(id=uid).first()
    if is_isbn_or_key(isbn):
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    if not yushu_book.first:
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    if user.can_save_to_list(str(isbn)):
        with db.auto_commit():
            wish = Wish()
            wish.isbn = isbn
            wish.user_id = user.id
            db.session.add(wish)
    else:
        return ErrorResponse(SAVE_WISH_ERROR).make()
    return SuccessResponse()()
Esempio n. 10
0
def forget_password_request():
    schema = ResetEmailValSchema(strict=True)
    email = schema.load(request.get_json()).data['email']
    user = User.query.filter_by(email=email).first()
    if not user:
        return ErrorResponse(USER_NOT_EXIST).make()
    token = generate_token(user.id, reset_password_token_key, config.RESET_TOKEN_EXPIRE_TIME)
    forget_url = config.FRONT_RESET_EMAIL_URL
    send_email(email, '重置你的密码', 'email/reset_password.html', user=user, token=token, forget_url=forget_url)
    return SuccessResponse(Accepted)()
Esempio n. 11
0
def save_to_gifts(isbn):
    if is_isbn_or_key(isbn):
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    if not yushu_book.first:
        return ErrorResponse(BOOK_ISBN_ERROR).make()
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.get(uid)
    if user.can_save_to_list(isbn):
        with db.auto_commit():
            gift = Gift()
            gift.isbn = isbn
            gift.user_id = user.id
            user.beans += Decimal(0.5).quantize(Decimal('0.00'))
            db.session.add(gift)
    else:
        return ErrorResponse(SAVE_BOOK_ERROR).make()
    return SuccessResponse()()
Esempio n. 12
0
def redraw_from_gifts(gid):
    uid = getattr(g, REQUEST_USER_ID)
    user = User.query.get_or_404(uid)
    gift = Gift.query.filter_by(id=gid, launched=False, user_id=uid).first_or_404()
    drift = Drift.query.filter_by(gift_id=gid, pending=PendingStatus.Waiting.value).first()
    if drift:
        return ErrorResponse(REDRAW_GIFT_ERROR).make()
    with db.auto_commit():
        user.beans -= Decimal(0.5).quantize(Decimal('0.00'))
        gift.is_deleted = True
    return SuccessResponse()()
Esempio n. 13
0
def forget_password(token):
    schema = ForgetPasswordValSchema(strict=True)
    password = schema.load(request.get_json()).data['password']
    payload = decode_token(token)
    # 验证token一致性
    redis_key = reset_password_token_key.format(payload['uid'])
    token_from_redis = redis.get(redis_key)
    if check_token(token, token_from_redis):
        User.reset_password(payload['uid'], password)
        redis.delete(redis_key)
        return SuccessResponse(NotContent)()
    else:
        return ErrorResponse(TOKEN_INVALID).make()
Esempio n. 14
0
def before_request():
    logger.debug("request ip: %s, path: %s, args: %s, body: %s",
                 request.remote_addr, request.path, request.args,
                 request.data.decode('utf-8'))
    if request.method == 'OPTIONS':
        return SuccessResponse()()
    login_urls = set(
        [url.decode('utf-8') for url in redis.smembers(login_url_key)])
    try:
        if request.endpoint.split('.')[-1] in login_urls:
            return check_request_token()
    except AttributeError as err:
        logger.error(err)
        return ErrorResponse(ENDPOINT_NOT_EXIST).make()
Esempio n. 15
0
def default_handler(e):
    logger.exception(e)
    return ErrorResponse(ServerError).make()
Esempio n. 16
0
def default_handler(e):
    if isinstance(e, HTTPException):
        logger.error(e)
        return ErrorResponse(ErrorCode(http=e.code, message=e.name)).make()