Пример #1
0
 def test_utils(self):
     self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc"))
     self.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d",
                      sha1("abc"))
     self.assertEqual("picbed:a:b", rsp("a", "b"))
     self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"])
     self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"])
     self.assertTrue(is_true(1))
     self.assertTrue(is_true("on"))
     self.assertTrue(is_true("true"))
     self.assertFalse(is_true(0))
     self.assertIsInstance(get_current_timestamp(), int)
     self.assertTrue(allowed_file("test.PNG"))
     self.assertTrue(allowed_file(".jpeg"))
     self.assertFalse(allowed_file("my.psd"))
     self.assertFalse(allowed_file("ha.gif", ["jpg"]))
     self.assertFalse(allowed_file("ha.jpeg", ["jpg"]))
     self.assertFalse(allowed_file("ha.png", ["jpg"]))
     self.assertTrue(allowed_file("ha.jpg", ["jpg"]))
     v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6"
     self.assertEqual(v, hmac_sha256('key', 'text'))
     self.assertEqual(v, hmac_sha256(b'key', b'text'))
     self.assertEqual(v, hmac_sha256(u'key', u'text'))
     self.assertEqual(
         "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
         sha256("abc"))
Пример #2
0
def login():
    res = dict(code=1, msg=None)
    usr = request.form.get("username")
    pwd = request.form.get("password")
    #: 定义是否设置cookie状态
    set_state = is_true(request.form.get("set_state"))
    is_secure = False if request.url_root.split("://")[0] == "http" else True
    max_age = 7200
    if is_true(request.form.get("remember")):
        #: Remember me 7d
        max_age = 604800
    #: 登录接口钩子
    try:
        if g.cfg.site_auth:
            so = current_app.extensions["hookmanager"].proxy(g.cfg.site_auth)
            if so and hasattr(so, "login_api"):
                result = so.login_api(usr, pwd, set_state, max_age, is_secure)
                if result and isinstance(result, Response):
                    return result
    except (ValueError, TypeError, Exception) as e:
        logger.warning(e, exc_info=True)
    if usr and username_pat.match(usr) and pwd and len(pwd) >= 6:
        ak = rsp("accounts")
        usr = usr.lower()
        if g.rc.sismember(ak, usr):
            userinfo = g.rc.hgetall(rsp("account", usr))
            if is_true(g.cfg.disable_login) and \
                    not is_true(userinfo.get("is_admin")):
                res.update(msg="Normal user login has been disabled")
                return res
            password = userinfo.get("password")
            if password and check_password_hash(password, pwd):
                expire = get_current_timestamp() + max_age
                sid = "%s.%s.%s" % (usr, expire,
                                    sha256("%s:%s:%s:%s" %
                                           (usr, password, expire,
                                            current_app.config["SECRET_KEY"])))
                sid = b64encode(sid.encode("utf-8")).decode("utf-8")
                res.update(
                    code=0,
                    sid=sid,
                    expire=expire,
                    # is_admin=is_true(userinfo.get("is_admin"))
                )
                if set_state:
                    res = make_response(jsonify(res))
                    res.set_cookie(key="dSid",
                                   value=sid,
                                   max_age=max_age,
                                   httponly=True,
                                   secure=is_secure)
            else:
                res.update(msg="Password verification failed")
        else:
            res.update(msg="No valid username found")
    else:
        res.update(msg="The username or password parameter error")
    return res
