示例#1
0
class CommentMod(ClassTool):
    def __init__(self, user_info=None):
        ClassTool.__init__(self)
        self.__conn = MongoHelp('Comment')
        from user import User
        if isinstance(user_info, User):
            self.user = user_info

    @ModVerify
    def add(self, main_id, comment, level_reply=None, reviewed=False):
        comment_num = self.__conn.conn.find({'main_id': main_id}).count()
        comment_post = dict(
            main_id=main_id,
            level_num=comment_num+1,
            level_reply=level_reply,
            content=comment,
            username=self.user.user_data['username'],
            user_id=self.user.user_data['_id'],
            status='normal',
            reviewed=reviewed
        )
        is_add = self.__conn.insert(comment_post)
        return self._sys_msg(is_add, 'Grant Fail', {'_id': is_add})

    @ModVerify
    def modify(self, comment_id, comment):
        is_fix = self.__conn.fix_one({'_id': comment_id}, {'content': comment})
        return self._sys_msg(is_fix, 'Grant Fail', {'_id': comment_id})

    @ModVerify
    def remove(self, comment_id):
        is_del = self.__conn.remove({'_id': comment_id})
        return self._sys_msg(is_del, 'Grant Fail', {'_id': comment_id})

    @ModVerify
    def review(self, comment_id, is_pass=True):
        is_review = self.__conn.fix_one({'_id': comment_id}, {'reviewed': is_pass})
        return self._sys_msg(is_review, 'Grant Fail', {'_id': comment_id})

    @ModVerify
    def details(self, _id):
        found = self.__conn.find_one({'_id': _id})
        return self._sys_msg(found, 'Not Found')

    @ModVerify
    def get_list(self, ident=None, limit=10, skip=0):
        if ident is None:
            ident = {'reviewed': True}
        found = self.__conn.conn.find(ident).limit(limit).skip(skip)
        total = found.count()
        comment_data = self.__conn.id_format(found)
        return self._sys_msg(comment_data, 'Not Found', {'page': {'total': total, 'limit': limit, 'skip': skip}})
示例#2
0
# coding=utf-8
from conn import MongoHelp

__author__ = 'dolacmeo'
__doc__ = '模块装饰器'
setting_conn = MongoHelp('Setting')

is_super_disable = setting_conn.find_one({'set_type':
                                          'system'})['super_user']['disable']
func_registered = setting_conn.find_one({'set_type':
                                         'system'})['all_fuc'].keys()


def ModVerify(func):
    """
    验证用户权限,处理数据结果,注册功能模块
    :param func:
    """
    content_less_permission = ['UserMod', 'PermissionMod']

    def wrapper(*args, **kwargs):
        if len(args) == 0:
            raise Exception('Used within class.func')
        user_model = args[0].user
        class_name = args[0].__class__.__name__
        fuc_name = args[0].__class__.__name__ + '#' + func.__name__
        print '%s:' % fuc_name
        if not user_model.is_login:
            raise Exception('Need User login first')
        if (fuc_name in user_model.permission.keys()) \
                or (user_model.group == 'super' and not is_super_disable):
