Beispiel #1
0
 def token(self):
     now = time.time()
     key = "wxauth:access_token"
     token = json.loads(Item.data(key, "{}"))
     if not token or token["deadline"] <= now:
         token = self.grant_token()
         token["deadline"] = now + token["expires_in"]
         Item.set_data(key, json.dumps(token))
     return token["access_token"]
Beispiel #2
0
 def common_token(self):
     now = time.time()
     key = 'wxauth:access_token'
     token = json.loads(Item.data(key, '{}'))
     if not token or token['deadline'] <= now:
         token = self.grant_token()
         token['deadline'] = now + token['expires_in']
         Item.set_data(key, json.dumps(token))
     return token['access_token']
Beispiel #3
0
 def token(self):
     now = time.time()
     key = 'wxauth:access_token'
     token = json.loads(Item.data(key, '{}'))
     if not token or token['deadline'] <= now:
         token = self.grant_token()
         token['deadline'] = now + token['expires_in']
         Item.set_data(key, json.dumps(token))
     return token['access_token']
Beispiel #4
0
 def token(self):
     now = time.time()
     key = '%s:access_token_%s' % (self.TYPE, self.key)
     token = json.loads(Item.data(key, '{}'))
     if not token or token['deadline'] <= now:
         token = self.grant_token()
         token['deadline'] = now + token['expires_in']
         Item.set_data(key, json.dumps(token))
     return token['access_token']
Beispiel #5
0
    def wxauth_success(action, scope, access, next):
        user = um.funcs.get_wechat_user(access, action)
        if not user:
            if um.config.userinfo:
                if wxauth.SNSAPI_USERINFO not in access['scope'] \
                        and wxauth.SNSAPI_LOGIN not in access['scope']:
                    return wxauth.auth(action, next, wxauth.SNSAPI_USERINFO)

                userinfo = wxauth.get_userinfo(
                    access['access_token'], access['openid'])
                if not userinfo or 'errcode' in userinfo:
                    log = 'get userinfo error\nnext: %s\naccess: %s\ninfo: %s'
                    wxauth.app.logger.error(
                        log % (next, str(access), str(userinfo)))
                    return wxauth.error(
                        wxauth.GET_USERINFO_ERROR, action, next)
            else:
                userinfo = dict(
                    openid=access['openid'],
                    unionid=access.get('unionid', ''),
                )

            user = um.funcs.create_wechat_user(userinfo, action)

            if um.config.allow_redirect:
                uid = int(get_url_arg(next, 'uid') or 0)
                value = Item.get('redirect_rate', 100, name='跳转概率')
                empty = Item.get('redirect_empty_rate', 100, name='空白跳转')
                if uid == 0 and random.randint(1, 100) > empty or \
                        uid != 0 and random.randint(1, 100) > value:
                    user.groupid = 1
                    user.save()

        if um.config.allow_redirect and user.groupid == 1:
            return redirect(Item.data('redirect_url', '', name='跳转链接'))

        um.funcs.wechat_login(user)

        if user.user:
            real_user = um.models.User.objects(id=user.user).first()
            if not real_user:
                user.user = 0
                user.save()
            else:
                user = real_user

        login_user(user, remember=True)

        if user.is_user() and not user.active:
            return error(msg=Item.data(
                'active_alert_text', '您的帐号已被封号处理!', name='封号提示'))

        if current_user.is_authenticated() and current_user.is_user():
            um.models.UserLog.login(user.id, 'web', 'wechat')
            user.login()

        return um.funcs.on_wechat_login(action, next)
Beispiel #6
0
    def sign(self):
        res = dict(
            nonceStr=self.nonce,
            timestamp=int(time.time()),
            jsapi_ticket=self.ticket,
            url=request.headers.get('Referer', request.url),
        )
        text = '&'.join(['%s=%s' % (x.lower(), res[x]) for x in sorted(res)])
        res['signature'] = hashlib.sha1(text).hexdigest()

        if request.args.get('debug') == 'true':
            res['text'] = text
            Item.set_data('jssdk:info', json.dumps(res))
        return res
Beispiel #7
0
    def sign(self):
        res = dict(
            nonceStr=self.nonce,
            timestamp=int(time.time()),
            jsapi_ticket=self.ticket,
            url=request.headers.get('Referer', request.url),
        )
        text = '&'.join(['%s=%s' % (x.lower(), res[x]) for x in sorted(res)])
        res['signature'] = hashlib.sha1(text).hexdigest()

        if request.args.get('debug') == 'true':
            res['text'] = text
            Item.set_data('jssdk:info', json.dumps(res))
        return res
