Ejemplo n.º 1
0
def all():
    u = current_user()
    uid = u.id
    todos = Todo.all_todos(user_id=uid)
    todos_dict = []
    for t in todos:
        todo = {
            'id': t.id,
            'title': t.title,
            'user_id': t.user_id,
            'created_time': t.created_time,
            'updated_time': t.updated_time,
        }
        todos_dict.append(todo)
    return jsonify(todos_dict)
Ejemplo n.º 2
0
def index():
    send_mail_result = session.pop('send_mail_result', None)
    send_mail_success = session.pop('send_mail_success', False)

    u = current_user()
    send_mails = Mail.all(sender_id=u.id)
    receive_mails = Mail.all(receiver_id=u.id)
    csrf_token = make_csrf_token(u)
    return render_template('mail/index.html',
                           u=u,
                           send_mails=send_mails,
                           receive_mails=receive_mails,
                           csrf_token=csrf_token,
                           s_m_r=send_mail_result,
                           s_m_s=send_mail_success)
Ejemplo n.º 3
0
def avatar_add():
    file: FileStorage = request.files['avatar']
    suffix = file.filename.split('.')[-1]
    if suffix not in ['gif', 'jpg', 'jpeg', 'png']:
        abort(400)
        log('不接受的后缀, {}'.format(suffix))
    else:
        filename = '{}.{}'.format(str(uuid.uuid4()), suffix)
        path = os.path.join('images', filename)
        file.save(path)

        u = current_user()
        User.update(u.id, image='/images/{}'.format(filename))

        return redirect(url_for('.profile'))
Ejemplo n.º 4
0
Archivo: user.py Proyecto: zen-yang/bbs
def image_add():
    file = request.files['avatar']

    suffix = file.filename.split('.')[-1]
    filename = '{}.{}'.format(str(uuid.uuid4()), suffix)
    path = os.path.join('images', filename)
    file.save(path)

    u = current_user()
    id = u.id
    images = dict(image='/images/{}'.format(filename), )
    m = User.update(id, **images)
    flash('头像修改成功')

    return redirect(url_for('.setting'))
Ejemplo n.º 5
0
 def f(request):
     log('same_user_required')
     u = current_user(request)
     if 'id' in request.query:
         comment_id = request.query['id']
     else:
         form = request.json()
         comment_id = int(form['id'])
     w = Comment.one(id=int(comment_id))
     z = Weibo.one(id=w.weibo_id)
     if w.user_id == u.id or u.id == z.user_id:
         return route_function(request)
     else:
         d = dict(message="权限不足")
         return json_response(d)
Ejemplo n.º 6
0
    def f(request):
        log('weibo_owner_required')
        u = current_user(request)
        method = request.method
        if method == 'POST':
            weibo_id = request.form()['id']
        else:
            weibo_id = request.query['id']
        log('*** weibo_owner_required *** weibo_id <{}>'.format(weibo_id))
        w = Weibo.one(id=int(weibo_id))

        if w.user_id == u.id:
            return route_function(request)
        else:
            return redirect('/weibo/index')
Ejemplo n.º 7
0
def profile():
    u = current_user()
    if u is None:
        return redirect(url_for('.index'))
    else:
        user_topics = Topic.all_current_user_topic(u.id)
        replied_topics = Topic.all_replied_topic(u.id)
        # for t in user_topics:
        #     u = t.last_reply_user()
        #     print('last reply user', u, u.image)
        board_id = int(request.args.get('board_id', -1))
        return render_template('profile.html',
                               user=u,
                               ms=user_topics,
                               rs=replied_topics,
                               bid=board_id)
Ejemplo n.º 8
0
def add_img():
    # file 是一个上传的文件对象
    file = request.files['avatar']
    suffix = file.filename.split('.')[-1]
    if valid_suffix(suffix):
        # 上传的文件用 secure_filename 函数过滤一下名字
        # 防止这情况:../../../../../../../root/.ssh/authorized_keys
        # filename = secure_filename(file.filename)
        filename = '{}.{}'.format(str(uuid.uuid4()), suffix)
        file.save(os.path.join('static/user_image', filename))
        u = current_user()

        User.update(u.id, dict(
            user_image='/static/user_image/{}'.format(filename)
        ))
    return redirect(url_for("index.user_detail", id=u.id))
