Example #1
0
def get_obj_auth(oid=None, obj=None):
    s = SQL()
    if obj is None:
        return False
    res = s.query_value("`authority`", "`" + obj + "`", "`id`=" + oid)
    if not res or len(res) < 1:
        return False
    return json.loads(res[0])
Example #2
0
def index():
    try:
        s = SQL()
        sql = "select * from `user`"
        return jsonify({"status": "ok", "data": s.query(sql)})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #3
0
 def get_user_id(access_token="*"):
     from app.utils import SQL
     s = SQL()
     res = s.query_value("`id`", "`login`",
                         "where `access_token` = '%s'" % access_token)
     if not res or len(res) < 1:
         return None
     return res[0]
Example #4
0
def get_detail():
    try:
        tid = escape_string(request.args.get("id"))
        s = SQL()
        condition = "where id = %s" % tid
        sql = "select `name`,`homepage`,`header`,`age`,`job`,`edu`,`degree`,`email`,`native`,`pho`,`department`," \
              "`intro`,`paper`,`other` from `people` where id = %s;" % tid
        return jsonify({"status": "ok", "data": s.query(sql)})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #5
0
def get_list():
    try:
        page = int(request.args.get('page') or "1")
        psize = int(request.args.get('psize') or "8")
        pno = (page - 1) * psize
        s = SQL()
        condition = "where 1 = 1"
        sql = "select `id`,`pub_date`,`tag`,`title`,`type` from (select * from `notice` order by pub_date desc ) " \
              "tmp %s limit %d , %d " % (condition, pno, psize)
        return jsonify({"status": "ok", "data": s.query(sql)})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #6
0
def get_mlist():
    try:
        page = int(request.args.get('page') or "1")
        psize = int(request.args.get('psize') or "8")
        ntype = escape_string(request.args.get("type") or "news")
        pno = (page - 1) * psize
        s = SQL()
        # 补充查询条件
        condition = "where 1 = 1 and `status` = 'valid' and `type` = '%s'" % ntype
        sql = "select `id`,`title`,`pub_date`,`album`,`author`,`type` from " \
              "(select * from `news` order by pub_date desc ) tmp %s limit %d , %d" % (condition, pno, psize)
        return jsonify({"status": "ok", "data": s.query(sql)})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #7
0
def news_review():
    try:
        nid = escape_string(request.args.get("id"))


        # 验证权限

        # 通过验证
        s = SQL()
        sql = "update `news` set status = 'pass' where id = '%s'" % nid
        s.operator(sql)
        return jsonify({"status": "ok", "data": "新闻审批通过"})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #8
0
def check_mani(mani, obj, oid=None, access_token="*"):
    s = SQL()

    # 根据access_token查询用户
    user = s.query_value("`id`,`authority`,`identity`", "`user`", "`access_token`=" + access_token)
    auth_user = json.loads(user[1])

    # 发布、上传
    if mani == "pub":
        for iobj in auth_user["pub"]:
            if iobj == obj:
                return True

    # 查询、修改
    # 查询访问权限
    auth_obj = json.loads(s.query_value("`authority`", "`" + obj + "`", "`id`=" + oid)[0])

    # 如果请求的资源为read并且对所有人可见,则可以访问
    for index in auth_obj["read"]["identity"]:
        if index == "everyone" and mani == "read":
            return True

    # 用户身份不通过
    if user is None:
        return False
    # 查询其操作权限
    else:
        # 用户的管理员身份通过

        for mani_type in auth_user:
            # 查询操作权限
            if mani_type == mani:
                # 查询权限是否存在
                for iobj in auth_user[mani_type]:
                    if iobj == obj:
                        return True

        # 用户在obj许可中
        # 用户在identity中
        for iden in auth_obj[mani]["identity"]:
            if iden == "public" or int(iden) >= int(user[2]):
                return True
        # 用户在users中
        for users in auth_obj[mani]["users"]:
            if users == user[0]:
                return True
    # 其他情况
    return False
