Example #1
0
 def isLogin(self):
     sesid = self.get_cookie(config.sesskey)
     user = ApolloUser(sessionid=sesid)
     if user.is_login():
         log.debug('已登录')
         return func(self)
     else:
         log.debug('未登录')
         return self.redirect('/login')
Example #2
0
 def GET(self):
     uid = self.get_cookie('uid')
     sessionid = self.get_cookie(config.sesskey)
     user = ApolloUser(uid,sessionid)
     user.logout()
     self.resp.del_cookie(config.sesskey)
     self.resp.del_cookie('uname')
     self.resp.del_cookie('uid')
     return self.redirect('/login')
Example #3
0
 def check_login(self):
     '''
     method: 验证商户是否登录
     return: 是否登录并会将session值写入self
     '''
     try:
         sessionid = self.get_cookie('sessionid')
         self.user = ApolloUser(sessionid=sessionid)
         if not self.user.is_login():
             return False
     except:
         log.warn('check_login error: %s' % traceback.format_exc())
         return False
     return True
Example #4
0
 def GET(self):
     sesid = self._set_session(uid=11754, username='******', expire=86400 * 10)
     self.set_cookie(config.sesskey, sesid, **config.COOKIE_CONFIG)
     user = ApolloUser(sessionid=sesid)
     uname = '李巍'
     self.set_cookie('uname', unicode_to_utf8(uname), **config.COOKIE_CONFIG)
     self.set_cookie('uid', 11754, **config.COOKIE_CONFIG)
     ret = {'success': 1, 'msg': uname}
     return self.redirect('/index')
Example #5
0
 def record(self, values):
     if func:
         now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
         values['ctime'] = now_time
         sesid = self.get_cookie('sessionid')
         user = ApolloUser(sessionid=sesid)
         values['operator'] = user.ses['username']
         try:
             self.db['qf_solar'].insert(table='operation_table',
                                        values=values)
         except Exception, e:
             log.debug('mysql insert error: %s' % traceback.format_exc())
Example #6
0
 def _set_session(self, uid, username, expire):
     user = ApolloUser(uid, expire=expire)
     user.ses['username'] = username
     log.debug('user_info[0].name:%s', username)
     user.ses['uid'] = uid
     user.login(uid)
     user.ses.save()
     return user.ses._sesid
Example #7
0
class BaseHandler(Handler):
    def initial(self):
        self.set_headers({'Content-Type': 'application/json; charset=UTF-8'})

    def check_login(self):
        '''
        method: 验证商户是否登录
        return: 是否登录并会将session值写入self
        '''
        try:
            sessionid = self.get_cookie('sessionid')
            self.user = ApolloUser(sessionid=sessionid)
            if not self.user.is_login():
                return False
        except:
            log.warn('check_login error: %s' % traceback.format_exc())
            return False
        return True

    def get_groupid(self, **kw):
        '''获取商户的groupid'''
        groupid = None
        try:
            groupid = self.user.ses.data['groupid']
        except:
            userid = (self.user.userid if
                      (hasattr(self, 'user')
                       and self.user.userid) else kw.get('userid'))
            if userid:
                user = apcli.user_by_id(userid)
                if user:
                    try:
                        self.user.ses.data['groupid'] = user['groupid']
                    except:
                        pass
                    groupid = user['groupid']

        return groupid
Example #8
0
    def adjust_ret(self, userid):
        data = self._data
        ret = {}
        try:
            # 存储session
            user = ApolloUser(userid, expire=86400 * 7)
            user.ses['chnlid'] = 0
            user.ses['groupid'] = data['groupid']
            user.ses['udid'] = data.get('udid', '')
            user.login(userid)
            user.ses.save()
            sessionid = user.ses._sesid

            # 用户信息
            userinfo = {
                i: data.get(i, '')
                for i in ('shopname', 'province', 'city', 'address',
                          'username')
            }
            userinfo['groupid'] = data['groupid']
            userinfo['mobile'] = userinfo['username']
            userinfo['uid'] = userid
            userinfo['jointime'] = time.strftime('%Y-%m-%d %H:%M:%S')
            userinfo['telephone'] = data.get('landline') or ''

            # 返回登录的信息
            ret = UserUtil.ret_userinfo(userinfo,
                                        sessionid=sessionid,
                                        is_creat_shop=0)
            ret['shop_info']['head_img'] = (data.get('head_img', '')
                                            or config.APP_DEFAULT_AVATR)
            ret['shop_info']['logo_url'] = data.get('logo_url') or ''
        except:
            log.debug(traceback.format_exc())
            ret = {}

        return ret