Ejemplo n.º 9
0
def edit(request):
    headers = {'Content-Type': 'text/html'}
    uname = current_user(request)
    user = User.find_by(username=uname)
    todo = Todo.find_by(id=int(request.query.get('id', -1)))
    log('todo: ', todo, todo.user_id)
    if user.id != todo.user_id:
        return redirect('/todo')
    header = response_with_headers(headers)
    body = template('todo_edit.html')
    body = body.replace('{{todo_id}}',
                        str(todo.id)).replace('{{todo_title}}',
                                              str(todo.title))
    response = header + '\r\n' + body

    return response.encode('utf-8')
Ejemplo n.º 10
0
def add_img():
    # file 是一个上传的文件对象
    file = request.files['avatar']
    suffix = file.filename.split('.')[-1]
    if valid_suffix(suffix):
        # 上传的文件一定要用 secure_filename 函数过滤一下名字
        # ../../../../../../../root/.ssh/authorized_keys
        # filename = secure_filename(file.filename)
        filename = '{}.{}'.format(str(uuid.uuid4()), suffix)
        print('avatar path',
              os.path.join(config.basedir + '/user_image', filename))
        file.save(os.path.join(config.basedir + '/user_image', filename))
        u = current_user()
        u.update(dict(user_image='/uploads/{}'.format(filename)))

    return redirect(url_for(".profile"))
Ejemplo n.º 11
0
def sweep():
    """清理所有已读信息"""
    u = current_user()
    owner_id = int(request.form.get('owner_id', -1))
    owner = cached_user_id2user(owner_id)
    if owner is not None:
        if owner_id == u.id:
            read_infos = Info.all(receiver_id=owner_id, been_read=True)
            with data_cache.pipeline(transaction=False) as pipe:
                for i in read_infos:
                    Info.delete(i)
                    key = 'user_id_{}.received_info'.format(u.id)
                    pipe.delete(key)
                pipe.execute()

    return redirect(url_for('.info'))
Ejemplo n.º 12
0
def topic_content(topic_id):
    topic = add_read_num(topic_id)
    replys = Reply.all(topic_id=topic_id)
    u = current_user()
    if not u.is_guest():
        token = Csrf.one(user_id=u.id).csrf_token
    else:
        token = ''

    response = make_response(
        render_template('detail.html',
                        topic=topic,
                        replys=replys,
                        user=u,
                        token=token))
    return response
Ejemplo n.º 13
0
def avatar_add():
    u = current_user()
    token = request.args['token']
    # if token in csrf_tokens and csrf_tokens[token] == u.id:
    if r.exists(token) and int(r.get(token).decode()) == u.id:
        file: FileStorage = request.files['avatar']
        suffix = file.filename.split('.')[-1]
        filename = '{}.{}'.format(str(uuid.uuid4()), suffix)
        path = os.path.join('static/images', filename)
        file.save(path)
        User.update(u.id, image='/static/images/{}'.format(filename))
        # return render_template('profile.html', user=u)
        r.delete(token)
        return redirect(url_for('.profile'))
    else:
        return 'CSRF攻击'
Ejemplo n.º 14
0
def add_img():
    # file 上传
    file = request.files['avatar']
    suffix = file.filename.split('.')[-1]
    if valid_suffix(suffix):
        # 上传文件的名字要处理一下
        # flask也有自带的 secure_filename 函数过滤
        # filename = secure_filename(file.filename)
        filename = '{}.{}'.format(str(uuid.uuid4()), suffix)
        file.save(os.path.join('user_image', filename))
        u = current_user()
        User.update(u.id, dict(
            user_image='/uploads/{}'.format(filename)
        ))

    return redirect(url_for(".setting"))
Ejemplo n.º 15
0
def index():
    """
    weibo 首页的路由函数
    """
    # u = current_user()
    # weibos = Weibo.all(user_id=u.id)
    # # 替换模板文件中的标记字符串
    # return html_response('weibo_index.html', weibos=weibos, user=u)
    if 'id' in request.args:
        user_id = int(request.args['id'])
        u = User.one(id=user_id)
    else:
        u = current_user()

    weibos = Weibo.all(user_id=u.id)
    return render_template('weibo_index.html', weibos=weibos, user=u)
Ejemplo n.º 16
0
def update():
    token = request.args.get('token')
    form = request.form
    id = int(form.get('id', -1))
    name = form.get('name', '')
    u = current_user()
    t = get_token(u.id)
    if t.content == token and '' != name:
        flash_token(t)
        b = Theme.find(id)
        log('update board 用户是', u.id, u.username, b)
        b.name = name
        b.save()
        return redirect(url_for('board.edit'))
    else:
        abort(403)
