def _verify_user(self): try: type_statusUser = type_status_user(self.user) if not type_statusUser: raise ErrorRun_impl('{0} Нет данных Type_status_user'.format( self.s_err)) if type_statusUser.levelperm > 39: return advData = AdvUser.get_advData(self.user) if advData is None: raise ErrorRun_impl( '{0} нет данных advData for self.user'.format(self.s_err)) logincl = Res_proc.FN_get_val_dict(advData, 'logincl') pswcl = Res_proc.FN_get_val_dict(advData, 'pswcl') # Обновление по значениям, полученным из гостВхода if logincl != self.logincl or pswcl != self.pswcl: _dict = dict(logincl=self.logincl, pswcl=self.pswcl) self._upd_quest(self.user.advuser, _dict, True) except Exception as ex: self._init_err(ex, self.s_err_serv)
def save_upd(self, arg_user: User, arg_parentuser) -> Res_proc: """ Процедура обработки обновления профиля клиента """ from app.com_serv_dbase.serv_modf_profil import serv_add_profil from .serv_sprstatus import Com_proc_sprstatus try: res_proc = Res_proc() cd_dict = self.cleaned_data s_error = 'ValueError##advuser.form.Base_profilForm.save_upd' user_head = getUser(arg_parentuser) user = getUser(arg_user) js_struct = Com_proc_advuser.get_js_struct(user) js_struct = self.com_modf_quest( user_head, js_struct) # верификация pswcl and logincl cd_dict['js_struct'] = js_struct cd_dict['username'] = user.username cd_dict = clear_space(cd_dict) cd_dict = upd_space_into_empty(cd_dict) res_proc = serv_add_profil(cd_dict, serv_proc='sp_serv_upd_profil') except Exception as ex: res_proc.error = ex return res_proc
def restor_psw(): from app import loadJSON_withTempl from app import Type_value from django.contrib.auth.models import User res_proc = Res_proc() _lst = [] s_err = 'ResError##advuser.modify_serv.restor_psw' try: path = Type_value.init_formatTempl('advuser/arg_restor_psw', 'jsn') dict_psw = loadJSON_withTempl(path) for item in dict_psw: username = item[0] psw = item[1] user = getUser(username) if user: user.set_password(psw) _lst.append('{0} обновлено; '.format(username)) else: _lst.append('{0} не найден в User; '.format(username)) res_proc.res_list = _lst except Exception as ex: res_proc.error = ex return res_proc
def conv_str_json_test(cls, arg_lst): res = Res_proc(res=False) obj_appl = jsonTest obj_modl = None for item in arg_lst[1].split('#'): _error = None if obj_modl: if hasattr(arg_obj_appl, item): obj_modl = getattr(obj_modl, item) else: _error = True else: if hasattr(obj_appl, item): obj_modl = getattr(obj_appl, item) else: _error = True if _error: res.error = 'Атрибут %s не найден' % item return res res.res = True res.res_obj = obj_modl return res
def SelectFilesTesting(cls, arg_par_testing): list_res_test = [] path_file_arg = arg_par_testing.PR_path_file_arg for file in arg_par_testing.PR_files: arg_proc = dict(file=path_file_arg + file, base_path=path_file_arg) res_arr_dict = cls.Testing(arg_proc) if get_valFromDict(res_arr_dict, 'res') == -300: return Res_proc(res=-300, error=get_valFromDict(res_arr_dict, 'error'), res_list=list_res_test) if get_valFromDict(res_arr_dict, 'list_res_test'): for item in get_valFromDict(res_arr_dict, 'list_res_test'): list_res_test.append(item) else: # Поставить заглушку и вывести сообщение отсутствия данных в файле тестирования list_res_test.append( dict(empty_data='В файле %s нет данных для тестирования ' % file)) #list_res_test.append(get_valFromDict(res_arr_dict,'list_res_test')) return Res_proc(res=200, mes='Ok', res_list=list_res_test)
def save_status_into_db(self, arg_dict: dict, arg_user: User): """ Запись изменений status в БД увеличение статуса или изменении структуры status.* """ res_proc = Res_proc() try: rec = AdvUser.objects.get(pk=arg_user) js_struct = arg_dict['js_struct'] status_id = arg_dict['status_id'] advData = json.loads(rec.advData) self.clear_data_status( advData) # очистить от прежних значений status.* advData.update(js_struct) # Обновление новыми значениями status.* advData.update(dict(status_id=status_id, status=status_id)) rec.status_id = status_id rec.js_struct = json.dumps(js_struct, ensure_ascii=False) rec.advData = json.dumps(advData, ensure_ascii=False) rec.save() res_proc.res = True except Exception as ex: res_proc.error = ex return res_proc
def get_parentuser_02(cls, arg_user) -> User: """ return User for parentuser or None Отличается от get_parentuser -> Res_proc.any_str """ from .models import AdvUser res_proc = Res_proc() try: user = getUser(arg_user) if user is None: cls._run_raise(f'get_parentuser: arg_user не определен') if user.is_superuser: parentuser = cls.get_user_head() res_proc.any_str = parentuser.username return res_proc row = AdvUser.objects.get(pk=user) parentuser = row.parentuser parentuser = getUser(parentuser) except Exception as ex: return None return parentuser
def com_modf_quest(cls, arg_head, arg_jsstruct=None, new_pswd=False) -> dict: """ Обобщенная процедура обработки quest верификация/изменение pswcl and logincl --------------------------- arg_head используется для загрузки pswcl and logincl as default arg_user для загрузки js_struct arg_user==None создается js_struct else loadFrom advuser_advuser.js_struct return js_struct """ js_struct = dict() if arg_jsstruct: js_struct = arg_jsstruct if new_pswd: js_struct['pswcl'] = getPassword_cl() js_struct['logincl'] = getLogin_cl() else: user_head = getUser(arg_head) if Res_proc.FN_get_val_dict(js_struct, 'pswcl') is None: js_struct_head = Com_proc_advuser.get_js_struct(user_head) js_struct['pswcl'] = js_struct_head['pswcl'] if Res_proc.FN_get_val_dict(js_struct, 'logincl') is None: js_struct['logincl'] = getLogin_cl() return js_struct
def save(self, arg_user: User) -> Res_proc: """ Сохранение пароля пользователя проекта arg_user используется для значений password from User """ from django.contrib.auth.hashers import make_password from app.com_serv_dbase.serv_modf_profil import user_upd_psw res_save = Res_proc() try: psw = self.cleaned_data['password'] password = make_password(psw) user = getUser(arg_user) status = Com_proc_sprstatus.getStatus_or_None(user) dc_sp = dict(username=user.username, password=password, pswcl=psw, status_id=status.pk) res_proc = user_upd_psw(dc_sp) res_save.mes = 'Пароль пользователя изменен' except Exception as ex: res_save.error = ex return res_save
def update_user(cls, user, arg_dict, commit=True): from app.models import spr_fields_models res = Res_proc(res=False) # Блок заполнения полей User для существующего пользователя if not isinstance(user, User): user = getUser(user) if user is None: res.error = 'ValueError##modify_models.Modify_user.update_user user Нет данных для логина стр.213' return res # Заполнение списка полей, используемых для этой модели arg_dict['list_fieldsModel'] = spr_fields_models.get_list_fields( 'user', onlyKeys=True) init_user = Init_model(user, arg_dict) res.res_model = user if commit: try: user.save(force_update=True) res.mes = 'Выполнено обновление модели User' res.res = True except Exception as ex: res.error = ex return res else: res.mes = 'Заполнены данные для модели User' res.res = True return res
def test_res_proc(): from app import Res_proc from app import ErrorRun_impl try: res = [] res_proc = Res_proc() s_empty = res_proc.PR_empty res_proc.any_str = s_empty res_proc.res_dict = dict(par=1) res_proc.res_list = [1,2] val_dict = res_proc.FN_get_val_dict(dict(par='anyDataDict'), 'par') res.append(val_dict + '; ') s_proc = '{0} {1} {2}'.format(res_proc.FN_empty(), res_proc.FN_exist(), res_proc.PR_notRecord ) res.append('## ' + s_proc) res_proc.error = ErrorRun_impl('ValueError##Пробное исключение') s_res = str(res_proc) res.append(s_res) return res except Exception as ex: return str(ex)
def resubm_parentuser(arg_user): def run_raise(s_arg): s_err = 'ResError##advuser.modify_serv.resubm_parentuser' raise ErrorRun_impl('{0} {1}'.format(s_err, s_arg)) # ----------------------------------------------------------- res_proc = Res_proc() lst = [] try: user = getUser(arg_user) if user is None: run_raise('arg_user не определен') user_typeStatus = type_status_user(user) if not user_typeStatus: run_raise('нет данных для статуса') #if user_typeStatus.levelperm < 40: # run_raise('нет прав на переопределение parentuser') res_parentuser = AdvUser.get_parentuser(user) if not res_parentuser: run_raise('нет данных для руководителя группы') _parentuser = res_parentuser.any_str level_user = user_typeStatus.levelperm rows = AdvUser.objects.filter(parentuser=user, status__levelperm__gte=10, status__levelperm__lt=level_user) if rows.exists(): for row in rows: row.parentuser = _parentuser advData = json.loads(row.advData) advData['parentuser'] = _parentuser row.advData = json.dumps(advData, ensure_ascii=False) row.save() lst.append('{0} обновл. pswcl; '.format(row.user.username)) res_proc.res = True res_proc.res_list = lst except Exception as ex: res_proc.error = ex return res_proc
def create_templDict_qust(cls, arg_user, arg_pswcl=None): from .serv_sprstatus import Com_proc_sprstatus res_proc = Res_proc() def run_raise(s_arg, showMes=None): s_err = 'advuser.forms.Base_profForm.create_templDict_quest' if showMes: raise ErrorRun_impl('verify##{0}'.format(s_arg)) else: raise ErrorRun_impl('{0} {1}'.format(s_err, s_arg)) try: _username = '' _user = getUser(arg_user) if _user is None: _username = arg_user else: _username = _user.username logincl = getLogin_cl() pswcl = '' if arg_pswcl: pswcl = arg_pswcl else: res_pswcl = getPassword_cl() if res_pswcl: pswcl = res_pswcl else: ErrorRun_impl( 'NotData##advuser.forms.Base_profForm.create_templDict_quest пароль не создан' ) _dict = dict( username=logincl, first_name='Гость', last_name='сайта', password=pswcl, pswcl=pswcl, parentuser=_username, status_id=Com_proc_sprstatus.get_status_qust_simp().pk, sendMes='false', pol='-') res_proc.res_dict = _dict except Exception as ex: res_proc.error = ex return res_proc
def add_advuser(user, arg_dict, commit=True): res = Res_proc(res=False) if not isinstance(user, User): raise ValueError('Отсутствует аргумент User') advuser = None advData = None advuser = AdvUser() advuser.user = user # Заполнение списка полей, используемых для этой модели arg_dict['list_fieldsModel'] = spr_fields_models.get_list_fields( 'advuser', onlyKeys=True, exclude='advData') init_advUser = Init_model(advuser, arg_dict) res.res_model = advuser if commit: try: advuser.save() res.mes = 'Создана модель AdvUser' res.res = True return res except Exception as ex: res.error = ex return res else: res.mes = 'Заполнены данные для профиля' res.res = True return res
def _ver_exists_quest(self): try: row_cl = AdvUser.objects.filter(parentuser=self.user.username, status__levelperm=10) if row_cl.exists(): row_cl = row_cl.last() self.logincl = row_cl.user.username advuser = row_cl.user.advuser advData = json.loads(advuser.advData) _pswcl = Res_proc.FN_get_val_dict(advData, 'pswcl') if _pswcl is None: res_pswcl = get_pswcl_fromHead(self.user) if res_pswcl: _pswcl = res_pswcl.any_str self._upd_quest(row_cl, dict(pswcl=_pswcl)) else: raise ErrorRun_impl( '{0} pswcl не определен из get_pswcl_fromHead'. format(self.s_err)) else: self.pswcl = _pswcl else: self._add_quest(self.user) except Exception as ex: self._init_err(ex, self.s_err_serv)
def _initData_quest(self): try: row_cl = AdvUser.objects.filter(user=self.user_quest) if row_cl.exists(): row_cl = row_cl.first() advuser = row_cl.user.advuser advData = json.loads(advuser.advData) _pswcl = Res_proc.FN_get_val_dict(advData, 'pswcl') if _pswcl is None: _pswcl = generate_pswcl() if _pswcl: self._upd_quest(row_cl, dict(pswcl=_pswcl)) else: raise ErrorRun_impl( '{0} pswcl не определен из advuser.forms.Base_profilForm.generate_pswcl' .format(self.s_err)) else: self.pswcl = _pswcl else: self._add_quest(self.user_quest) except Exception as ex: self._init_err(ex, self.s_err_serv)
def save_add(self, arg_user:User)->Res_proc: """ Процедура обработки добавления профиля клиента """ from django.contrib.auth.hashers import make_password from app.com_serv_dbase.serv_modf_profil import serv_add_profil from app.models import spr_fields_models res_proc = Res_proc() cd_dict = self.cleaned_data s_error = 'ValueError##advuser.form.Base_profilForm.save_add' try: parentuser = Com_proc_advuser.get_user_cons(arg_user) if parentuser is None: run_raise(s_error+' Консультант гостВхода не найден') status = Com_proc_sprstatus.get_status_by_levelperm(20) statusID = status.pk levelperm_sel = status.levelperm # Заполнение структуры js_struct # from spr_fields_models.js_data where levelperm = levelperm_sel js_struct = spr_fields_models.get_js_struct(levelperm_sel) js_struct['pswcl'] = getPassword_cl() js_struct['idcomp'] = cd_dict.get('idcomp') or 'empty' cd_dict.update( dict( parentuser = parentuser.username, password = make_password(js_struct['pswcl']), username = getLogin_cl(), status_id= statusID, full_name= cd_dict['first_name'] + ' ' + cd_dict['last_name'], js_struct = js_struct )) cd_dict = clear_space(cd_dict) cd_dict = upd_space_into_empty(cd_dict) res_proc = serv_add_profil(cd_dict) except Exception as ex: res_proc.error = ex return res_proc
def sp_modf_data(arg_dc: dict, serv_proc='sp_serv_add_profil'): """ Процедура взаимодействия с сервПроцедурой Общая для ВСЕх операций взаимодействия с БД """ from ..com_data.write_exception_into_log import PM_write_except_into_log as write_into_log res_proc = Res_proc() s_error_not_show = 'verify#app.com_serv_dbase.serv_modf_profil.sp_modf_data' try: con = getConnection() s_dict = json.dumps(arg_dc, ensure_ascii=False) with con.cursor() as cur: cur.callproc(serv_proc, (s_dict, )) res_call = cur.fetchall()[0] # возврат из сервПроцедуры в виде select {res:ok/err, mes:ok/strMessage} as res # {"mes": "Создан профиль: mysql_test", "res": "ok", "data": {"username": "******", "str_status": "Участник проекта"}} # {"mes": "Повторный ввод данных профиля: insert into auth_user", "res": "err"} res_call = res_call['res'] res_call_dc = json.loads(res_call) if res_call_dc[ 'res'] == 'err': # элемент, созданный в процессе проверки входящих данных err = None if res_call_dc.get('err'): err = res_call_dc['err'] else: err = res_call_dc[ 'mes_error'] # элемент, который используется в блоке обработчика исключений сервПроцедуры write_into_log(s_error_not_show, res_call_dc['mes_error']) run_raise('Ошибки исходных данных', showMes=True) res_data = res_call_dc['data'] dc = dict(mes=res_call_dc['mes'], data_mes=res_data['mes']) res_proc.res_dict = dc res_proc.res = True except Exception as ex: res_proc.error = ex return res_proc
def get_parentuser(cls, arg_user) -> str: """ Извлекает строку User.username return Res_proc.any_str """ s_err = 'get_parentuser' res_proc = Res_proc() try: user = getUser(arg_user) if user is None: cls._run_raise(f'{s_err} arg_user не определен') if user.is_superuser: parentuser = cls.get_user_head() res_proc.any_str = parentuser.username return res_proc res_advUser = servAdvUser_get_advUser(user) if not res_advUser: cls._run_raise(f'{s_err} нет данных по AdvUser') advuser = res_advUser.res_model parentuser = advuser.parentuser # Проверка, что login существует user_parentuser = getUser(parentuser) if user_parentuser is None: cls._run_raise( f'{s_err} parentuser не найден в справочнике auth_user') # Проверка соответствия в advData[parentuser] == advuser.parentuser advData = json.loads(advuser.advData) if user_parentuser.username == advData['parentuser']: res_proc.any_str = user_parentuser.username else: cls._run_raise( f'{s_err} advData[parentuser] != advuser.parentuser') except Exception as ex: res_proc.error = ex return res_proc
def serv_get_data_prof(arg_user, str_levelperm=None, num_rows=0, sel_page=1, num_count=False): """ Выборка данных профиля для отображения в виде списка пользователей проекта Предназначено для рукПроекта --------------------------------- arg_user Пользователь для которого делается фильтрация данных str_levelperm уровень levelperm (значение = None -> ВСЕх уровней ) num_rows кол-во записей в части (значение = 0 -> ВСЕ записи) sel_page Номер выбираемой части """ from ..com_data.write_exception_into_log import PM_write_except_into_log as write_into_log res_proc = Res_proc() s_error_not_show = 'verify#app.com_serv_dbase.serv_modf_profil.serv_add_profil' user = getUser(arg_user) try: con = getConnection() if str_levelperm is None: str_levelperm = '30,40,70' dc_arg = dict(username=user.username, lstlevelperm=str_levelperm, num_rows=num_rows, sel_page=sel_page) s_dict = json.dumps(dc_arg, ensure_ascii=False) lst_res = [] with con.cursor() as cur: cur.callproc('sp_serv_dataprof', (s_dict, )) res_call = cur.fetchall() res_proc.res_list = res_call res_proc.res = True except Exception as ex: res_proc.error = ex return res_proc
def get_dictData_init_Form_regQuest(user): """ Инициализация базовых данных для измПрофиля участПроекта """ from .serv_advuser import servAdvUser_get_advUser res_proc = Res_proc(res=False) perm_type = 'User, str, int' s_typeUser = type(user).__name__ # ----------------- инициализация базовых параметров ------------------- if 2 > 1: if user is None: res_proc.error = 'modify_models.get_dictData_init_Form_regQuest: user None' return res_proc if s_typeUser not in perm_type: res_proc.error = 'modify_models.get_dictData_init_Form_regQuest: user не соответствие типа' return res_proc if s_typeUser in ('str', 'int'): _user = getUser(user) if _user is None: res_proc.error = 'modify_models.get_dictData_init_Form_regQuest: user нет в БД' return res_proc else: user = _user if user.is_superuser: # if type_status.is_proj_sadm: res_proc.error = 'Профиль superuser не меняется' return res_proc advuser = servAdvUser_get_advUser(user) if advuser is None: res_proc.error = 'Для {0} нет данных для профиля'.format( user.get_full_name()) return res_proc # ------------- Конец блока инициализации базовых параметров ------------- dict_models = initDict_allModels(user) for key, val in dict_models.items(): if val == res_proc.PR_empty: dict_models[key] = None res_proc.res = True res_proc.res_dict = dict_models return res_proc
def save(self, arg_session:dict)->Res_proc: """ Сохранение пароля пользователя проекта arg_session используется для значений upd_username """ from django.contrib.auth.hashers import make_password from app.com_serv_dbase.serv_modf_profil import user_upd_psw res_save = Res_proc() try: cd_clean = self.cleaned_data user = getUser(arg_session['upd_username']) if user is None: run_raise('Логин не определен', showMes=True) #user.password = make_password(cd_clean['password']) type_status = type_status_user(user); statusID = type_status.statusID pswcl = None if type_status.levelperm >=30: pswcl = Com_proc_advuser.get_val_from_advData(user, 'pswcl') dc_sp = dict( username = user.username, password = make_password(cd_clean['password']), pswcl = pswcl or 'empty', status_id = statusID ) res_proc = user_upd_psw(dc_sp); res_save.mes = 'Пароль пользователя изменен' #user.save() #res_save.res = True res_save.mes = 'Пароль пользователя обновлен' except Exception as ex: res_save.error = ex return res_save
def save(self, arg_user, arg_parentuser)->Res_proc: from app.com_serv_dbase.serv_modf_profil import serv_add_profil res_proc = Res_proc() cd_dict = self.cleaned_data s_error = 'ValueError##advuser.form.UpdProf_memberForm.save' try: user = getUser(arg_user) if user is None: run_raise(s_error + ' Пользователь не найден в БД') user_head = getUser(arg_parentuser) _advdata = Com_proc_advuser.get_advData(user) # Параметр, который не используется в форме, но обязателен cd_dict['sendMes'] = _advdata['sendMes'] js_struct = Com_proc_advuser.get_js_struct(user) js_struct['idcomp'] = cd_dict['idcomp'] # верификация а clean() js_struct = self.com_modf_quest(user_head, js_struct) # верификация pswcl and logincl # ----------- Подготовка dict for servProc ---------------- cd_dict.update( dict(username=user.username, js_struct = js_struct )) # удаление пробелов. Для подстраховки cd_dict = clear_space(cd_dict) cd_dict = upd_space_into_empty(cd_dict) # дополнительное преобразование # Запись профиля в БД by servProc res_proc = serv_add_profil(cd_dict, serv_proc='sp_serv_upd_profil') except Exception as ex: res_proc.error = ex; return res_proc
def user_upd_psw (arg_dc:dict)->Res_proc: from . .com_data.write_exception_into_log import PM_write_except_into_log as write_into_log s_error_not_show = 'verify#app.com_serv_dbase.serv_modf_profil.serv_add_profil' res_proc = Res_proc() try: con = getConnection() s_dict = json.dumps(arg_dc, ensure_ascii=False) with con.cursor() as cur: cur.callproc('sp_user_upd_psw', (s_dict,)) res_call = cur.fetchall()[0] # {"res": "err", "mes_error": "текст сообщений ошибки"} # {"mes": "Обновление пароля: XEMP-9069", "res": "ok", "data": {"username": "******"}} res_call = res_call['res'] res_call_dc = json.loads(res_call) if res_call_dc['res'] == 'err': # элемент, созданный в процессе проверки входящих данных write_into_log(s_error_not_show, res_call_dc['mes_error'] ); run_raise('Ошибки исходных данных', showMes=True) res_data = res_call_dc['data'] res_proc.res = True res_proc.any_str = res_data['username'] res_proc.mes = 'Изменен пароль: ' + res_data['username'] except Exception as ex: res_proc.error = ex return res_proc
def save(self, arg_username, arg_parentuser): """ Сохранение изменений профиля arg_username для обработки профиля arg_parentuser для доступа к значению pswcl на уровне рукГруппы """ from app.com_serv_dbase.serv_modf_profil import serv_add_profil res_proc = Res_proc() try: user = getUser(arg_username) if user is None: run_raise('Сбой обработки профиля: пользователь не определен', showMes=True) user_head = getUser(arg_parentuser) cd_dict = self.cleaned_data cd_dict['username'] = user.username js_struct = Com_proc_advuser.get_js_struct(user) js_struct['idcomp'] = cd_dict[ 'idcomp'] # верификация idcomp в clean() js_struct = self.com_modf_quest( user_head, js_struct) # верификация pswcl and logincl cd_dict['js_struct'] = js_struct # удаление пробелов. Для подстраховки cd_dict = clear_space(cd_dict) cd_dict = upd_space_into_empty(cd_dict) res_proc = serv_add_profil(cd_dict, serv_proc='sp_serv_upd_profil') except Exception as ex: res_proc.error = ex return res_proc
def add_user(cls, arg_dict: dict): if not isinstance(arg_dict, dict): raise ValueError('arg_dict не соответствие типа') res = Res_proc() ext_dict = Ext_dict(arg_dict) tmp_dict = spr_fields_models.get_list_fields('user') ext_dict.modifyExtDict_bySelf_dict(tmp_dict) tmp_dict.update(dict(password=ext_dict.get_val('password'))) user = CreateUser_ext.create_user( username=tmp_dict['username'], email=tmp_dict['email'] if tmp_dict['email'] != 'empty' else None, password=tmp_dict['password']) user.first_name = tmp_dict['first_name'] user.last_name = tmp_dict['last_name'] res.res_model = user try: user.save() res.mes = 'Создан профиль участника проекта' res.res = True return res except Exception as ex: res.error = ex return res
def verify_yourHead(cls, arg_user, arg_head) -> Res_proc: """ Анализ, что arg_head является рукГруппы или рукПроекта """ res_proc = Res_proc() try: user = getUser(arg_user) user_head = getUser(arg_head) if user.username == user_head.username: res_proc.mes = 'Собственный профиль изменяется из панели \"Профиль\"' cls._run_raise(res_proc.mes, True) if user is None or user_head is None: res_proc.mes = 'Пользователь/рукГруппы не определен' cls._run_raise(res_proc.mes, True) head_typeStatus = type_status_user(user_head) if not head_typeStatus: res_proc.mes = 'Статус рукГруппы не определен' cls._run_raise(res_proc.mes, True) if head_typeStatus.levelperm < 40: res_proc.mes = 'Статус пользователя не соответсвует рукГруппы' cls._run_raise(res_proc.mes, True) # ------------- конец блока верификации -------------- res_parentuser = cls.get_parentuser(user) if not res_parentuser: res_proc.mes = 'РукГруппы не определен' cls._run_raise(res_proc.mes, True) parentuser = res_parentuser.any_str if user_head.username == parentuser: # верификация, что user_head явлРукГруппы res_proc = True else: res_proc.mes = f'{user_head.get_full_name()} не является рукГруппы для {user.username}' cls._run_raise(res_proc.mes, True) except Exception as ex: res_proc.error = ex return res_proc
def upd_pswcl_quest(arg_user, arg_pswcl=None): res_proc = Res_proc() def run_raise(s_arg, showMes=None): s_err = 'advuser.modify_serv.upd_pswcl_quest' if showMes: raise ErrorRun_impl('verify##{0}'.format(s_arg)) else: raise ErrorRun_impl('{0} {1}'.format(s_err, s_arg)) try: user = getUser(arg_user) if user is None: run_raise('arg_user не найден в User') if arg_pswcl is None: res_pswcl = get_pswcl_fromHead(user) if not res_pswcl: run_raise( 'пароль гостВхода не определен из get_pswcl_fromHead') arg_pswcl = res_pswcl.any_str # ---------------- конец блока предОбработки входящих параметров --------- advuser = AdvUser.get_advUser(user) if not advuser: run_raise('нет данных для advuser ' + user.username) FM_init_advData(advuser, dict(pswcl=arg_pswcl)) advuser.save() res_proc.any_str = arg_pswcl res_proc.res = True except Exception as ex: res_proc.error = ex return res_proc
def get_pswcl_fromHead(arg_user): res_proc = Res_proc() s_notData = 'NotData##advuser.modify_serv.get_pswcl_fromHead:' try: user = getUser(arg_user) if user is None: raise ErrorRun_impl('{0} arg_user нет в БД'.format(s_notData)) type_status = type_status_user(user) if not type_status: raise ErrorRun_impl('{0} {1} нет статуса'.format( s_notData, user.username)) user_head = None if type_status.levelperm > 39: user_head = user else: res_head = AdvUser.get_head_user(user) user_head = res_head.res_model if user_head is None: raise ErrorRun_impl('{0} {1} нет данных для рукГруппы '.format( s_notData, user.username)) advData = AdvUser.get_advData(user_head) pswcl = advData.get('pswcl') if pswcl is None: raise ErrorRun_impl('{0} {1} advData нет pswcl'.format( s_notData, user.username)) res_proc.any_str = pswcl except Exception as ex: res_proc.error = ex return res_proc
def conv_pol(cls, arg_char: str): s_pol = '-' _empty = Res_proc.FN_empty() pol = arg_char or cls.pol if pol == _empty: pol = '-' if pol != '-': for p in POL: if p[0] == pol.upper(): s_pol = p[1] break return s_pol