Example #9
0
    def POST(self):
        data = self.req.input()
        username = data['username']
        password = data['password']
        # 获取用户,user[0]有数据则有该用户
        # user = self._get_user_info(username)
        user = Pub_Method.get_user_info(username)
        if not user[0]:
            ret = {'success': 0, 'username': username, 'msg': user[1]}
            return self.write(template.render('user_login.html',data=ret))

        count = 0 if not redis_pool.get(username) else int(redis_pool.get(username))
        if count >= 5:
            ret = {'success': 0, 'username': username, 'msg': '抱歉,您输入的密码错误已达到5次,账号处于锁定状态,请联系管理员!'}
            return self.write(template.render('user_login.html', data=ret))

        # 验证登录是否成功,result[0]为0的话,登录失败,否则登录成功
        # result = self._get_login_status(username,password)
        result = Pub_Method.get_login_status(username, password)

        if not result[0]:
            count = redis_pool.get(username)
            # 获取当前时间,仅仅获取到年月日
            now_time = datetime.datetime.now().strftime('%Y-%m-%d')
            # 得到次日凌晨时间
            when = datetime.datetime.strptime(now_time, '%Y-%m-%d') + datetime.timedelta(days=1)
            if not count:
                count = 1
                redis_pool.set(username, count)
                redis_pool.expireat(username, when)
            else:
                count = int(count) + 1
                redis_pool.set(username, count)
                redis_pool.expireat(username, when)
            ret = {}
            if count >= 5:
                ret = {'success': 0, 'username': username, 'msg': '抱歉,您输入的密码错误已达到5次,账号处于锁定状态,请联系管理员!'}
            else:
                ret = {'success': 0, 'username': username, 'msg': result[1]+'还有'+str(5-count)+'次机会!'}
            return self.write(template.render('user_login.html', data=ret))

        else:
            # 获取该手机号用户的权限,通过uid,有权限方可继续登录,返回的元组,元组中第一个元素为列表,第二个为msg
            # roles = self._get_userpermissionrole(result[0])
            roles = Pub_Method.get_userpermissionrole(result[0])
            if len(roles[0]) == 0:
                ret = {'success':0,'username':username,'msg':roles[1]}
                return self.write(template.render('user_login.html',data=ret))

            # 登录成功后验证密码
            pwd_ok = checkPassword(password)

            if pwd_ok:
                user_info = Pub_Method.get_username(result[0])
                if not user_info[0]:
                    ret = {'success': 0, 'username': username, 'msg': '用户信息获取失败'}
                    return self.write(template.render('user_login.html', data=ret))
                #86400*30

                sesid = self._set_session(uid=result[0],username=user_info[0].name,expire=86400*1)
                self.set_cookie(config.sesskey, sesid, **config.COOKIE_CONFIG)
                user = ApolloUser(sessionid=sesid)
                uname = user.ses['username']
                self.set_cookie('uname', unicode_to_utf8(uname), **config.COOKIE_CONFIG)
                self.set_cookie('uid', result[0], **config.COOKIE_CONFIG)
                ret = {'success': 1, 'msg': result[1]}
                return self.redirect('/index')
            else:
                ret = {'success': 0, 'username': username, 'msg': '您的密码存在风险,请通过"钱方好近商户app"修改', 'tourl': '/reset_pwd',
                       'toword': '点击此处去修改'}
                return self.write(template.render('user_login.html', data=ret))