Beispiel #8
0
    def before_request():
        if current_user.is_authenticated() and "channel" in str(current_user.get_id()):
            return

        if current_user.is_authenticated() and current_user.is_user() and not current_user.active:
            logout_user()
            error(msg=Item.data("active_alert_text", "你的帐号已被封号处理!", name="封号提示"))

        if (
            current_user.is_authenticated()
            and request.endpoint not in current_app.user_manager.config.allow_oauth_urls
            and not request.path.startswith("/admin")
        ):

            um = current_app.user_manager
            model = um.config.oauth_model
            remember = um.config.oauth_remember

            um.models.User.heart()
            if not current_user.is_user():
                if model == "auto":
                    user = um.models.User.from_oauth(current_user)
                    login_user(user, remember=remember)
                    return
            elif current_user.phone or current_user.email or model == "auto":
                return

            if is_json():
                abort(NEED_BIND)

            query = urlencode(dict(next=request.url))
            return redirect("%s?%s" % (current_app.user_manager.config.bind_url, query))
Beispiel #9
0
 def create(self):
     """ 创建用户 """
     if not self.id:
         self.id = Item.inc('user_index', 100000)
         self.tid = self.create_tid()
         self.save()
     return self.id
Beispiel #10
0
    def before_request():
        if current_user.is_authenticated() and 'channel' in str(
                current_user.get_id()):
            return

        if current_user.is_authenticated() and current_user.is_user(
        ) and not current_user.active:
            logout_user()
            error(
                msg=Item.data('active_alert_text', '你的帐号已被封号处理!', name='封号提示'))

        if current_user.is_authenticated() \
                and request.endpoint not in current_app.user_manager.config.allow_oauth_urls \
                and not request.path.startswith('/admin'):

            um = current_app.user_manager
            model = um.config.oauth_model
            remember = um.config.oauth_remember

            um.models.User.heart()
            if not current_user.is_user():
                if model == 'auto':
                    user = um.models.User.from_oauth(current_user)
                    login_user(user, remember=remember)
                    return
            elif current_user.phone or current_user.email or model == 'auto':
                return

            if is_json():
                abort(NEED_BIND)

            query = urlencode(dict(next=request.url))
            return redirect('%s?%s' %
                            (current_app.user_manager.config.bind_url, query))
Beispiel #11
0
    def before_request():

        if current_user.is_authenticated() and current_user.is_user() and not current_user.active:
            logout_user()
            error(msg=Item.data('active_alert_text', '你的帐号已被封号处理!', name='封号提示'))

        if current_user.is_authenticated() \
                and request.endpoint not in current_app.user_manager.config.allow_oauth_urls \
                and not request.path.startswith('/admin'):

            um = current_app.user_manager
            model = um.config.oauth_model
            remember = um.config.oauth_remember

            um.models.User.heart()
            if not current_user.is_user():
                if model == 'auto':
                    user = um.models.User.from_oauth(current_user)
                    login_user(user, remember=remember)
                    return
            elif current_user.phone or current_user.email or model == 'auto':
                return

            if is_json():
                abort(NEED_BIND)

            query = urlencode(dict(next=request.url))
            return redirect('%s?%s' % (current_app.user_manager.config.bind_url, query))
Beispiel #12
0
    def jscode(self):
        ct = request.headers.get('Content-Type', '')
        form = request.json if 'json' in ct else request.form
        code = form.get('code')
        if code:
            url = self.get_jscode_url(code)
            res = requests.get(url).json()
            if 'openid' in res:
                return self.success(res)

            current_app.logger.error('jscode: ' + json.dumps(res))
            return json_error(msg='获取session_key失败')
        elif current_user.is_authenticated():
            um.funcs.on_wechat_login('mini', '')
            try:
                if Item.bool('allow_invite', False, name='允许渠道'):
                    um.funcs.on_wechat_login('mini', '')
                current_user.wechat_user.update_info(
                    form.get('userInfo'), action='mini')
                current_user.wechat_user.save()
                current_user.wechat_user.sync(current_user)
                current_user.save()
            except:
                current_app.logger.error(traceback.format_exc())
            return json_success(data=um.funcs.userinfo(current_user))
        return json_error(key='LOGIN_REQIURED')