示例#3
0
class PermissionMod(ClassTool):
    def __init__(self, user_info=None):
        ClassTool.__init__(self)
        self.__conn = MongoHelp('Permission')
        self.__conn_user = MongoHelp('User')
        self.__conn_settings = MongoHelp('Setting')
        self.__permission_model = self.__conn_settings.find_one(
            {"set_type": "permission_model"})
        from user import User
        if isinstance(user_info, User):
            self.user = user_info
            self.__allow_list = self.__allow()

    def __allow(self):
        if self.user.group == 'super':
            return MongoHelp('Setting').find_one({'set_type':
                                                  'system'})['all_fuc'].keys()
        return self.user.user_data['permission']['tag'].keys()

    @ModVerify
    def grant(self, ident, func_name, class_list=None):
        print self.__allow_list
        the_user = self.__conn_user.find_one({'username': ident})
        if func_name not in the_user['permission']['tag'].keys():
            tag = the_user['permission']['tag']
            if class_list is None:
                tag[func_name] = []
            else:
                tag[func_name] = [class_list]
            is_update = self.__conn_user.fix_one({'_id': the_user['_id']}, {
                'permission': {
                    'tag': tag,
                    'group': the_user['permission']['group']
                }
            })
            return self._sys_msg(is_update, 'Grant Fail',
                                 {'_id': the_user['_id']})
        else:
            permission_keys = the_user['permission']['tag'][func_name]
            tag = the_user['permission']['tag']
            if isinstance(class_list, unicode):
                if class_list in permission_keys:
                    pass
                else:
                    permission_keys.append(class_list)
                    class_list = permission_keys
            elif isinstance(class_list, list):
                for key in permission_keys:
                    if key in class_list:
                        pass
                    else:
                        class_list.append(key)
            if not class_list:
                class_list = []
            tag[func_name] = class_list
            is_update = self.__conn_user.fix_one({'_id': the_user['_id']}, {
                'permission': {
                    'tag': tag,
                    'group': the_user['permission']['group']
                }
            })
            return self._sys_msg(is_update, 'Grant Fail',
                                 {'_id': the_user['_id']})

    @ModVerify
    def revoke(self, ident, func_name, class_list=None):
        print self.__allow_list
        the_user = self.__conn_user.find_one({'username': ident})
        if func_name in the_user['permission']['tag'].keys():
            permission_keys = the_user['permission']['tag'][func_name]
            if isinstance(class_list, list):
                for key in class_list:
                    if key in permission_keys:
                        permission_keys.remove(key)
                    else:
                        pass
            elif isinstance(class_list, unicode):
                if class_list in permission_keys:
                    permission_keys.remove(class_list)
                else:
                    pass
            else:
                pass
            tag = the_user['permission']['tag']
            if not permission_keys:
                pass
            else:
                tag[func_name] = permission_keys
            if permission_keys:
                is_update = self.__conn_user.fix_one(
                    {'_id': the_user['_id']}, {
                        'permission': {
                            'tag': tag,
                            'group': the_user['permission']['group']
                        }
                    })
                return self._sys_msg(is_update, 'Grant Fail',
                                     {'_id': the_user['_id']})
            else:
                tag = the_user['permission']['tag']
                del tag[func_name]
                is_update = self.__conn_user.fix_one(
                    {'_id': the_user['_id']}, {
                        'permission': {
                            'tag': tag,
                            'group': the_user['permission']['group']
                        }
                    })
                return self._sys_msg(is_update, 'Grant Fail',
                                     {'_id': the_user['_id']})
        else:
            return self._sys_msg(True, ext_json={'_id': the_user['_id']})
        pass

    @ModVerify
    def setup_model(self,
                    user_model,
                    func_name,
                    class_list=None,
                    is_fix=False):
        if class_list is None:
            class_list = []
        if user_model in self.__permission_model['tag'].keys() and not is_fix:
            return self._sys_msg(False, 'Already have')
        else:
            self.__permission_model['tag'][user_model] = {
                func_name: sorted(class_list)
            }
        is_insert = self.__conn_settings.fix_one(
            {"set_type": "permission_model"},
            {'tag': self.__permission_model['tag']})
        return self._sys_msg(is_insert, 'Setup Fail')

    @ModVerify
    def remove_model(self, user_model):
        del self.__permission_model['tag'][user_model]
        is_delete = self.__conn_settings.fix_one(
            {"set_type": "permission_model"},
            {'tag': self.__permission_model['tag']})
        return self._sys_msg(is_delete, 'Delete Fail')

    @ModVerify
    def details(self, _id):
        found = self.__conn_user.find_one({'_id': _id})
        return self._sys_msg(found, 'Not Found')

    @ModVerify
    def get_list(self, ident=None, limit=10, skip=0):
        if ident is None:
            ident = {'reviewed': True}
        found = self.__conn_user.conn.find(ident).limit(limit).skip(skip)
        total = found.count()
        user_data = self.__conn_user.id_format(found)
        return self._sys_msg(
            user_data, 'Grant Fail',
            {'page': {
                'total': total,
                'limit': limit,
                'skip': skip
            }})

    pass