Example #10
0
class BaseHandler(Handler):

    def initial(self):
        self.set_headers({'Content-Type': 'application/json; charset=UTF-8'})

    @with_customer
    def get_cid(self):
        '''
        获取customer_id
        '''
        if not self.customer.is_login():
            raise SessionError('用户未登录')

        return self.customer.customer_id


    def get_language(self, userid=None):
        ''' 获取商户的语言

        从useragnet中获取, 若没有从session中获取,
        session中如果没有从渠道获取对应的语言
        '''

        if hasattr(self, '_language'):
            return self._language

        language = 'zh-cn'
        # 从useragent获取
        try:
            ua = self.req.environ.get('HTTP_USER_AGENT','')
            groups = UA_LANGUAGE_PATTERN.search(ua)
            self._language = groups.group(1).lower()
            return self._language
        except:
            pass

        # 从session中获取
        try:
            self._language = self.user.ses.data['language']
            return self._language
        except:
            pass

        # 从渠道中获取
        groupid = self.get_groupid(userid=userid)
        if groupid:
            language = get_qudaoinfo(groupid)['language'].lower()
            try:
                self.user.ses.data['language'] = language
            except:
                pass
        self._language = language

        return language


    def get_cate(self, userid=None, cates=None):
        ''' 用户角色

        salesman 和 qudao 回自动忽略

        Params:
            userid: 商户userid,不传即从self.user获取
            cates: 商户角色, 不传将自动获取
        Returns:
            bigmerchant: 大商户
            submerchant: 子商户
            merchant: 商户
        '''
        try:
            if not userid:
                return self.user.ses.data['cate']
        except:
            pass

        if cates is None:
            try:
                userid = userid or self.user.userid
                if userid:
                    cates = apcli.get_user_cate(userid)
            except:
                cates = []

        if not userid:
            return 'merchant'

        cate_dict = {cate['code'] for cate in cates or []}
        if 'bigmerchant' in cate_dict:
            cate = 'bigmerchant'
        else:
            big_uid = apcli.reverse_userids(userid, 'merchant')
            if big_uid:
                self._big_uid = big_uid[0].userid
                cate = 'submerchant'
            else:
                cate = 'merchant'

        try:
            self.user.ses.data['cate'] = cate
        except:
            pass

        return cate

    def check_login(self):
        '''
        method: 验证商户是否登录
        return: 是否登录并会将session值写入self
        '''
        try:
            sessionid = self.get_cookie('sessionid')
            self.user = ApolloUser(sessionid=sessionid)
            if not self.user.is_login():
                return False
        except:
            log.warn('check_login error: %s' % traceback.format_exc())
            return False
        return True

    def check_ip(self):
        '''验证ip'''
        ips = (getattr(config, 'IP_LIMIT', None) or
            ('192.30.*.*', '192.10.*.*', '127.0.0.1','172.100.*.*'))
        remote_ip = self.req.clientip()
        for ip in ips:
            index = ip.find('*')
            if ((index == -1 and remote_ip == ip) or
                remote_ip[:index - 1] == ip[:index - 1]):
                    return True
        log.debug(remote_ip)
        return False

    def get_groupid(self, userid=None, **kw):
        '''获取商户的groupid'''
        groupid = None
        try:
            if not userid:
                return self.user.ses.data['groupid']
        except:
            pass

        try:
            userid = userid or self.user.userid
        except:
            userid = None

        if userid:
            try:
                groupid = groupid_cache[int(userid)]
                self.user.ses.data['groupid'] = groupid
            except:
                #log.debug(traceback.format_exc())
                pass

        return groupid


    def is_baipai(self, groupid):
        '''是否是白牌商户'''
        return int(groupid in config.BAIPAI_GROUPIDS)


    def get_big_uid(self, userid=None):
        '''
        获取商户的大商户id
        '''
        big_uid = None
        try:
            if not userid:
                return self.user.ses.data['big_uid']
        except:
            pass

        try:
            userid = userid or self.user.userid
        except:
            userid = None

        if userid:
            try:
                relate = apcli('getUserReverseRelation',
                               int(userid), 'merchant')
                big_uid = relate[0].userid if relate else 0

                self.user.ses.data['big_uid'] = big_uid
            except:
                return big_uid

        return big_uid

    def get_userids(self, userid=None):
        '''获取商户列表

        Params:
            userid:商户userid

        Returns:
            若商户为大商户的子商户时, 返回大商户id和商户id列表
            否则返回的列表仅包含商户id
        '''

        userids = [userid] if userid else [self.user.userid]
        big_uid = self.get_big_uid(userid)
        if big_uid:
            userids.append(big_uid)
        return userids

    def get_link_ids(self, userid=None):
        '''获取大商户的子商户id列表'''
        cate = self.get_cate(userid)
        if cate != 'bigmerchant':
            return []

        link_ids = None
        try:
            if not userid:
                return self.user.ses.data['link_ids']
        except:
            pass

        try:
            userid = userid or self.user.userid
        except:
            userid = None

        if userid:
            try:
                relats = apcli(
                    'getUserRelation', int(userid),
                    'merchant'
                ) or []
                link_ids = [i.userid for i in relats]

                self.user.ses.data['link_ids'] = link_ids
            except:
                return link_ids

        return link_ids

    def get_userid_login_or_ip(self):
        '''
        通过session或者ip获取userid
        '''
        userid = None
        # 好近商户版登陆
        if self.check_login():
            userid = self.user.userid

        # qiantai2 调用
        elif self.check_ip():
            userid = self.req.input().get('userid')

        if not is_valid_int(userid):
            raise SessionError('无操作权限')

        return userid

    def get_pageinfo(self):
        params = self.req.input()

        page = params.get('page', 0)
        pagesize = params.get('pagesize', 10)

        if not is_valid_int(page) or not is_valid_int(pagesize):
            raise ParamError('分页信息错误')

        limit = int(pagesize)

        offset = limit * int(page)

        return limit, offset


    def get_other(self, fields=None, default_field='ctime', default_type='desc'):
        params = self.req.input()

        orderby = ''
        if fields:
            order_field = params.get('order_field', default_field)
            order_type = params.get('order_type', default_type)
            fields = [i.split('.')[-1] for i in fields]
            if (order_field.split('.')[-1] not in fields or
                order_type not in ('desc', 'asc')):
                raise ParamError('排列信息错误')

            orderby = 'order by {order_field} {order_type}'.format(
                order_field=order_field, order_type=order_type)

        return (
            '{orderby} limit {limit} offset {offset}'.format(
                orderby = orderby,
                limit = int(params.get('pagesize', 10)),
                offset = int(params.get('page', 0)) * int(params.get('pagesize', 10))
            )
        )