Example #9
0
def get_list():
    try:
        page = int(request.args.get('page') or "1")
        psize = int(request.args.get('psize') or "50")
        pno = (page - 1) * psize
        s = SQL()
        # 按职称分别查询
        job = ["教授", "副教授", "讲师", "其他"]
        res = {}
        for t in job:
            condition = "where job = '%s'" % t
            sql = "select `id`,`name`,`header`,`job` from `people` where `job` = '%s';" % t
            res[t] = s.query(sql)
        return jsonify({"status": "ok", "data": res})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #10
0
def get_abs():
    try:
        import os
        from app.config import BASE_DIR

        f = open(os.path.join(BASE_DIR, "data/sz.txt"), 'r')
        text = f.read()
        f.close()
        s = SQL()
        sql = "select (select count(id) from `people`) 'total',(select count(id) from `people` where job = '教授') " \
              "'pro',(select count(id) from `people` where job = '副教授') 'ass'"
        res = s.query(sql)[0]
        print(res)
        print(text)
        text = text.replace("{{total}}", str(res["total"])).replace("{{pro}}", str(res["pro"]))\
            .replace("{{ass}}", str(res["ass"]))
        return jsonify({"status": "ok", "data": text})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #11
0
def get_detail():
    try:
        nid = escape_string(request.args.get("id"))
        s = SQL()
        condition = "where id = %s" % nid
        sql = "select `id`,`title`,`pub_date`,`tag`,`author`,`type`,`content`,`read` from `notice` %s" % condition

        # 新闻阅读量+1
        sqls = [
            "begin work;",
            "select `read` from `notice` where `id` = '%s' for update;" % nid,
            "update `notice` set `read` = `read` + 1 where `id` = '%s';" % nid,
            "commit work;"
        ]
        s.operat_many(sqls)

        return jsonify({"status": "ok", "data": s.query(sql)})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #12
0
    def create_accesstoken(uid):
        import datetime
        import hashlib
        import random
        from app.utils import SQL
        s = SQL()
        password_hash = s.query_value("`password_hash`", "`user`",
                                      "`id`=" + uid)[0]
        # 获取当前时间并格式化为 日月年时分秒 如10122018151401
        time = datetime.datetime.now().strftime('%d%m%Y%H%M%S')
        # 将时间与用户账号连接 并进行一次MD5散列
        md5 = hashlib.md5()
        md5.update((time + uid).encode('utf-8'))  # 注意转码
        crypt1 = md5.hexdigest()

        # 将crypt1 和 密码的HASH值以及生成的随机数进行一次sha256
        random.seed()
        sha256 = hashlib.sha256()
        sha256.update(
            str(str(crypt1) + str(password_hash) +
                str(random.random())).encode('utf-8'))
        crypt2 = sha256.hexdigest()
        return crypt2
Example #13
0
 def get_user_auth(uid=None, access_token=None):
     import datetime
     import json
     from flask import current_app
     from app.utils import SQL
     s = SQL()
     sql = ""
     user = None
     if uid is not None:
         user = s.query_value("`authority`", "`user`", "`id`=" + uid)
     # 使用accesstoken 需要验证时效性
     elif access_token is not None:
         # 取用户最近一次操作
         log = s.query_value(
             "`time`,`mani`", "`login`",
             "access_token = '%s' order by time desc limit 1;" %
             access_token)
         # token无效
         if not log:
             print("查询结果为空")
             return False
         # 如果是注销 logout 则需要重新登录
         # 如果access token过期
         df = log[0] + datetime.timedelta(
             seconds=current_app.config["ACCESSTOKEN_VALID_TIME"])
         if log[1] == "logout" or df < datetime.datetime.now():
             print("accesstoken过期")
             return False
         user = s.query_value("`authority`", "`user`",
                              "`access_token`='%s'" % access_token)
     else:
         return False
     # 查询不到结果
     if not user or len(user) < 1:
         return False
     return json.loads(user[0])