示例#4
0
文件: user.py 项目: laurencechan/test
class UserMod(ClassTool):
    def __init__(self, user_info=None):
        ClassTool.__init__(self)
        if isinstance(user_info, User):
            self.user = user_info
            self.__conn = MongoHelp('User')
            self.__conn_setting = MongoHelp('Setting').find_one(
                {'set_type': 'system'})
            self.__salt = self.__conn_setting['user_salt']
            self.__raw_data = MongoHelp('Setting').find_one(
                {'set_type': 'raw_data'})
            self.__permission = self.__raw_data['permission']
            self.__group_range = MongoHelp('Permission').find_one(
                {'group_name': self.user.group})['control']
        else:
            # raise Exception('Plz input User case')
            pass

    @ModVerify
    def create(self, username, password, phone='', group='user', info=None):
        if len(password) < 6:
            return self._sys_msg(False, {'_id': ''},
                                 'password need more then 6 char')
        if username.isdigit():
            return self._sys_msg(False, {'_id': ''},
                                 'username fail with only numbers')
        if not self.__group_range:
            return self._sys_msg(False, {'_id': ''},
                                 'Need create_user Permission')
        is_old_nicename = self.__conn.find_one({'username': username})
        is_old_phone = self.__conn.find_one({'phone': phone})
        if is_old_nicename or (is_old_phone and phone):
            return self._sys_msg(False, {'_id': ''}, 'username already in')
        else:
            user_default = self.__raw_data['user_default']
            new_user = dict(
                username=username,
                password=hashlib.md5(self.__salt + password +
                                     self.__salt).hexdigest(),
                phone=phone if phone.isdigit() and (len(phone) == 11) else '',
                permission=dict(
                    group=group if group in self.__group_range else 'user',
                    tag={}),
                create_date=datetime.datetime.now())
            if info:
                new_user.update(info)
            user_default.update(new_user)
            return self._sys_msg(
                True, ext_json={'_id': self.__conn.insert(user_default)})

    @ModVerify
    def modify(self, ident, info):
        if not info or not isinstance(info, dict):
            raise Exception('Update what? need dict data')
        if not self.__group_range:
            raise Exception('Need update_user Permission')
        if ident.isdigit() and len(ident) == 11:
            key = 'phone'
        else:
            key = 'username'
        user_data = self.__conn.find_one({key: ident})
        if not user_data:
            return self._sys_msg(False, 'ident error, check out!', {'_id': ''})
        user_id = user_data['_id']
        user_default = self.__raw_data['user_default']
        for n in info.keys():
            if n not in ['username', 'password'] and n in user_default.keys():
                if n == 'permission':
                    if info[n].get('group') not in self.__group_range:
                        return self._sys_msg(False, 'Permission Limit',
                                             {'_id': ''})
                    else:
                        if 'group' in info[n].keys():
                            user_data[n]['group'] = info[n]['group']
                        if 'tag' in info[n].keys():
                            system_mod = MongoHelp('Setting').find_one(
                                {'set_type': 'system'})['all_fuc'].keys()
                            for m in info[n].keys():
                                if m in system_mod:
                                    if m in user_data[n]['tag'].keys():
                                        user_data[n]['tag'][m].extend(
                                            info[n][m])
                                    else:
                                        user_data[n]['tag'][m] = info[n][m]
                else:
                    if isinstance(info[n], str):
                        user_data[n] = info[n]
                    elif isinstance(info[n], dict):
                        for m in info[n].keys():
                            user_data[n][m] = info[n][m]
        for i in ['_id', 'username', 'password']:
            del user_data[i]
        is_update = self.__conn.fix_one({'_id': user_id}, user_data)
        return self._sys_msg(is_update, 'Update Failed', {'_id': is_update})

    @ModVerify
    def details(self, _id):
        found = self.__conn.find_one({'_id': _id})
        return self._sys_msg(found, 'Not Found')

    @ModVerify
    def get_list(self, ident=None, limit=10, skip=0):
        if ident is None:
            ident = {}
        found = self.__conn.conn.find(ident).limit(limit).skip(skip)
        total = found.count()
        found = self.__conn.id_format(found)
        return self._sys_msg(
            found, 'Grant Fail',
            {'page': {
                'total': total,
                'limit': limit,
                'skip': skip
            }})

    @staticmethod
    def reset_pwd(is_request=True, **kwargs):
        db_conn = MongoHelp('User')
        if is_request:
            if 'username' not in kwargs.keys():
                raise Exception('Need username to request reset password!')
            try:
                import random
                reset_code = '%06d' % random.randint(0, 999999)
                db_conn.fix_one({'username': kwargs['username']},
                                {'reset_code': reset_code})
                return {
                    'success': True,
                    'reset_code': reset_code,
                    'error': '',
                    'fuc_name': 'UserMod#reset_pwd'
                }
            except Exception, e:
                return {
                    'success': False,
                    'reset_code': '',
                    'error': 'reset_pwd: %s' % e,
                    'fuc_name': 'UserMod#reset_pwd'
                }
        else:
