예제 #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
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
예제 #3
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:
예제 #4
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