Example #14
0
def user_login():
    import hashlib
    from datetime import datetime
    try:
        uid = escape_string(request.args.get("id")) or None
        password_hash = escape_string(
            request.args.get("password_hash")) or None
        code = escape_string(request.args.get("code") or "")
        usa = request.user_agent or "hidden"
        uip = request.remote_addr or "hidden"

        # md5 = hashlib.md5()
        # md5.update(password.encode("utf-8"))
        # password_hash = md5.hexdigest()

        s = SQL()
        if password_hash == s.query_value("`password_hash`", "`user`",
                                          "`id`='%s'" % uid)[0]:
            # 验证通过

            # 生成token
            token = user.User.create_accesstoken(uid)

            # 存入登录记录
            lgn = login.Login(uid=uid,
                              time=datetime.now(),
                              ip=uip,
                              user_agent=usa,
                              access_token=token,
                              mani="login")
            db.session.add(lgn)
            db.session.commit()

            # 更新user表
            s = SQL()
            sql = "update `user` set `latest_time`='%s', `access_token`='%s' where `id`='%s'" % (
                datetime.now(), token, uid)
            s.operator(sql)

            return jsonify({"status": "ok", "data": token})
        else:
            # 密码或账号错误
            return jsonify({"status": "failed", "data": "密码或账号错误"})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "error:%s" % e})
Example #15
0
def get_file():
    try:
        from .utils import get_obj_auth

        oid = escape_string(request.args.get("id"))
        s = SQL()
        # 文件不存在
        file_res = s.query_value("`*`", "`file`", "id='%s'" % oid)
        if file_res is None or len(file_res) < 1:
            return jsonify({"status": "failed", "data": {"code": 1, "msg": "文件不存在!"}})

        # 文件权限查询

        # 查询文件路径
        file_path = s.query_value("`path`", "`file`", "`id`='%s'" % oid)[0]

        file_abpath = os.path.join(BASE_DIR, file_path)

        # 下载次数 + 1

        sqls = [
            "begin work;",
            "select `download` from `file` where `id` = '%s' for update;" % oid,
            "update `file` set `download` = `download` + 1 where `id` = '%s';" % oid,
            "commit work;"
        ]
        s.operat_many(sqls)

        # 记录用户操作
        print(request.user_agent)
        print(request.remote_addr)
        f_dic, fn = os.path.split(file_abpath)
        return send_from_directory(directory=f_dic, filename=fn, as_attachment=True)
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "错误请求"})
Example #16
0
def rev_file():
    try:
        from werkzeug.utils import secure_filename
        import datetime
        from app.extensions import db
        accesstoken = request.form.get('accesstoken')
        # 定义返回参数
        file_url = ""

        # 接收部分参数
        obj = request.form.get('type') or "None"

        # 权限控制
        user_auth = User.get_user_auth(access_token=accesstoken)
        print(user_auth)
        if not user_auth or obj not in user_auth["pub"]:
            return jsonify({"status": "failed", "data": {"code": 1, "msg": "你无权限上传文件!"}})

        # 接收文件
        f = request.files["file"] or None
        if f is None:
            return jsonify({"status": "failed", "data": {"code": 2, "msg": "未接收到文件!"}})

        # 取文件名和后缀
        fn, ff = os.path.splitext(secure_filename(f.filename))
        # 格式控制
        if str.lower(ff) not in current_app.config["ALLOWED_FILE_FORMAT"]:
            return jsonify({"status": "failed", "data": {"code": 3, "msg": "不允许的文件格式!"}})

        # 文件大小
        f_size = len(f.read())
        # 重置文件指针
        f.seek(0, 0)
        if f_size > current_app.config["MAX_FILE_SIZE"]:
            return jsonify({"status": "failed", "data": {"code": 4, "msg": "文件过大!"}})

        # 文件查重
        file_hash = File.cul_file_hash(f)
        s = SQL()
        query_res = s.query_value("`path`", "`file`", "`hash`='%s'" % file_hash)

        uid = s.query_value("`id`", "`user`", "access_token='%s'" % accesstoken)[0]
        # 文件未收录
        if query_res is None or len(query_res) < 1:
            # 文件名安全性  werzeug

            basepath = current_app.config["UPLOADED_TMP_DEST"]
            if obj == "news":
                basepath = current_app.config["UPLOADED_NEWS_DEST"]
                file_url = os.path.join(current_app.config["UPLOADED_BASE_DIR"], 'news')
            elif obj == "notice":
                basepath = current_app.config["UPLOADED_NOTICE_DEST"]
                file_url = os.path.join(current_app.config["UPLOADED_BASE_DIR"], 'notice')
            elif obj == "file":
                basepath = current_app.config["UPLOADED_FILE_DEST"]
                file_url = os.path.join(current_app.config["UPLOADED_BASE_DIR"], 'file')
            elif obj == "person":
                basepath = current_app.config["UPLOADED_FILE_DEST"]
                file_url = os.path.join(current_app.config["UPLOADED_BASE_DIR"], 'person')
            else:
                basepath = current_app.config["UPLOADED_TMP_DEST"]
                file_url = os.path.join(current_app.config["UPLOADED_BASE_DIR"], 'tmp')

            filename = fn + "-" + obj + "-" + file_hash + ff
            filepath = os.path.join(basepath, filename)
            # 存入目录
            f.save(filepath)
            file_url = os.path.join(file_url, filename)

            #
            #
            # 设置文件权限
            # 如果不是公开文件,就要设置动态下载
            #

            # 数据库存档
            new_file = File(name=filename, type=ff, author=uid, pub_date=datetime.datetime.now(), path=file_url
                            , authority=File.create_obj_ahthority(), hash=file_hash, status="default")
            db.session.add(new_file)
            db.session.commit()

        # 文件已收录,返回文件路径
        else:
            # 返回文件路径
            file_url = query_res[0]
        # 记录用户操作记录
        uip = request.remote_addr or "hidden"
        usa = str(request.user_agent) or "hidden"
        lgn = Login(uid=uid, time=datetime.datetime.now(), ip=uip, user_agent=usa, access_token=accesstoken,
                    mani="upload file: %s" % file_url)
        db.session.add(lgn)
        db.session.commit()

        return jsonify({"status": "ok", "data": {"url": file_url}})
    except Exception as e:
        log.logger.warning(e)
        return jsonify({"status": "failed", "data": "错误请求"})