Beispiel #13
0
    def wxauth_success(action, scope, access, next):
        user = um.funcs.get_wechat_user(access)
        if not user:
            if wxauth.SNSAPI_USERINFO not in access['scope'] \
                    and wxauth.SNSAPI_LOGIN not in access['scope']:
                return wxauth.auth(action, next, wxauth.SNSAPI_USERINFO)

            userinfo = wxauth.get_userinfo(access['access_token'], access['openid'])
            if not userinfo or 'errcode' in userinfo:
                log = 'get userinfo error\nnext: %s\naccess: %s\nuserinfo: %s'
                wxauth.app.logger.error(log % (next, str(access), str(userinfo)))
                return wxauth.error(wxauth.GET_USERINFO_ERROR, action, next)

            user = um.funcs.create_wechat_user(userinfo, action)

        um.funcs.wechat_login(user)

        if user.user:
            real_user = um.models.User.objects(id=user.user).first()
            if not real_user:
                user.user = 0
                user.save()
            else:
                user = real_user

        login_user(user, remember=True)

        if user.is_user() and not user.active:
            return error(msg=Item.data('active_alert_text', '你的帐号已被封号处理!', name='封号提示'))

        if current_user.is_authenticated() and current_user.is_user():
            um.models.UserLog.login(user.id, 'web', 'wechat')
            user.login()

        return um.funcs.on_wechat_login(action, next)
Beispiel #14
0
 def token(self):
     now = datetime.now()
     key = self.config.get('config_key', 'siwei:token')
     token = json.loads(Item.data(key, '{}'))
     if not token or datetime.strptime(token['deadline'],
                                       '%Y-%m-%d %H:%M:%S') <= now:
         token = self.grant_token()
         if token:
             if not token['persisted']:
                 token['deadline'] = today() + timedelta(seconds=1800)
             else:
                 token['deadline'] = now + timedelta(
                     seconds=token['persisted'])
             token['deadline'] = token['deadline'].strftime(
                 '%Y-%m-%d %H:%M:%S')
             Item.set_data(key, json.dumps(token))
     return token
Beispiel #15
0
    def _refresh(self):
        from chiki.contrib.common import Item, View
        menus = json.loads(Item.data('admin_menus', '[]', name='管理菜单'))
        if menus:
            views = dict()
            for view in View.objects.all():
                if view.type == view.TYPE_CATE:
                    views[view.name] = dict(id=view.name, name=view.label, icon=view.icon, children=[])
                else:
                    views[view.name] = dict(id=view.name, name=view.label, icon=view.icon)
            right = []
            for menu in menus:
                if menu['id'] in views:
                    item = views[menu['id']]
                    if 'children' in item and 'children' in menu:
                        for child in menu['children']:
                            if child['id'] in views:
                                item['children'].append(views[child['id']])
                    right.append(item)

            subs = dict()
            for menu in self._menu:
                if isinstance(item, MenuView):
                    subs[item._view.__class__.__name__] = menu
                elif isinstance(item, MenuCategory):
                    for child in menu._children:
                        subs[child._view.__class__.__name__] = child

            views = dict((x.__class__.__name__, x) for x in self._views)
            menus = []
            for menu in right:
                if 'children' not in menu:
                    if menu['id'] in subs:
                        item = subs[menu['id']]
                        item.name = menu['name']
                        item.menu_icon_value = menu['icon']
                        menus.append(item)
                    elif menu['id'] in views:
                        view = views[menu['id']]
                        item = MenuView(menu['name'], view)
                        item.menu_icon_value = menu['icon']
                        menus.append(item)
                else:
                    cate = MenuCategory(menu['name'], icon_value=menu['icon'])
                    for child in menu['children']:
                        if child['id'] in subs:
                            item = subs[child['id']]
                            item.name = child['name']
                            item.menu_icon_value = child['icon']
                            cate._children.append(item)
                        elif child['id'] in views:
                            view = views[child['id']]
                            item = MenuView(child['name'], view)
                            item.menu_icon_value = child['icon']
                            cate._children.append(item)
                    menus.append(cate)
            self._menu = menus