Ejemplo n.º 17
0
 def f():
     if 'id' in request.args:
         log('if true', request.args)
         comment_id = int(request.args['id'])
     else:
         log('if false')
         form: dict = request.json
         comment_id = int(form.get('id'))
     u = current_user()
     c = Comment.find_by(id=comment_id)
     w = Weibo.find_by(id=c.weibo_id)
     if c.user_id == u.id or w.user_id == u.id:
         return route_function()
     else:
         d = dict(remove=False, message="权限不足")
         return jsonify(d)
Ejemplo n.º 18
0
def view(id):
    message: Messages = Messages.one(id=id)
    u = current_user()
    is_sender = u.id == message.sender_id
    is_receiver = u.id == message.receiver_id
    if is_receiver or is_sender:

        if is_receiver and not message.been_read:
            message.been_read = True
            message.save()
            key = 'message_id_{}.message'.format(message.id)
            data_cache.delete(key)

        return render_template('mail/detail.html', message=message, user=u)
    else:
        return abort(404)
def login_view(request):
    u = current_user(request)
    result = request.query.get('result', '')
    result = unquote_plus(result)

    if u is not None:
        username = u.username
    else:
        username = User.guest().username

    body = RenderTemplate.render(
        'login.html',
        username=username,
        result=result,
    )
    return html_response(body)
Ejemplo n.º 20
0
def user_detail(id):
    now_time = int(time.time())
    u = User.one(id=id)
    cu = current_user()
    if u is None:
        abort(404)
    else:
        diff = now_time - int(u.created_time)
        diff = round(diff / 60 / 60)
        print(now_time, u.created_time, diff)
        return render_template(
            'profile.html',
            user=cu,
            other=u,
            # time=now_time - u.created_time)
            time=diff)
Ejemplo n.º 21
0
def index():
    form = request.args
    board_id = form.get('board_id', -1)
    board_id = int(board_id)

    if board_id == -1:
        # 访问主页,显示所有的ts
        ts = Topic.all()
    else:
        # 返回版块下的ts,无论board_id是否有效都能处理
        ts = Topic.all(board_id=board_id)

    u = current_user()
    bs = Board.all()
    # 传入board_id是为了让点击的版块呈现选中的效果
    return render_template("index.html", ts=ts, u=u, bs=bs, board_id=board_id)
Ejemplo n.º 22
0
def login(request):
    """
    登录页面的路由函数
    """
    log('login, headers', request.headers)
    log('login, cookies', request.cookies)
    user_current = current_user(request)
    log('current user', user_current)
    form = request.form()
    user, result = User.login(form)
    if user.is_guest():
        return redirect('/user/login/view?result={}'.format(result))
    else:
        session_id = Session.add(user_id=user.id)
        return redirect('/user/login/view?result={}'.format(result),
                        session_id)
Ejemplo n.º 23
0
def login():
	session.clear()
	if request.method == 'POST':
		form = request.form
		username = form.get('username')
		password = form.get('password')
		if User.validate_login(username, password):
			u = User.find_by(username=username)
			session['user_id'] = u.id
			returnurl = request.args.get('returnurl')
			flash('You were successfully logged in!', 'success')
			return redirect(returnurl or url_for('main.index'))
		else:
			flash('Invalid username or password!', 'danger')
	u = current_user()
	return render_template('login.html', username=u.username)
Ejemplo n.º 24
0
def add():
    # 发电子邮件
    form = request.form.to_dict()
    form['receiver_id'] = int(form['receiver_id'])
    u = current_user()
    form['sender_id'] = u.id

    r = User.one(id=form['receiver_id'])
    m = Message(subject=form['title'],
                body=form['content'],
                sender=admin_mail,
                recipients=[r.email])
    mail.send(m)

    m = Messages.new(form)
    return redirect(url_for('.index'))
Ejemplo n.º 25
0
Archivo: index.py Proyecto: Auraxc/web
def profile():
    u = current_user()
    if u is None:
        return redirect(url_for('.index'))
    else:
        # 获取发布的 topic
        topic = created_topic(u.id)
        # 获取参与的 topic
        replied = replied_topic(u.id)

        return render_template(
            'profile.html',
            user=u,
            topic=topic,
            replied=replied,
        )