示例#5
0
文件: user.py 项目: laurencechan/test
class User:
    def __init__(self, **kwargs):
        for i in ['ident', 'pwd', 'apikey', 'visitor']:
            if i in kwargs:
                break
        else:
            raise Exception('Login Fail')
        self.__conn_user = MongoHelp('User')
        self.__conn_setting = MongoHelp('Setting').find_one(
            {'set_type': 'system'})
        self.user_data, self.is_login, self.group, self.permission = None, False, None, None
        if kwargs.get('visitor', False):
            self.__visitor_login()
        elif kwargs.get('apikey', False):
            self.__apikey_login(kwargs['apikey'])
        else:
            self.__user_login((kwargs['ident'], kwargs['pwd']))
        pass

    def __user_login(self, user_ident):
        self.__salt = self.__conn_setting['user_salt']
        if user_ident[0] == 'super':
            if self.__conn_setting['super_user']['disable']:
                print 'Super is Disable'
                user_data = None
            else:
                user_data = self.__conn_user.find_one(
                    {'_id': self.__conn_setting['super_user']['_id']})
        else:
            if user_ident[0].isdigit() and len(user_ident[0]) == 11:
                ident = 'phone'
            else:
                ident = 'username'
            user_data = self.__conn_user.find_one({ident: user_ident[0]})
        if user_data:
            if user_data['username'] == 'super':
                salt = self.__conn_setting['super_user']['salt']
            else:
                salt = self.__salt
            if user_data['password'] == hashlib.md5(salt + user_ident[1] +
                                                    salt).hexdigest():
                self.user_data = user_data
                self.is_login = True
                self.group = user_data['permission']['group']
                self.permission = user_data['permission']['tag']
                print user_data['username'] + ' is Login'
            else:
                print user_data['username'] + ' Login Fail'
            if 'reset_code' in user_data.keys():
                self.__conn_user.fix_one({'_id': user_data['_id']},
                                         {'reset_code': 1}, '$unset')
        else:
            print 'User not found'

    def __visitor_login(self):
        if self.__conn_setting['vistor_user']['disable']:
            raise
        visitor = self.__conn_user.find_one(
            {'_id': self.__conn_setting['vistor_user']['_id']})
        self.user_data = visitor
        self.is_login = True
        self.group = visitor['permission']['group']
        self.permission = visitor['permission']['tag']
        print visitor['username'] + ' is Login'

    def __apikey_login(self, apikey):
        if not self.__conn_setting.get('api_func', True):
            raise
        api_user = self.__conn_user.find_one({'apikey': apikey})
        if api_user:
            self.user_data = api_user
            self.is_login = True
            self.group = api_user['permission']['group']
            self.permission = api_user['permission']['tag']
            print api_user['username'] + ' is Login'
        else:
            print apikey + ' Login Fail'

    def set_apikey(self):
        if not self.is_login:
            return {
                'success': False,
                '_id': '',
                'apikey': '',
                'error': 'Login Failed'
            }
        user_apikey = self.user_data.get('apikey', '')
        if user_apikey:
            return {
                'success': True,
                '_id': self.user_data['_id'],
                'apikey': user_apikey,
                'error': ''
            }
        import random
        while True:
            if not self.__conn_user.find({'apikey': user_apikey}):
                break
            user_apikey = hashlib.md5("".join(random.sample(
                ran_char, 32))).hexdigest().upper()
        is_set = self.__conn_user.fix_one({'_id': self.user_data['_id']},
                                          {'apikey': user_apikey})
        if is_set:
            return {
                'success': True,
                '_id': self.user_data['_id'],
                'apikey': user_apikey,
                'error': ''
            }
        else:
            return {
                'success': False,
                '_id': self.user_data['_id'],
                'apikey': '',
                'error': 'Set apikey Failed'
            }

    def unset_apikey(self):
        if not self.is_login:
            return {
                'success': False,
                '_id': '',
                'apikey': '',
                'error': 'Login Failed'
            }
        is_set = self.__conn_user.fix_one({'_id': self.user_data['_id']},
                                          {'apikey': 1}, '$unset')
        if is_set:
            return {'success': True, '_id': self.user_data['_id'], 'error': ''}
        else:
            return {
                'success': False,
                '_id': self.user_data['_id'],
                'error': 'Unset apikey Failed'
            }

    def info_update(self, info):
        if not self.is_login:
            return {
                'success': False,
                '_id': '',
                'apikey': '',
                'error': 'Login Failed'
            }
        user_data = self.user_data
        user_id = user_data['_id']
        user_default = MongoHelp('Setting').find_one({'set_type': 'raw_data'
                                                      })['user_default']
        for n in info.keys():
            if n not in ['username', 'password'] and n in user_default.keys():
                if n != 'permission':
                    if isinstance(info[n], str):
                        user_data[n] = info[n]
                    elif isinstance(info[n], dict):
                        for m in info[n].keys():
                            user_data[n][m] = info[n][m]
        for i in ['_id', 'username', 'password']:
            del user_data[i]
        is_update = self.__conn_user.fix_one({'_id': user_id}, user_data)
        if is_update:
            return {'success': True, '_id': user_id, 'apikey': '', 'error': ''}
        else:
            return {
                'success': False,
                '_id': user_id,
                'apikey': '',
                'error': 'Update Failed'
            }

    pass