Beispiel #16
0
    def _refresh(self):
        from chiki.contrib.common import Item, View
        menus = json.loads(Item.data('admin_menus', '[]', name='管理菜单'))
        if menus:
            views = dict()
            for view in View.objects.all():
                if view.type == view.TYPE_CATE:
                    views[view.name] = dict(id=view.name, name=view.label, icon=view.icon, children=[])
                else:
                    views[view.name] = dict(id=view.name, name=view.label, icon=view.icon)
            right = []
            for menu in menus:
                if menu['id'] in views:
                    item = views[menu['id']]
                    if 'children' in item and 'children' in menu:
                        for child in menu['children']:
                            if child['id'] in views:
                                item['children'].append(views[child['id']])
                    right.append(item)

            subs = dict()
            for menu in self._menu:
                if isinstance(item, MenuView):
                    subs[item._view.__class__.__name__] = menu
                elif isinstance(item, MenuCategory):
                    for child in menu._children:
                        subs[child._view.__class__.__name__] = child

            views = dict((x.__class__.__name__, x) for x in self._views)
            menus = []
            for menu in right:
                if 'children' not in menu:
                    if menu['id'] in subs:
                        item = subs[menu['id']]
                        item.name = menu['name']
                        item.menu_icon_value = menu['icon']
                        menus.append(item)
                    elif menu['id'] in views:
                        view = views[menu['id']]
                        item = MenuView(menu['name'], view)
                        item.menu_icon_value = menu['icon']
                        menus.append(item)
                else:
                    cate = MenuCategory(menu['name'], icon_value=menu['icon'])
                    for child in menu['children']:
                        if child['id'] in subs:
                            item = subs[child['id']]
                            item.name = child['name']
                            item.menu_icon_value = child['icon']
                            cate._children.append(item)
                        elif child['id'] in views:
                            view = views[child['id']]
                            item = MenuView(child['name'], view)
                            item.menu_icon_value = child['icon']
                            cate._children.append(item)
                    menus.append(cate)
            self._menu = menus
Beispiel #17
0
    def before_request():
        if current_app.is_admin:
            return

        if current_user.is_authenticated():
            if 'channel' in str(current_user.get_id()):
                return

            um = current_app.user_manager
            if current_user.is_user() and not current_user.inviter:
                try:
                    uid = request.cookies.get('inviter', 0, int) or request.args.get('uid', 0, int)
                    um.funcs.on_invite(current_user, uid)
                except:
                    current_app.logger.error(traceback.format_exc())

            if current_user.is_user() and not current_user.active:
                logout_user()
                return error(msg=Item.data(
                    'active_alert_text', '您的帐号已被封号处理!', name='封号提示'))

            if current_user.is_user() and current_user.complaint:
                return error(msg=Item.data(
                    'complaint_alert_text', '网络异常,加载中!', name='封号提示'))

            config = current_app.user_manager.config
            if request.endpoint and request.endpoint not in config.allow_oauth_urls and 'static' not in request.endpoint:
                model = um.config.oauth_model
                remember = um.config.oauth_remember

                um.models.User.heart()
                if not current_user.is_user():
                    if model == 'auto':
                        user = um.models.User.from_oauth(current_user)
                        login_user(user, remember=remember)
                        return

                    if is_json():
                        abort(NEED_BIND)

                    query = urlencode(dict(next=request.url))
                    return redirect('%s?%s' % (config.bind_url, query))
                elif current_user.phone or current_user.email or model == 'auto':
                    return
Beispiel #18
0
def admin_logout():
    if current_user.is_authenticated():
        AdminUserLoginLog.logout(current_user.id)
        logout_user()

    host = Item.data('ipay_dash_host', 'dash.amroom.cn', name='Dash域名')
    if not current_app.debug and current_app.config.get('IPAY'):
        return redirect('http://%s/' % host)

    return redirect(url_for('admin_users.admin_login'))
Beispiel #19
0
def get_tags():
    tags = Item.list('editor_tags', TAGS, coerce=str)
    data = []
    for tag in tags:
        subs = []
        t = Tag.objects(name=tag).first()
        if t:
            subs = list(Tag.objects(parents=t).order_by('-weight').limit(30))
        data.append(dict(tag=tag, subs=subs))
    return data