Пример #3
0
def login():
    if request.method == "GET":
        return abort(404)
    res = dict(code=1)
    usr = request.form.get("username")
    pwd = request.form.get("password")
    #: 定义是否设置cookie状态
    set_state = is_true(request.form.get("set_state"))
    is_secure = False if request.url_root.split("://")[0] == "http" else True
    max_age = 7200
    if is_true(request.form.get("remember")):
        #: Remember me 7d
        max_age = 604800
    if usr and pwd and check_username(usr) and len(pwd) >= 6:
        ak = rsp("accounts")
        if rc.sismember(ak, usr):
            userinfo = rc.hgetall(rsp("account", usr))
            password = userinfo.get("password")
            if password and check_password_hash(password, pwd):
                expire = get_current_timestamp() + max_age
                sid = "%s.%s.%s" % (usr, expire,
                                    sha256("%s:%s:%s:%s" %
                                           (usr, password, expire,
                                            current_app.config["SECRET_KEY"])))
                sid = b64encode(sid.encode("utf-8")).decode("utf-8")
                res.update(
                    code=0,
                    sid=sid,
                    expire=expire,
                    # is_admin=is_true(userinfo.get("is_admin"))
                )
                if set_state:
                    res = make_response(jsonify(res))
                    res.set_cookie(key="dSid",
                                   value=sid,
                                   max_age=max_age,
                                   httponly=True,
                                   secure=is_secure)
            else:
                res.update(msg="Password verification failed")
        else:
            res.update(msg="No valid username found")
    else:
        res.update(msg="Parameter error")
    return res
Пример #4
0
 def test_utils(self):
     self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc"))
     self.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d",
                      sha1("abc"))
     self.assertEqual("picbed:a:b", rsp("a", "b"))
     self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"])
     self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"])
     self.assertTrue(is_true(1))
     self.assertTrue(is_true("on"))
     self.assertTrue(is_true("true"))
     self.assertFalse(is_true(0))
     self.assertIsInstance(get_current_timestamp(), int)
     self.assertTrue(allowed_file("test.PNG"))
     self.assertTrue(allowed_file(".jpeg"))
     self.assertFalse(allowed_file("my.psd"))
     self.assertFalse(allowed_file("ha.gif", ["jpg"]))
     self.assertFalse(allowed_file("ha.jpeg", ["jpg"]))
     self.assertFalse(allowed_file("ha.png", ["jpg"]))
     self.assertTrue(allowed_file("ha.jpg", ["jpg"]))
     v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6"
     self.assertEqual(v, hmac_sha256("key", "text"))
     self.assertEqual(v, hmac_sha256(b"key", b"text"))
     self.assertEqual(v, hmac_sha256(u"key", u"text"))
     self.assertEqual(
         "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
         sha256("abc"),
     )
     #: test format_upload_src
     baseimg = "img-url"
     basefmt = {"src": baseimg}
     self.assertEqual(format_upload_src(123, baseimg), basefmt)
     self.assertEqual(format_upload_src(None, baseimg), basefmt)
     self.assertEqual(format_upload_src([0], baseimg), basefmt)
     self.assertEqual(format_upload_src("", baseimg), basefmt)
     self.assertEqual(format_upload_src(".", baseimg), basefmt)
     self.assertEqual(format_upload_src(".1", baseimg), basefmt)
     self.assertEqual(format_upload_src("1.", baseimg), basefmt)
     self.assertEqual(format_upload_src(1.1, baseimg), basefmt)
     self.assertEqual(format_upload_src("1.1", baseimg),
                      {"1": {
                          "1": baseimg
                      }})
     self.assertEqual(format_upload_src("u", baseimg), basefmt)
     self.assertEqual(format_upload_src("im", baseimg), {"im": baseimg})
     self.assertEqual(format_upload_src("url", baseimg), {"url": baseimg})
     self.assertEqual(format_upload_src("i.am.src", baseimg), basefmt)
     self.assertEqual(format_upload_src("src.url", baseimg),
                      {"src": {
                          "url": baseimg
                      }})
     #: test format_apires
     self.assertEqual(format_apires({"code": 0}, "success", "bool"),
                      {"success": True})
     self.assertEqual(format_apires({"code": 0}, oc="200"), {"code": 200})
     self.assertEqual(format_apires({"code": -1}, "status", "bool"),
                      {"status": False})
     self.assertEqual(
         format_apires(dict(code=-1, msg="xxx"), "errno", "200"),
         {
             "errno": -1,
             "msg": "xxx"
         },
     )
     self.assertEqual(
         format_apires(dict(code=-1, msg="xxx"), "errno", "200", "errmsg"),
         {
             "errno": -1,
             "errmsg": "xxx"
         },
     )
     self.assertEqual(
         format_apires(dict(code=0, msg="xxx"), "", "200", "errmsg"),
         {
             "code": 200,
             "errmsg": "xxx"
         },
     )
     self.assertEqual(len(generate_random()), 6)
     self.assertIn("Mozilla/5.0", gen_ua())
     # bleach
     self.assertEqual(bleach_html("<i>abc</i>"), "<i>abc</i>")
     self.assertEqual(
         bleach_html("<script>var abc</script>"),
         "&lt;script&gt;var abc&lt;/script&gt;",
     )
     # re
     self.assertEqual(parse_author_mail("staugur"), ("staugur", None))
     self.assertEqual(parse_author_mail("staugur <mail>"),
                      ("staugur", "mail"))