示例#6
0
class ContentMod(ClassTool):
    def __init__(self, user_info=None):
        ClassTool.__init__(self)
        self.__conn = MongoHelp('Content')
        from user import User
        if isinstance(user_info, User):
            self.user = user_info

    def __set_classid(self, class_id):
        self.req_permisssion = class_id
        self.__class_id = class_id
        self.__class_info = MongoHelp('Column').find_one({'class_id': class_id})
        if self.__class_info['type'] not in MongoHelp('Setting').find_one(
                {'set_type': 'content'})['content_default'].keys():
            raise Exception('Content set Error: %s' % self.__class_info['type'])
        self.__content_default = MongoHelp('Setting').find_one(
            {'set_type': 'content'})['content_default'][self.__class_info['type']]['data']

    @staticmethod
    def _set_type(default, input_data):
        if isinstance(default, unicode):
            if default.split(',')[0] == 'str':
                default = input_data
            elif default.split(',')[0] == 'int':
                default = int(input_data)
            elif default.split(',')[0] == 'datetime':
                default = datetime.datetime.strptime(input_data, "%Y-%m-%d %H:%M:%S").date()
                # default = input_data
            else:
                default = default.split(',')[2]
            return default
        elif isinstance(default, dict):
            new = {}
            for n in default.keys():
                new[n] = ContentMod._set_type(default[n], input_data[n])
            return new
        elif isinstance(default, list):
            new = []
            for n in input_data:
                new.append(ContentMod._set_type(default[0], n))
            return new

    def _data_format(self, json_data):
        format_data = dict(content_type=self.__class_info['type'],
                           status='normal',
                           reviewed=False,
                           class_id=self.__class_id,
                           statistics={})
        format_data['data'] = ContentMod._set_type(self.__content_default, json_data)
        return format_data

    @ModVerify
    def insert(self, class_id, content_json):
        self.__set_classid(class_id)
        content_json['author_name'] = self.user.user_data['username']
        content_json['author_id'] = self.user.user_data['_id']
        content_data = self._data_format(content_json)
        content_data['addtime'] = datetime.datetime.now()
        content_data['title'] = content_data['data'].get('title', '')
        content_data['author_id'] = self.user.user_data['_id']
        is_insert = self.__conn.insert(content_data)
        return self._sys_msg(is_insert, 'Grant Fail', {'_id': is_insert})

    @ModVerify
    def modify(self, content_id, content_json):
        content_json['author_name'] = self.user.user_data['username']
        content_json['author_id'] = self.user.user_data['_id']
        content_data = self._data_format(content_json)
        is_update = self.__conn.fix_one({'_id': content_id}, content_data)
        return self._sys_msg(is_update, 'Grant Fail', {'_id': content_id})

    @ModVerify
    def remove(self, content_id):
        is_remove = self.__conn.remove({'_id': content_id})
        return self._sys_msg(is_remove, 'Grant Fail', {'_id': content_id})

    @ModVerify
    def review(self, content_id, is_pass=True):
        is_reviewed = self.__conn.fix_one({'_id': content_id}, {'reviewed': is_pass})
        return self._sys_msg(is_reviewed, 'Grant Fail', {'_id': content_id})

    @ModVerify
    def details(self, _id):
        found = self.__conn.find_one({'_id': _id})
        return self._sys_msg(found, 'Not Found')

    @ModVerify
    def get_list(self, ident=None, limit=10, skip=0):
        ident_json = {}
        if isinstance(ident, dict):
            ident_json.update(ident)
        found = self.__conn.conn.find(ident_json, {'data': 0}).limit(limit).skip(skip)
        total = found.count()
        found = self.__conn.id_format(found)
        reviewed = self.__conn.conn.find({'reviewed': True}).count()
        return self._sys_msg(found, 'Grant Fail', {'page': {'total': total, 'limit': limit,
                                                            'skip': skip, 'reviewed': reviewed}})

    pass