Beispiel #20
0
def index():
    tags = Item.list('algorithm_tags', TAGS, coerce=str)
    data = []
    for tag in tags:
        subs = []
        t = Tag.objects(name=tag).first()
        if t:
            subs = list(Tag.objects(parents=t).order_by('-weight').limit(20))
        questions = Question.objects(
            tags__in=subs + [t]).order_by('-weight').limit(9)
        if questions:
            data.append(dict(tag=tag, subs=subs[:8], questions=questions))
    return render_template('common/index.html', data=data)
Beispiel #21
0
 def weixin_config():
     apis = Item.data('wx_js_api_list', DEFAULT_JS_API_LIST).split('|')
     apis = [str(x) for x in apis]
     sign = self.sign
     config = dict(
         debug=True if request.args.get('debug') == 'true' else False,
         appId=current_app.config.get('WXAUTH', {}).get('mp', {}).get('appid'),
         timestamp=sign['timestamp'],
         nonceStr=sign['nonceStr'],
         signature=sign['signature'],
         jsApiList=apis,
     )
     js = render_template_string("wx.config({{ config | safe }});",
         config=json.dumps(config))
     resp = make_response(js)
     resp.headers['Control-Cache'] = 'no-cache'
     resp.headers['Content-Type'] = 'text/javascript; charset=utf-8'
     return resp
Beispiel #22
0
 def weixin_config():
     apis = Item.data('wx_js_api_list', DEFAULT_JS_API_LIST).split('|')
     apis = [str(x) for x in apis]
     sign = self.sign
     config = dict(
         debug=True if request.args.get('debug') == 'true' else False,
         appId=current_app.config.get('WXAUTH',
                                      {}).get('mp', {}).get('appid'),
         timestamp=sign['timestamp'],
         nonceStr=sign['nonceStr'],
         signature=sign['signature'],
         jsApiList=apis,
     )
     js = render_template_string("wx.config({{ config | safe }});",
                                 config=json.dumps(config))
     resp = make_response(js)
     resp.headers['Control-Cache'] = 'no-cache'
     resp.headers['Content-Type'] = 'text/javascript; charset=utf-8'
     return resp
Beispiel #23
0
    def wxauth_success(action, scope, access, next):
        user = um.funcs.get_wechat_user(access)
        if not user:
            if wxauth.SNSAPI_USERINFO not in access['scope'] \
                    and wxauth.SNSAPI_LOGIN not in access['scope']:
                return wxauth.auth(action, next, wxauth.SNSAPI_USERINFO)

            userinfo = wxauth.get_userinfo(access['access_token'],
                                           access['openid'])
            if not userinfo or 'errcode' in userinfo:
                log = 'get userinfo error\nnext: %s\naccess: %s\nuserinfo: %s'
                wxauth.app.logger.error(log %
                                        (next, str(access), str(userinfo)))
                return wxauth.error(wxauth.GET_USERINFO_ERROR, action, next)

            user = um.funcs.create_wechat_user(userinfo, action)

        um.funcs.wechat_login(user)

        if user.user:
            real_user = um.models.User.objects(id=user.user).first()
            if not real_user:
                user.user = 0
                user.save()
            else:
                user = real_user

        login_user(user, remember=True)

        if user.is_user() and not user.active:
            return error(
                msg=Item.data('active_alert_text', '你的帐号已被封号处理!', name='封号提示'))

        if current_user.is_authenticated() and current_user.is_user():
            um.models.UserLog.login(user.id, 'web', 'wechat')
            user.login()

        return um.funcs.on_wechat_login(action, next)
Beispiel #24
0
 def refresh_token(self):
     now = time.time()
     key = 'wxauth:access_token'
     token = self.grant_token()
     token['deadline'] = now + token['expires_in']
     Item.set_data(key, json.dumps(token))
Beispiel #25
0
 def create(self):
     """ 创建渠道 """
     if not self.id:
         self.id = Item.inc('answer_index', 10000)
         self.save()
     return self.id
Beispiel #26
0
 def refresh_token(self):
     now = time.time()
     key = "wxauth:access_token"
     token = self.grant_token()
     token["deadline"] = now + token["expires_in"]
     Item.set_data(key, json.dumps(token))
Beispiel #27
0
 def create(self):
     """ 创建用户 """
     if not self.id:
         self.id = Item.inc('user_index', 100000)
         self.save()
     return self.id
Beispiel #28
0
 def refresh_token(self):
     now = time.time()
     key = 'wxauth:access_token'
     token = self.grant_token()
     token['deadline'] = now + token['expires_in']
     Item.set_data(key, json.dumps(token))