Пример #5
0
def upload():
    #: 视频上传接口,上传流程:
    #: 1. 必须登录,通过固定的picbed字段获取上传内容
    #: 2. 生成sha,文件名规则是年月日时分秒原名,上传到用户目录下
    #: 3. 保存到后端,存储数据返回响应
    res = dict(code=1, msg=None)
    if not g.signin:
        res.update(code=403, msg="Anonymous user is not sign in")
        return res
    if g.userinfo.status != 1:
        msg = ("Pending review, cannot upload pictures" if g.userinfo.status
               in (-2, -1) else "The user is disabled, no operation")
        res.update(code=403, msg=msg)
        return res
    allowed_suffix = partial(allowed_file,
                             suffix=("mp4", "ogg", "ogv", "webm", "3gp",
                                     "mov"))
    fp = request.files.get("picbed")
    title = request.form.get("title") or ""
    if not fp or not allowed_suffix(fp.filename):
        res.update(msg="No file or image format error")
        return res
    suffix = splitext(fp.filename)[-1]
    filename = secure_filename(fp.filename)
    if "." not in filename:
        filename = "%s%s" % (generate_random(8), suffix)
    stream = fp.stream.read()
    upload_path = join(g.userinfo.username, get_today("%Y/%m/%d"))
    sha = "sha256.%s.%s" % (get_current_timestamp(True), sha256(filename))
    includes = parse_valid_comma(g.cfg.upload_includes or 'up2local')
    if len(includes) > 1:
        includes = [choice(includes)]
    data = current_app.extensions["hookmanager"].call(
        _funcname="upimg_save",
        _include=includes,
        _kwargs=dict(filename=filename,
                     stream=stream,
                     upload_path=upload_path,
                     local_basedir=join(current_app.root_path,
                                        current_app.static_folder,
                                        UPLOAD_FOLDER)))
    for i, result in enumerate(data):
        if result["sender"] == "up2local":
            data.pop(i)
            result["src"] = url_for("static",
                                    filename=join(UPLOAD_FOLDER, upload_path,
                                                  filename),
                                    _external=True)
            data.insert(i, result)
    #: 判定后端存储全部失败时,上传失败
    if not data:
        res.update(code=1, msg="No valid backend storage service")
        return res
    if is_all_fail(data):
        res.update(
            code=1,
            msg="All backend storage services failed to save pictures",
        )
        return res
    #: 存储数据
    defaultSrc = data[0]["src"]
    pipe = g.rc.pipeline()
    pipe.sadd(rsp("index", "video", g.userinfo.username), sha)
    pipe.hmset(
        rsp("video", sha),
        dict(
            sha=sha,
            user=g.userinfo.username,
            title=title,
            filename=filename,
            upload_path=upload_path,
            ctime=get_current_timestamp(),
            src=defaultSrc,
            sender=data[0]["sender"],
            senders=json.dumps(data),
        ))
    try:
        pipe.execute()
    except RedisError:
        res.update(code=3, msg="Program data storage service error")
    else:
        res.update(
            code=0,
            sender=data[0]["sender"],
            src=defaultSrc,
        )
    return res
