def add_user(self, cn, sn, uid_number, gid_number=100, gecos=None, mail=None, display_name=None, shadow_min=None, shadow_max=None, shadow_inactive=None, shadow_warning=None, shadow_last_change=None, skip_event_callback=False): # check value if strings.is_blank(cn): raise Exception('cn cannot be blank') if strings.is_blank(sn): raise Exception('sn cannot be blank') if num.safe_int(uid_number) <= 1000: raise Exception('uidNumber should > 1000') attributes = { 'cn': cn, 'uid': cn, 'sn': sn, 'uidNumber': num.safe_int(uid_number), 'gidNumber': num.safe_int(gid_number), 'homeDirectory': '/home/' + cn, 'loginShell': '/bin/bash', 'userPassword': '******', 'sudoUser': cn, 'sudoHost': 'ALL', 'sudoOption': '!authenticate', } if gecos is not None: attributes['gecos'] = gecos if mail is not None: attributes['mail'] = mail if display_name is not None: attributes['displayName'] = display_name if shadow_min is not None: attributes['shadowMin'] = shadow_min if shadow_max is not None: attributes['shadowMax'] = shadow_max if shadow_inactive is not None: attributes['shadowInactive'] = shadow_inactive if shadow_warning is not None: attributes['shadowWarning'] = shadow_warning if shadow_last_change is not None: attributes['shadowLastChange'] = shadow_last_change # set 0 to force change password on the first login else: attributes['shadowLastChange'] = self._epoch_days() return self.add( dn=self.assemble_user_dn(cn), object_class=['top', 'posixAccount', 'shadowAccount', 'person', 'inetOrgPerson', 'hostObject', 'sudoRole', 'authorizedServiceObject'], attributes=attributes, event=self.EVENT_ON_USER_CREATED, skip_event_callback=skip_event_callback, )
def groups_save(): dn = request.form.get('dn') ret = {'success': False, 'error_msg': None} try: if strings.is_blank(dn): response = models.add_group( cn=request.form.get('cn'), gid_number=request.form.get('gid'), ) else: response = models.modify_group( cn=request.form.get('cn'), gid_number=request.form.get('gid'), ) if not response: ret['error_msg'] = '添加失败,请查询 slapd.server 日志' else: ret['success'] = True except LDAPBindError: ret['error_msg'] = '授权错误' return ret except Exception as e: logger.error_traceback(LOGGER_NAME) ret['error_msg'] = str(e) return strings.to_json(ret, True)
def set_auth(): function_id = request.form.get("functionId") user_id = request.form.get("userId") _type = int(request.form.get("type")) if strings.is_blank(function_id) or strings.is_blank( user_id) or not objects.contains(_type, 1, 2): return "参数错误!" func = get_function(function_id) if func is None: return "功能不存在" user = get_user_byid(user_id) if user is None: return "用户不存在" _set_auth(function_id, user_id, _type) return "success"
def save_task_schedule(o): if strings.is_blank(o.get('id', None)): raise ValueError('Field "id" not in this object: ' + str(o)) if o['enabled']: # prepare args & kwargs args = None kwargs = None try: args_kwargs = json.loads(o['args']) args = args_kwargs['args'] kwargs = args_kwargs['kwargs'] except: pass # add if o['type'] == 1: # date task.add_date_job(o['func'], o['id'], TASK_DATABASE, args=args, kwargs=kwargs, run_date=time.string_to_date( o['data'], '%Y-%m-%d %H:%M:%S'), timezone='utc') elif o['type'] == 2: # interval interval = json.loads(o['data']) task.add_interval_job(o['func'], o['id'], TASK_DATABASE, args=args, kwargs=kwargs, weeks=num.safe_int(interval['weeks']), days=num.safe_int(interval['days']), hours=num.safe_int(interval['hours']), minutes=num.safe_int(interval['minutes']), seconds=num.safe_int(interval['seconds']), start_date=o['starttime'], end_date=o['endtime'], timezone='utc') elif o['type'] == 3: # cron cron = json.loads(o['data']) task.add_cron_job(o['func'], o['id'], TASK_DATABASE, args=args, kwargs=kwargs, year=cron['year'], month=cron['month'], day=cron['day'], day_of_week=cron['day_of_week'], hour=cron['hour'], minute=cron['minute'], second=cron['second'], start_date=o['starttime'], end_date=o['endtime'], timezone='utc') else: try: task.remove_job(o['id'], TASK_DATABASE) except JobLookupError: pass
def set_auth(): menu_id = request.form.get("menuId") user_id = request.form.get("userId") _type = int(request.form.get("type")) if strings.is_blank(menu_id) or strings.is_blank( user_id) or not objects.contains(_type, 1, 2): return "参数错误!" menu = get_menu(menu_id) if menu is None: return "菜单不存在" user = get_user_byid(user_id) if user is None: return "用户不存在" _set_auth(menu_id, user_id, _type) return "success"
def save(): import pyotp oid = request.form.get("inid") login_id = request.form.get("inloginid") user = {} if strings.is_not_blank(oid): user = um.get_user_byid(oid) if user is None: user = {} else: # 判断重复 duser = um.get_user_byloginid(login_id) if duser is not None: return "用户登录ID已经存在!" user["loginid"] = login_id user["name"] = request.form.get("inname") password = request.form.get("inpassword", None) if strings.is_not_blank(password): # 不为空则重置密码 salt, enpassword = um.make_password(password) user["salt"] = salt user["password"] = enpassword user['email'] = request.form.get('email', None) if strings.is_blank(oid): user['otpsecret'] = pyotp.random_base32() um.save_user(user) return "success"
def qrcode(): user_id = request.args.get('userid', None) user = um.get_user_byid(user_id) if not user: return None if strings.is_blank(user.get('otpsecret')): return None import pyotp import pyqrcode totp = pyotp.TOTP(user.get('otpsecret')) uri = totp.provisioning_uri(user['loginid']) _qrcode = pyqrcode.create(uri) svg_path = os.path.join(setting.get('system.tempdir'), user_id + '.svg') _qrcode.svg(svg_path) @webutils.after_this_response # clear temp file on finish def remove_tmp_file(): if strings.is_not_blank(user_id): try: os.remove(svg_path) except: pass return send_from_directory(setting.get('system.tempdir'), user_id + '.svg', mimetype=net.get_content_type_by_ext('.svg'))
def save(self, table_name, obj): from datetime import datetime assert isinstance(obj, dict) if ("id" not in obj) or strings.is_blank(obj["id"]): obj["id"] = strings.uuid() insert_flag = True else: count = self.create_sql_query("select count(*) c from " + table_name + " where id = :id", id=obj["id"]).fetch()[0]["c"] insert_flag = int(count) == 0 utcnow = datetime.utcnow() obj['utc_modified'] = utcnow if insert_flag: obj['utc_create'] = utcnow arr = [ "insert into", table_name, "(", ",".join(obj.keys()), ") values(", ",".join([":" + k for k in obj.keys()]), ")" ] else: arr = [ "update", table_name, "set", ",".join([k + "=:" + k for k in obj.keys()]), "where id=:id" ] try: self.begin() self.execute(" ".join(arr), **obj) self.commit() except Exception as e: self.rollback() raise e
def add_host(self, cn, cn_list=None, ip_host_number=None, skip_event_callback=False): attributes = {} if strings.is_blank(cn): raise Exception("host cn can't be blank") if cn_list is not None and not isinstance(cn_list, collections.Iterable): raise Exception("host cn_list should be iterable or None") cn_list = set(cn_list).add(cn) attributes['cn'] = cn if cn_list is None else cn_list if ip_host_number is not None: attributes['ipHostNumber'] = ip_host_number return self.add( dn=self.assemble_host_dn(cn), object_class=['top', 'device', 'ipHost'], attributes=attributes, event=self.EVENT_ON_HOST_CREATED, skip_event_callback=skip_event_callback, )
def save(): oid = strings.strip_to_none(request.form.get('id', None)) name = request.form.get('name', None) if strings.is_blank(name): return 'Name cannot be blank' # check duplication cond = {'name': name} if strings.is_not_blank(oid): cond['notid'] = oid if find_settings(**cond).count() > 0: return 'Name has already been exist!' CmSettingCache.save_obj({ 'id': oid, 'name': name, 'value': request.form.get('value', None) }) return 'success'
def users_save(): dn = request.form.get('dn') ret = {'success': False, 'error_msg': None, 'new_password': None} try: if strings.is_blank(dn): response = models.add_user( cn=request.form.get('cn'), sn=request.form.get('sn'), uid_number=request.form.get('uid'), gid_number=request.form.get('gid'), gecos=request.form.get('gecos'), mail=request.form.get('mail'), display_name=request.form.get('displayName'), ) if not response: ret['error_msg'] = '添加失败,请查询 slapd.server 日志' else: # new password new_password = strings.random_str(12) models.reset_password(request.form.get('cn'), new_password) ret['success'] = True ret['new_password'] = new_password else: response = models.modify_user( cn=request.form.get('cn'), sn=request.form.get('sn'), uid_number=request.form.get('uid'), gid_number=request.form.get('gid'), gecos=request.form.get('gecos'), mail=request.form.get('mail'), display_name=request.form.get('displayName'), ) if not response: ret['error_msg'] = '添加失败,请查询 slapd.server 日志' else: ret['success'] = True except LDAPBindError: ret['error_msg'] = '授权错误' return ret except Exception as e: logger.error_traceback(LOGGER_NAME) ret['error_msg'] = str(e) return strings.to_json(ret, True)
def services_save(): cn = request.form.get('cn') services = request.form.get('services') if strings.is_blank(services): return '服务不能为空!' service_list = list( filter(lambda s: strings.is_not_empty(s), map(lambda x: strings.strip_to_empty(x), services.split('\n')))) _type = request.form.get('type') if _type == 'NEW': if models.add_service(cn, authorized_service=service_list): return 'success' else: return '保存失败' elif _type == 'EDIT': if models.modify_service(cn, authorizedService=service_list): return 'success' else: return '保存失败' else: return 'Unknown type: %s' % _type
def commands_save(): cn = request.form.get('cn') commands = request.form.get('commands') if strings.is_blank(commands): return '命令不能为空!' command_list = list( filter(lambda s: strings.is_not_empty(s), map(lambda x: strings.strip_to_empty(x), commands.split('\n')))) _type = request.form.get('type') if _type == 'NEW': if models.add_command(cn, sudo_command=command_list): return 'success' else: return '保存失败' elif _type == 'EDIT': if models.modify_command(cn, sudoCommand=command_list): return 'success' else: return '保存失败' else: return 'Unknown type: %s' % _type
def actual_get(cls, user_id): import copy from operator import itemgetter menus = [] ret = [] if get_user_byid(user_id) is not None: my_menu_db = find_my_menu_db(user_id).order_by('name').fetch() menus = copy.deepcopy(my_menu_db) # serialize for menu in menus: if strings.is_blank(menu.get('parentid')): menu['children'] = [] ret.append(menu) for menu in menus: if strings.is_not_blank(menu.get('parentid')): for m in ret: if m['id'] == menu['parentid']: m['children'].append(menu) for m in ret: m['children'] = sorted(m['children'], key=itemgetter('sort')) return sorted(ret, key=itemgetter('sort'))
def auth_save(): auth = {} # check empty value for k in 'sourceentity', 'sourceid', 'grantentity', 'grantid': val = request.form.get(k) if strings.is_blank(val): return 'empty attribute: ' + k auth[k] = val # check illegal value check_limit = { 'sourceentity': (models.ENTITY_HOST, models.ENTITY_HOSTGROUP, models.ENTITY_COMMAND, models.ENTITY_COMMANDGROUP, models.ENTITY_SERVICE, models.ENTITY_SERVICEPOINT), 'grantentity': (models.ENTITY_USER, models.ENTITY_GROUP), } for k, l in check_limit.items(): if not objects.contains(auth[k], *l): return 'illegal attribute: ' + k # save auth object models.save_auth(auth) return 'success'
def hosts_import(): ret = { 'success_count': 0, 'fail_count': 0, 'error_items': [], } hosts_text = request.form.get('hosts') for host_item in hosts_text.split('\n'): if strings.is_blank(host_item): continue parts = host_item.split() if len(parts) <= 1: ret['error_items'].append(host_item) ret['fail_count'] += 1 continue response = models.add_host(parts[1], parts[2:], parts[0]) if response: ret['success_count'] += 1 else: ret['error_items'].append(host_item) ret['fail_count'] += 1 return strings.to_json(ret, True)