Ejemplo n.º 26
0
def index():
    board_id = request.args.get("board_id", -1)
    if board_id == -1:
        ts = Topic.all()
    else:
        ts = Topic.find_all(board_id=board_id)
    bs = Board.all()
    u = current_user()
    # log("u: ", u)
    # log("type of u: ", type(u))
    if u is not None:
        token = str(uuid.uuid4())
        csrf_tokens[token] = u._id
        return render_template("topic/index.html", ts=ts, token=token, bs=bs)
    else:
        return render_template("topic/index.html", ts=ts, bs=bs)
Ejemplo n.º 27
0
def avatar_add():
    file: FileStorage = request.files['avatar']
    # file = request.files['avatar']
    # filename = file.filename
    # ../../root/.ssh/authorized_keys
    # images/../../root/.ssh/authorized_keys
    # filename = secure_filename(file.filename)
    suffix = file.filename.split('.')[-1]
    filename = '{}.{}'.format(str(uuid.uuid4()), suffix)
    path = os.path.join('images', filename)
    file.save(path)

    u = current_user()
    User.update(u.id, image='/images/{}'.format(filename))

    return redirect(url_for('.setting'))
Ejemplo n.º 28
0
def profile(username):
    user = current_user()
    u = User.one(username=username)
    if u == user:
        t = created_topic(u.id)
        topics = [i for i in reversed(t)]
        r = Reply.all(user_id=u.id)
        for i in r:
            print('测试', i.topic())
        replys = [i for i in reversed(r)]
        return render_template("user_profile.html",
                               topics=topics,
                               replys=replys,
                               user=u)
    else:
        return redirect(url_for('topic.index'))
Ejemplo n.º 29
0
def edit(request):
    """
    /todo/edit 的路由函数
    """
    headers = {
        'Content-Type': 'text/html',
    }
    # 找到当前登录的用户, 如果没登录, 就 redirect 到 /login
    uname = current_user(request)
    u = User.find_by(username=uname)
    if u is None:
        return redirect('/login')
    # 得到当前编辑的 todo 的 id,如果获取不到就设置为-1
    todo_id = int(request.query.get('id', -1))
    # 找到当前被编辑的条目的数据,按照当前编辑的 todo 的 id来寻找,
    # 比如编辑 {"id": 3, "title": "喝水", "user_id": 1},那么按照"id": 3取数据文件中查询
    # 比如 t = < Todo id: (3) title: (喝水) user_id: (1) >
    t = Todo.find_by(id=todo_id)
    # log('找到当前登录用户要编辑的数据的对应id', t)
    # 判断被编辑的这个数据对应的用户id(t.user_id)和编辑这个数据的用户id(u.id)是否一致
    # 比如 t.user_id = 1, u.id = 1
    # 如果两者相等说明登录用户在修改自己的数据,不相等说明登录用户在修改别人的数据,那这个是不允许的,就重定向到登录页面
    if t.user_id != u.id:
        return redirect('/login')
    # if todo_id < 1:
    #     return error(404)
    # 如果 t.user_id 和 u.id 相等,先读todo_edit.html 页面
    # 再替换模板文件todo_edit.html中的标记字符串{{todo_id}}为当前被编辑的todo的数据的id,
    # {{todo_title}}为当前被编辑的todo的数据的title
    body = template('todo_edit.html')
    body = body.replace('{{todo_id}}', str(t.id))
    body = body.replace('{{todo_title}}', str(t.title))
    # 下面 3 行可以改写为一条函数, 还把 headers 也放进函数中
    # 通过response_with_headers拿到服务器响应,headers上面设置了,headers = {'Content-Type': 'text/html',}
    # 返回请求头, HTTP/1.1 200 VERY OK\r\nContent-Type: text/html\r\n
    header = response_with_headers(headers)
    # 把请求头和body拼接
    """
    HTTP/1.1 200 VERY OK\r\n
    Content-Type: text/html\r\n\r\n
    <html>
        .........
    </html>

    """
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Ejemplo n.º 30
0
    def f(request):
        if 'id' in request.query:
            weibo_id = int(request.query['id'])
        else:
            form = request.json()
            weibo_id = int(form['id'])
        weibo = Weibo.find_by(id=weibo_id)
        u = current_user(request)

        if u.id == weibo.user_id:
            return api_function(request)
        else:
            d = dict(
                status=410,
                message="权限不足,请求无法执行",
            )
            return json_response(d)