예제 #1
0
def create_user():
    data = request.get_json()
    if not data:
        return bad_request('You must post JSON data')
    message = {}
    if 'username' not in data or not data.get('username', None):
        message['username'] = '******'
    pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'
    if 'email' not in data or not re.match(pattern, data.get('email', None)):
        message['email'] = 'Please provide a valid email address.'
    if 'password' not in data or not data.get('password', None):
        message['password'] = '******'
    if User.query.filter_by(username=data.get('username', None)).first():
        message['username'] = '******'
    if User.query.filter_by(email=data.get('email', None)).first():
        message['email'] = 'Please provide a different email'
    if message:
        return bad_request(message)
    user = User()
    user.from_dict(data, new_user=True)
    db.session.add(user)
    db.session.commit()
    response = jsonify(user.to_dict())
    response.status_code = 201
    # HTTP协议要求201响应包含一个值为新资源URL的Location头部
    response.headers['Location'] = url_for('api.get_user', id=user.id)
    return response
예제 #2
0
def updata_role(id):
    """修改一个角色"""
    role = Role.query.get_or_404(id)
    json_data = request.json
    if not json_data:
        return bad_request("You must post a Json data")

    # 校验数据
    message = {}
    if 'slug' not in json_data or not json_data.get('slug'):
        message['slug'] = 'Please provide a valid slug'
    if 'name' not in json_data or not json_data.get('name'):
        message['name'] = 'Please provide a valid name'

    r = Role.query.filter_by(slug=json_data.get('slug', None)).first()

    if r and r.id != role.id:
        print(r.id)
        print(role.id)
        message['slug'] = 'Please use a different slug'
    if message:
        return bad_request(message)

    permission = 0

    for perm in json_data.get('permission', 0):
        permission += perm

    role.from_dict(json_data)
    db.session.commit()
    return jsonify(role.to_dict())
예제 #3
0
def create_post():
    """创建一篇文章"""
    json_data = request.json
    if not json_data:
        return bad_request('You must post Json data')
    message = {}
    if 'title' not in json_data and not json_data.get('title'):
        message['title'] = 'Title is required.'
    elif len(json_data.get('title')) > 255:
        message['title'] = 'Title must less than 255 characters.'
    if 'body' not in json_data and not json_data.get('body'):
        message['body'] = 'Body is required'

    if message:
        return bad_request(message)

    # 构建post对象

    post = Post()
    post.from_dict(json_data)
    post.author = g.current_user  # 通过 auth.py 中 verify_token() 传递过来的(同一个request中,需要先进行 Token 认证)
    db.session.add(post)
    db.session.commit()
    response = jsonify(post.to_dict())
    response.status_code = 201
    # HTTP协议要求201响应包含一个值为新资源URL的Location头部
    response.headers['Location'] = url_for('api.get_post', id=post.id)
    return response