Example #11
0
    def set_session(self, udid, userinfo, opuid=None, cate=None, **kw):
        ''' 设置登录session

        session包含:
            cate: bigmerchant|submerchant|merchant 商户角色
            opuid: 有表示为操作员, 无即是普通商户
            groupid: 渠道id
            language: 语言
            udid: 设备识别码
            userid: 商户userid

        '''
        user = ApolloUser(userinfo['uid'], expire=86400 * 3)

        # 设置user session
        user.ses['udid'] = udid
        user.ses['groupid'] = userinfo['groupid']
        user.ses['chnlid'] = 0

        #设置登录时间
        user.ses['login_time'] = int(time.time())
        user.ses['cate'] = cate
        if hasattr(self, '_big_uid') and self._big_uid:
            user.ses['big_uid'] = self._big_uid

        # 如果是大商户, 存下他的连锁店id
        if cate == 'bigmerchant':
            relats = apcli_ex('getUserRelation', int(userinfo['uid']),
                              'merchant') or []
            link_ids = [i.userid for i in relats]
            user.ses['link_ids'] = link_ids

        if opuid:
            user.ses['opuid'] = str(opuid)

        for k, v in kw.iteritems():
            user.ses[k] = v

        user.login(userinfo['uid'])
        user.ses.save()

        return user.ses._sesid
Example #12
0
            raise ValueError(mapping.get(e.respcd, '用户登录失败'))
        except ValueError, e:
            log.debug(str(e))
            userid = None
        except:
            log.debug(traceback.format_exc())
            userid = None

        if userid:
            # 剔除用户
            if kickuser:
                thrift_callex(SESSION_CONF, Session, 'user_offline', [userid])

            # 设置session
            if set_session:
                user = ApolloUser(userid, expire=expire)

                # 存储userCates
                user.ses['userCates'] = userinfo['userCates']
                user.login(userid)
                user.ses.save()

                userinfo['sessionid'] = user.ses._sesid

            log.debug('user %s auth success', username)
        else:
            log.debug('user %s auth failed', username)
            userinfo = None

        return userinfo