Example #17
0
    '"CQHC","121341241321","SSE","nointro","nopaper","none");',

    'insert into login (`uid`,`time`,`ip`,`user_agent`,`access_token`,`mani`)'
    'values("1", "2018-12-10 12:00:12","127.0.0.1","CHROME","TOKEN1","signin");',
    'insert into login (`uid`,`time`,`ip`,`user_agent`,`access_token`,`mani`)'
    'values("1", "2018-12-11 12:00:12","127.0.0.1","CHROME","TOKEN1","pub");',
    'insert into login (`uid`,`time`,`ip`,`user_agent`,`access_token`,`mani`)'
    'values("1", "2018-12-12 12:00:12","127.0.0.1","CHROME","TOKEN1","edit");',
    'insert into login (`uid`,`time`,`ip`,`user_agent`,`access_token`,`mani`)'
    'values("1", "2018-12-12 16:00:12","127.0.0.1","CHROME","TOKEN2","logout");',
    'insert into login (`uid`,`time`,`ip`,`user_agent`,`access_token`,`mani`)'
    'values("2", "2018-12-10 12:40:12","127.0.0.1","CHROME","TOKEN3","login");',
    'insert into login (`uid`,`time`,`ip`,`user_agent`,`access_token`,`mani`)'
    'values("2", "2018-12-10 12:50:12","127.0.0.1","CHROME","TOKEN3","pub");',
    'insert into login (`uid`,`time`,`ip`,`user_agent`,`access_token`,`mani`)'
    'values("2", "2018-12-12 16:10:12","127.0.0.1","CHROME","TOKEN3","pub");',

    'insert into file (`name`,`type`,`author`,`path`,`authority`,`hash`,`status`)'
    'values("filename","png","Aaron","https://github.com/Aarebecca/jcx-flask/blob/master/app/models/user.py",'
    '\'{"read":{"identity":["everyone"],"users":[]},"edit":'
    '{"identity":["everyone"],"users":[]}}\',"hash","valid");'
]

s = SQL()

for sql in sqls:
    print(sql)
    s.operator(sql)