def create_message():
    """发送一条私信"""
    json_data = request.json

    if not json_data:
        return bad_request('You must post JSON data')
    if 'body' not in json_data and not json_data.get('body'):
        return bad_request('body is required')
    if 'recipient_id' not in json_data and not json_data.get('recipient_id'):
        return bad_request('recipient_id is required')

    user = User.query.get_or_404(json_data['recipient_id'])
    if g.current_user == user:
        return bad_request('You cannot send private message to yourself.')
    if user.is_blocking(g.current_user):
        return bad_request('You are in the blacklist of {}'.format(user.name if user.name else user.username))

    message = Message()
    message.from_dict(json_data)
    message.sender = g.current_user
    message.recipient = user
    db.session.add(message)
    db.session.commit()

    user.add_notification('unread_messages_count',user.new_recived_messages())

    response = jsonify(message.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_message', id=message.id)

    return response
예제 #5
0
def update_user(id):
    user = User.query.get_or_404(id)
    data = request.get_json()
    if not data:
        return bad_request("you must post JSON data.")
    message = {}
    if 'username' in data and not data.get('username', None):
        message['username'] = '******'

    pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'
    if 'email' in data and not re.match(pattern, data.get('email', None)):
        message['email'] = 'Please provide a valid email address.'

    if 'username' in data and data['username'] != user.username and \
            User.query.filter_by(username=data['username']).first():
        message['username'] = '******'
    if 'email' in data and data['email'] != user.email and \
            User.query.filter_by(email=data['email']).first():
        message['email'] = 'Please use a different email address.'

    if message:
        return bad_request(message)

    user.from_dict(data, new_user=False)
    db.session.commit()
    return jsonify(user.to_dict())
예제 #6
0
def login():
    data = request.get_json() or {}
    if 'username' not in data or 'password' not in data:
        return bad_request('参数错误')
    user = User.query.filter_by(username=data['username']).first()
    if user is None or not user.check_password(data['password']):
        return bad_request('密码或用户名错误')
    return jsonify({"userinfo": user.to_dict(), "token": user.encoded_token()})
예제 #7
0
def reset_password_request():
    """请求重置密码,需要填写时的邮箱"""
    json_data = request.json
    if not json_data:
        return bad_request("You must post Json data")
    message = {}

    if 'confirm_email_base_url' not in json_data.get(
            'confirm_email_base_url').strip():
        message[
            'confirm_email_base_url'] = "Plase provide a valid confirm email base url"
    pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'
    if 'email' not in json_data and re.match(pattern, json_data.get('email')):
        message['email'] = "Please provide a valid email address."

    if message:
        return bad_request(message)

    user = User.query.filter_by(email=json_data.get('email')).first()
    if g.current_user != user:
        return bad_request("Please provide a valid email address")
    if user:
        token = user.generate_reset_password_jwt()
        text_body = '''
                Dear {0},
                To reset your password click on the following link: {1}
                If you have not requested a password reset simply ignore this message.
                Sincerely,
                The Madblog Team
                Note: replies to this email address are not monitored.
                '''.format(user.username,
                           json_data.get('confirm_email_base_url') + token)
        html_body = '''
                <p>Dear {0},</p>
                <p>To reset your password <a href="{1}">click here</a>.</p>
                <p>Alternatively, you can paste the following link in your browser's address bar:</p>
                <p><b>{1}</b></p>
                <p>If you have not requested a password reset simply ignore this message.</p>
                <p>Sincerely,</p>
                <p>The Madblog Team</p>
                <p><small>Note: replies to this email address are not monitored.</small></p>
                '''.format(user.username,
                           json_data.get('confirm_email_base_url') + token)

        send_email('[Madblog] Reset Your Password',
                   sender=current_app.config['MAIL_SENDER'],
                   recipients=[user.username],
                   text_body=text_body,
                   html_body=html_body)

        return jsonify({
            'status':
            'success',
            'message':
            'An email with instructions to reset your password has been sent to you.'
        })
예제 #8
0
def follow(id):
    """关注用户一个用户"""
    user = User.query.get_or_404(id)
    if g.current_user == user:
        return bad_request("You cannot follow youself")
    if g.current_user.is_following(user):
        return bad_request("You have already followed that user")
    g.current_user.follow(user)
    db.session.commit()
    return jsonify({
        'status': 'success',
        'message': 'you are now following {}'.format(id)
    })
예제 #9
0
def unfollow(id):
    """取消关注一个用户"""
    user = User.query.get_or_404(id)
    if g.current_user == user:
        return bad_request('You cannot follow yourself.')
    if not g.current_user.is_following(user):
        return bad_request('You are not following this user.')
    g.current_user.unfollow(user)
    db.session.commit()
    return jsonify({
        'status': 'success',
        'message': 'You are not following {} anymore.'.format(id)
    })
예제 #10
0
def create_user():
    data = request.get_json() or {}
    if 'username' not in data or 'email' not in data or 'password' not in data:
        return bad_request('参数错误')
    if User.query.filter_by(username=data['username']).first():
        return bad_request('该用户名已被注册')
    if User.query.filter_by(username=data['email']).first():
        return bad_request('邮箱已被注册')
    user = User(username=data['username'], email=data['email'])
    user.set_password(data['password'])
    db.session.add(user)
    db.session.commit()
    return jsonify(user.to_dict())
예제 #11
0
def add_slot_i(iid):
    t_from = request.args.get('t_from', -1)
    t_to = request.args.get('t_to', -1)
    if Interviewer.check_existence_by_id(iid):
        if is_slot_legal(t_from, t_to):
            t_from = int(t_from)
            t_to = int(t_to)
            Interviewer.add_slot_by_id(iid, t_from, t_to)
            slots = Interviewer.get_slots_by_id(iid)
            return api_encoder(slots)
        else:
            return bad_request('Slot is illegal')
    else:
        return bad_request('Interviewer not exists')
예제 #12
0
def add_slot_c(cid):
    t_from = request.args.get('t_from', -1)
    t_to = request.args.get('t_to', -1)
    if Candidate.check_existence_by_id(cid):
        if is_slot_legal(t_from, t_to):
            t_from = int(t_from)
            t_to = int(t_to)
            Candidate.add_slot_by_id(cid, t_from, t_to)
            slots = Candidate.get_slots_by_id(cid)
            return api_encoder(slots)
        else:
            return bad_request('Slot is illegal')
    else:
        return bad_request('Candidate not exists')
예제 #13
0
def get_matching_for_candidate(cid):
    iids_raw = request.args.get('iids', [])
    iids = api_decoder(iids_raw)
    if Candidate.check_existence_by_id(cid):
        if type(iids) is list and len(iids) > 0:
            if Interviewer.check_all_existence_by_id(iids):
                print(cid, iids)
                ms = Candidate.get_matching_by_id(cid, iids)
                print(ms)
                return api_encoder(ms)
    else:
        return bad_request('Candidate not exists')

    return bad_request('Iids is illegal')
예제 #14
0
def confirm(token):
    """确认邮箱是有效的"""
    if g.current_user.confirmed:
        return bad_request('You have already confirmed your account.')
    if g.current_user.verify_confirm_jwt(token):
        g.current_user.ping()
        db.session.commit()
        token = g.current_user.get_jwt()
        return jsonify({
            'status': 'success',
            'message': 'You have confirmed your account. Thanks!',
            'token': token
        })
    else:
        return bad_request('The confirmation link is invalid or has expired.')
예제 #15
0
def update_message(id):
    """修改一条私信"""
    message = Message.query.get_or_404(id)
    if g.current_user != message.sender:
        return error_response(403)
    json_data = request.json

    if not json_data:
        return bad_request('You must post JSON data.')
    if 'body' not in json_data or not json_data.get('body'):
        return bad_request('Body is required.')

    message.from_dict(json_data)
    db.session.commit()

    return jsonify(message.to_dict())
예제 #16
0
def unblock(id):
    """解除拉黑一个用户"""
    user = User.query.get_or_404(id)
    if g.current_user == user:
        return bad_request('You cannot unblock yourself.')
    if not g.current_user.is_blocking(user):
        return bad_request('You are not blocking this user.')

    g.current_user.unblock(user)
    db.session.commit()

    return jsonify({
        'status':
        'success',
        'message':
        'You are now unblocking {}'.format(
            user.name if user.name else user.username)
    })
예제 #17
0
def block(id):
    """拉黑一个用户"""
    user = User.query.get_or_404(id)
    if g.current_user == user:
        return bad_request('You cannot block yourself.')
    if g.current_user.is_blocking(user):
        return bad_request('You have already blocked that user')

    g.current_user.block(user)
    db.session.commit()

    return jsonify({
        'status':
        'success',
        'message':
        "You are now blocking {}".format(
            user.name if user.name else user.username)
    })
예제 #18
0
def send_messages():
    """群发短信"""
    if g.current_user.get_task_in_process('send_messages'):
        return bad_request('上一个群发私信的后台任务尚未结束')
    else:
        json_data = request.json
        if not json_data:
            return bad_request('You must post Json data.')
        if 'body' not in json_data and not json_data.get('body'):
            return bad_request({'message': 'Body is required'})

        g.current_user.lanuch_tasks('send_messages',
                                    '....正在群发短信',
                                    kwrags={
                                        'user_id': g.current_user.id,
                                        'body': json_data.get('body')
                                    })
        return jsonify(message='正在运行群发私信后台任务')
예제 #19
0
def create_user():
    data = request.get_json() or {
    }  # request.get_json() extract the JSON from the request and return it as python structure
    # ensure that I've got all the information
    if 'firstname' not in data or 'lastname ' not in data or 'email' not in data or 'password' not in data:
        return bad_request('must include firstname, lastname, email, password'
                           )  # return error to client
    if User.query.filter_by(email=data['email']).first():
        return bad_request('please use a different email ! ')
    user = User()
    user.form_dict(data,
                   new_user=True)  # new_user: to accepts the password filed
    db.session.add(user)
    db.seesion.commit()
    response = jsonify(user.to_dict())
    response.status_code = 201
    response.headers['Location'] = url_for('api.get_user', id=user.id)
    return response
예제 #20
0
def update_user(id):
    user = User.query.get_or_404(id)
    data = request.get_json() or {}
    if 'username' not in data or 'email' not in data:
        return bad_request('参数错误')
    setattr(user, 'email', data['email'])
    setattr(user, 'username', data['username'])
    db.session.commit()
    return jsonify(user.to_dict())
예제 #21
0
def update_user(id):
    user = User.query.get_or_404(id)
    data = request.get_json() or {}

    if 'email' in data and data['email'] != user.email and \
            User.query.filter_by(email=data['email']).first():
        return bad_request('please use a different email address')
    user.form_dict(data, new_user=False)
    db.session.commit()
    return jsonify(user.to_dict())
예제 #22
0
def reset_password(token):
    '''用户点击邮件中的链接,通过验证 JWT 来重置对应的账户的密码'''
    json_data = request.json
    if not json_data:
        return bad_request('You must post JSON data.')
    if 'password' not in json_data:
        return bad_request('Please provide a valid password')

    user = User.verify_reset_password_jwt(token)
    if not user:
        return bad_request(
            'The reset password link is invalid or has expired.')

    user.password = json_data.get('password')
    db.session.commit()

    return jsonify({
        'status': 'success',
        'message': 'You password has been reset.'
    })
예제 #23
0
def get_user_history_messages(id):
    """获取用户与某人的消息记录"""
    user = User.query.get_or_404(id)
    if g.current_user != user:
        return error_response(403)
    page = request.args.get('page', 1, type=int)
    per_page = min(
        request.args.get('per_page',
                         current_app.config['MESSAGES_PER_PAGE'],
                         type=int), 100)
    from_id = request.args.get('from', type=int)
    if not from_id:
        return bad_request("You must provide the user id of opposite site")
    # 对方发给我的message
    q1 = Message.query.filter(Message.sender_id == from_id,
                              Message.recipient_id == user.id)
    # 我给对方发送的message
    q2 = Message.query.filter(Message.sender_id == user.id,
                              Message.recipient_id == from_id)
    # 按时间正序排序
    history_messages = q1.union(q2).order_by(Message.timestamp)
    data = Message.to_collection_dict(history_messages,
                                      page,
                                      per_page,
                                      'api.get_user_history_messages',
                                      id=id)
    recived_message = [
        item for item in data['items'] if item['sender']['id'] != id
    ]
    sent_message = [
        item for item in data['items'] if item['sender']['id'] == id
    ]
    last_read_time = user.last_messages_read_time or datetime(1900, 0, 0)
    new_count = 0
    for item in recived_message:
        if item['timestamp'] > last_read_time:
            item['is_new'] = True
            new_count += 1
    # 未读的私信个数
    if new_count > 0:
        user.last_messages_read_time = recived_message[-1]['timestamp']
        db.session.commit()

        user.add_notification('unread_message_count',
                              user.new_recived_messages())
        db.session.commit()

    messages = recived_message + sent_message
    messages.sort(key=data['items'].index)

    data['items'] = messages
    return jsonify(data)
예제 #24
0
def update_comment(id):
    """修改单个评论"""
    comment = Comment.query.get_or_404(id)
    if g.current_user != comment.author and g.current_user != comment.post.author:
        return error_response(403)
    json_data = request.json
    if not json_data:
        return bad_request('You must post JSON data.')

    comment.from_dict(json_data)

    db.session.commit()
    return jsonify(comment.to_dict())
예제 #25
0
def create_comment():
    """发布一条评论"""
    json_data = request.json
    if not json_data:
        return bad_request('You must post JSON data.')
    if 'body' not in json_data or not json_data.get('body').strip():
        return bad_request('Body is required.')
    if 'post_id' not in json_data or not json_data.get('post_id'):
        return bad_request('Post id is required.')

    post = Post.query.get_or_404(int(json_data.get('post_id')))

    comment = Comment()
    comment.from_dict(json_data)
    comment.author = g.current_user
    comment.post = post
    db.session.add(comment)
    db.session.commit()
    # 获取当前评论所有的祖先评论的作者
    users = set()
    users.add(comment.post.author)
    if comment.parent:
        ancestors_authors = {c.author for c in comment.get_ancestors()}
        users = users | ancestors_authors
    # 给所有的祖先评论作者发送通知
    for u in users:
        u.add_notification('unread_recived_comments_count',
                           u.new_recived_comments())
    db.session.commit()

    response = jsonify(comment.to_dict())
    response.status_code = 201

    # 201响应的请求头中要包含一个location
    response.headers['Location'] = url_for('api.get_comment', id=comment.id)
    # 给用户发送新评论的通知
    post.author.add_notification('unread_recived_comments_count',
                                 post.author.new_recived_comments())
    return response
예제 #26
0
 def wrapper(*args, **kw):
     print('---', req.headers['Authorization'])
     if req.headers['Authorization']:
         token = req.headers['Authorization'].split(' ')[1]
         try:
             data = jwt.decode(bytes(token, encoding="utf8"),
                               Config.SECRET_KEY,
                               algorithms="HS256")
             g.state = data
             return func(*args, **kw)
         except Exception as e:
             print(e)
             return bad_request(str(e))
예제 #27
0
def update_post(id):
    """更新一篇文章"""
    post = Post.query.get_or_404(id)
    if g.current_user.id != post.author_id:
        return error_response(403)
    json_data = request.json

    if not json_data:
        return bad_request("you must post Json data")
    message = {}
    if 'title' not in json_data and not json_data.get("title"):
        message["title"] = "title is required"
    elif len(json_data["title"]) > 255:
        message["title"] = "title must less than 255"
    if "body" not in json_data and not json_data.get("body"):
        message["body"] = "body is required"
    if message:
        return bad_request(message)

    post.from_dict(json_data)
    db.session.add(post)
    db.session.commit()
    return jsonify(post.to_dict())
예제 #28
0
def update_user(id):
    """修改单个用户"""
    user = User.query.get_or_404(id)
    json_data = request.json

    if not json_data:
        return bad_request('you must Post a data')

    message = dict()

    if 'username' in json_data and not json_data.get('username', None):
        message['username'] = '******'

    pattern = re.compile(
        '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'
    )

    if 'email' in json_data and not re.match(pattern,
                                             json_data.get('email', None)):
        message['email'] = 'Please provide a valid email address'

    if 'username' in json_data and json_data['username'] != user.username and \
            User.query.filter_by(username=json_data.get('username', None)).first():
        message['username'] = '******'

    if 'email' in json_data and json_data['email'] != user.email and \
            User.query.filter_by(email=json_data.get('email', None)).first():
        message['username'] = '******'

    if message:  # 返回错误信息
        return bad_request(message)

    # 修改模型属性并提交
    user.from_dict(data=json_data)
    db.session.commit()

    return jsonify(user.to_dict())
예제 #29
0
def create_roles():
    """创建角色"""
    json_data = request.json
    if json_data is None:
        return bad_request('You must Post JSON data')

    # 校验数据
    message = {}
    if 'slug' not in json_data or not json_data.get('slug'):
        message['slug'] = 'Please provide a valid slug'
    if 'name' not in json_data or not json_data.get('name'):
        message['name'] = 'Please provide a valid name'
    if Role.query.filter_by(slug=json_data.get('slug', None)).first():
        message['slug'] = 'Please use a different slug.'

    if message:
        return bad_request(message)

    permission = 0

    for perm in json_data.get('permission', 0):
        permission += perm

    json_data['permission'] = permission

    role = Role()
    role.from_dict(json_data)

    db.session.add(role)
    db.session.commit()

    response = jsonify({role.to_dict()})

    response.status_code = 201
    response.headers['Location'] = url_for('api.get_roles', id=role.id)

    return response
예제 #30
0
def create_user():
    """创建一个用户"""
    json_data = request.json  # 接收请求数据
    if not json_data:
        return bad_request('You must post Json data')

    message = {}  # 设置错误消息
    if 'username' not in json_data or not json_data.get('username', None):
        message['username'] = '******'
    # 邮箱正则匹配
    pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'
    if 'email' not in json_data or not re.match(pattern,
                                                json_data.get('email', None)):
        message['email'] = 'please provide a email address'

    if 'password' not in json_data or not json_data.get('password', None):
        message['password'] = '******'

    if User.query.filter_by(username=json_data.get('username', None)).first():
        message['username'] = '******'

    if User.query.filter_by(email=json_data.get('email', None)).first():
        message['email'] = 'Please use a different email address.'

    # 返回错误消息
    if message:
        return bad_request(message)

    user = User()
    user.from_dict(data=json_data, new_user=True)  # 注册用户数据

    db.session.add(user)
    db.session.commit()  # 保存至数据库

    token = user.generate_confirmed_jwt()
    if not json_data.get('confirm_email_base_url'):
        confirm_url = 'http://127.0.0.1:5000/api/confirm/' + token
    else:
        confirm_url = json_data.get('confirm_email_base_url')

    text_body = '''
        Dear {},
        Welcome to Madblog!
        To confirm your account please click on the following link: {}
        Sincerely,
        The Madblog Team
        Note: replies to this email address are not monitored.
        '''.format(user.username, confirm_url)

    html_body = '''
        <p>Dear {0},</p>
        <p>Welcome to <b>Madblog</b>!</p>
        <p>To confirm your account please <a href="{1}">click here</a>.</p>
        <p>Alternatively, you can paste the following link in your browser's address bar:</p>
        <p><b>{1}</b></p>
        <p>Sincerely,</p>
        <p>The Madblog Team</p>
        <p><small>Note: replies to this email address are not monitored.</small></p>
        '''.format(user.username, confirm_url)

    send_email('[Madblog] Confirm Your Account',
               sender=current_app.config['MAIL_SENDER'],
               recipients=[user.email],
               text_body=text_body,
               html_body=html_body)

    response = jsonify(user.to_dict())
    response.status_code = 201
    # HTTP协议要求201响应包含一个值为新资源URL的Location头部
    response.headers['Location'] = url_for('api.get_user', id=user.id)

    return response