Example #13
0
class BaseHandler(Handler):
    def initial(self):
        self.set_headers({'Content-Type': 'application/json; charset=UTF-8'})
        log.debug("lang : %s", self.req.environ.get('HTTP_LANG'))

    def get_name(self, userid=None):
        try:
            if not userid:
                return self.user.ses['username']
        except:
            pass

        user = {}
        if getattr(self, '_user', None):
            user = self._user
        else:
            try:
                userid = userid or self.user.userid
                if userid:
                    user = apcli.findUserBriefById(int(userid))
                    self._user = user = user.__dict__
            except:
                user = {}

        return user.get('name') or ''

    def get_cates(self, userid=None, reload=False):
        self._new_get_cates = False
        try:
            if not reload and not self._new_get_cates:
                return self.user.ses.data['user_cates']
        except:
            pass

        try:
            self._new_get_cates = True
            userid = int(userid or self.user.userid)
            cates = apcli.get_user_cate(userid)
            cates = [cate['code'] for cate in cates or []]
        except:
            cates = []

        try:
            self.user.ses.data['user_cates'] = cates
        except:
            pass

        return cates

    def get_cate(self, userid=None, cates=None):
        ''' 商户角色

        Returns:
            bigmerchant: 大商户
            submerchant: 子商户
            merchant: 商户
        '''
        cate = ''
        cate_dict = cates
        if not userid:
            return cate
        if not cates:
            try:
                userid = userid
                cates = apcli.get_user_cate(userid)
            except:
                cates = []
            cate_dict = {cate['code'] for cate in cates or []}
        if 'bigmerchant' in cate_dict:
            cate = 'bigmerchant'

        elif 'mchnt' in cate_dict and 'submchnt' not in cate_dict:
            cate = 'merchant'
        elif 'submchnt' in cate_dict and 'mchnt' not in cate_dict:
            cate = 'submerchant'
        elif 'mchnt' in cate_dict and 'submchnt' in cate_dict:
            big_uid = apcli.reverse_userids(userid, 'merchant')
            if big_uid:
                self._big_uid = big_uid[0].userid
                cate = 'submerchant'
            else:
                cate = 'merchant'

        return cate

    def check_cate(self, cate=web_cate, userid=None):
        if not cate: return True

        for flag in (False, True):
            user_cates = self.get_cates(userid, flag)
            if cate in user_cates:
                return True

        return False

    def get_perms(self, userid=None, reload=False):
        self._new_get_perms = False
        try:
            if not reload and not self._new_get_perms:
                return self.user.ses.data['perms']
        except:
            pass

        try:
            self._new_get_perms = True
            userid = int(userid or self.user.userid)
            perms = apcli('get_user_permissions', userid)
            perms = [
                p.code for p in perms or []
                if p.group.startswith(PermDef.PERM_ROLE_GROUP)
            ]
        except:
            perms = []

        try:
            self.user.ses.data['perms'] = perms
        except:
            pass

        return perms

    def check_perms(self, perm_codes, userid=None):
        if not perm_codes:
            return True

        for flag in (False, True):
            user_perms = self.get_perms(userid, flag)
            if set(perm_codes) & set(user_perms):
                return True

        return False

    def check_login(self):
        '''
        method: 验证商户是否登录
        return: 是否登录并会将session值写入self
        '''
        try:
            sessionid = self.get_cookie('sessionid')
            self.user = ApolloUser(sessionid=sessionid)
            if not self.user.is_login():
                return False
        except:
            log.warn('check_login error: %s' % traceback.format_exc())
            return False
        return True

    def get_pageinfo(self, params=None):
        params = params or self.req.input()

        page = params.get('page', 1)
        pagesize = params.get('pagesize', 10)

        if not is_valid_int(page) or not is_valid_int(pagesize):
            raise ParamError('分页信息错误')

        limit = int(pagesize)

        offset = limit * int(page)

        return limit, offset

    def get_where(self,
                  fields=None,
                  intfields=None,
                  likefields=None,
                  params=None):
        params = params or self.req.input()

        fields = fields or []
        intfields = intfields or []
        likefields = likefields or []
        # where
        where = {}
        search = list(fields) + list(intfields) + list(likefields)
        for i in search:
            if not params.get(i):
                continue
            elif i in intfields:
                where[i] = int(params[i])
            elif i in likefields:
                where[i] = 'like', '%%%s%%' % params[i]
            elif i in fields:
                where[i] = params[i]
        return where

    def get_other(self,
                  fields=None,
                  default_field='ctime',
                  default_type='desc',
                  params=None):
        '''
        获取sql查询other

        params:
            fields: 可排序字段
            default_field: 默认排序字段
            default_type: 默认排序方法
            params: 所有参数, 不传默认使用input

        return:
            order by XX limit XX offset XX
        '''
        if params is None:
            params = self.req.input()

        order_field = params.get('order_field') or default_field
        order_type = params.get('order_type') or default_type
        if ((fields is not None and order_field not in fields)
                or order_type not in ('desc', 'asc')):
            raise ParamError('排列信息错误')
        orderby = 'order by {order_field} {order_type}'.format(
            order_field=order_field, order_type=order_type)

        limit, offset = self.get_pageinfo(params)

        return '{orderby} limit {limit} offset {offset}'.format(
            orderby=orderby, limit=limit, offset=offset)

    def get_org_uid(self, userid=None):
        '''获取商户机构uid'''
        if not userid:
            try:
                return self.user.ses.data['groupid']
            except:
                pass

        admin = None
        with get_connection('qf_org') as db:
            userid = userid or self.user.userid
            admin = db.select_one('org_admin',
                                  where={'userid': userid},
                                  fields='qd_uid')

        if not admin:
            raise ParamError('org不存在')

        try:
            self.user.ses['org_uid'] = admin['qd_uid']
        except:
            pass

        return admin['qd_uid']