Пример #6
0
 def test_utils(self):
     self.assertEqual("900150983cd24fb0d6963f7d28e17f72", md5("abc"))
     self.assertEqual(
         "a9993e364706816aba3e25717850c26c9cd0d89d", sha1("abc")
     )
     self.assertEqual("picbed:a:b", rsp("a", "b"))
     self.assertEqual(parse_valid_comma("a,b, c,"), ["a", "b", "c"])
     self.assertEqual(parse_valid_verticaline("a|b| c"), ["a", "b", "c"])
     self.assertTrue(is_true(1))
     self.assertTrue(is_true("on"))
     self.assertTrue(is_true("true"))
     self.assertFalse(is_true(0))
     self.assertIsInstance(get_current_timestamp(), int)
     self.assertTrue(allowed_file("test.PNG"))
     self.assertTrue(allowed_file(".jpeg"))
     self.assertFalse(allowed_file("my.psd"))
     self.assertFalse(allowed_file("ha.gif", ["jpg"]))
     self.assertFalse(allowed_file("ha.jpeg", ["jpg"]))
     self.assertFalse(allowed_file("ha.png", ["jpg"]))
     self.assertTrue(allowed_file("ha.jpg", ["jpg"]))
     v = "6afa9046a9579cad143a384c1b564b9a250d27d6f6a63f9f20bf3a7594c9e2c6"
     self.assertEqual(v, hmac_sha256('key', 'text'))
     self.assertEqual(v, hmac_sha256(b'key', b'text'))
     self.assertEqual(v, hmac_sha256(u'key', u'text'))
     self.assertEqual(
         "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
         sha256("abc")
     )
     #: test format_upload_src
     baseimg = 'img-url'
     basefmt = {'src': baseimg}
     self.assertEqual(format_upload_src(123, baseimg), basefmt)
     self.assertEqual(format_upload_src(None, baseimg), basefmt)
     self.assertEqual(format_upload_src([0], baseimg), basefmt)
     self.assertEqual(format_upload_src('', baseimg), basefmt)
     self.assertEqual(format_upload_src('.', baseimg), basefmt)
     self.assertEqual(format_upload_src('.1', baseimg), basefmt)
     self.assertEqual(format_upload_src('1.', baseimg), basefmt)
     self.assertEqual(format_upload_src(1.1, baseimg), basefmt)
     self.assertEqual(
         format_upload_src('1.1', baseimg), {'1': {'1': baseimg}}
     )
     self.assertEqual(format_upload_src('u', baseimg), basefmt)
     self.assertEqual(format_upload_src('im', baseimg), {'im': baseimg})
     self.assertEqual(format_upload_src('url', baseimg), {'url': baseimg})
     self.assertEqual(format_upload_src('i.am.src', baseimg), basefmt)
     self.assertEqual(
         format_upload_src('src.url', baseimg), {'src': {'url': baseimg}}
     )
     #: test format_apires
     self.assertEqual(
         format_apires({'code': 0}, "success", "bool"), {'success': True}
     )
     self.assertEqual(
         format_apires({'code': 0}, oc="200"), {'code': 200}
     )
     self.assertEqual(
         format_apires({'code': -1}, "status", "bool"), {'status': False}
     )
     self.assertEqual(
         format_apires(dict(code=-1, msg='xxx'), 'errno', '200'),
         {'errno': -1, 'msg': 'xxx'}
     )
     self.assertEqual(
         format_apires(dict(code=-1, msg='xxx'), 'errno', '200', 'errmsg'),
         {'errno': -1, 'errmsg': 'xxx'}
     )
     self.assertEqual(
         format_apires(dict(code=0, msg='xxx'), '', '200', 'errmsg'),
         {'code': 200, 'errmsg': 'xxx'}
     )
     self.assertEqual(len(generate_random()), 6)
     self.assertIn("Mozilla/5.0", gen_ua())