def __import_to_ibs(self): all_users = IBSUserInfo.objects.all() for u in all_users: ibs = IBSManager(username='******') user_id = ibs.get_user_id_by_username(u.user.username) if user_id: self.__update_ibs_user_service(u.user_id, user_id, False) else: print('New User Detected : %s' % u.ibs_uid) ibs_id = create_user_in_ibs(u.user_id, u.user.username, '123456789') self.__update_ibs_user_service(u.user_id, ibs_id, True, True)
def create_user_in_ibs(user_id, username, password): ibs = IBSManager() ibs.add_new_user(username, password, 0) ib_id = ibs.get_user_id_by_username(username) if IBSUserInfo.objects.filter(user_id=user_id).exists(): ibi = IBSUserInfo.objects.filter(user_id=user_id).first() else: ibi = IBSUserInfo() ibi.ibs_uid = int(ib_id) ibi.user_id = int(user_id) ibi.save() update_ibs_user_from_crm(user_id) return ib_id
def add_user_to_tower(user_id, tower): if User.objects.filter(fk_ibs_user_info_user=user_id).exists(): ibm = IBSManager() ibu = IBSUserManager(ibm) ibu.change_user_custom_field( User.objects.get(pk=user_id).fk_ibs_user_info_user.get().ibs_uid, 'building', tower.ibs_name)
def get_username_from_ras(ip_address, failed_ibs_id): try: ibs = IBSManager() online = ibs.get_user_connection_info_1(failed_ibs_id) for o in online: try: if o[4] == ip_address: ras = o[0] util = MKUtils(ras, read_config('ras_username', 'saeed'), read_config('ras_password', 'saeed')) return util.get_user_by_ip(ip_address) except Exception as e: print e.message continue except Exception as e: print e.message
def __get_status__(request): if request.method == 'GET': t = request.GET.get('t') if t == 'd': return HttpResponse(__get_dashboard__(request.user)) elif t == 'ord': return HttpResponse(__get_new_equipment_orders__()) elif t == 'o': ibs = IBSManager() return HttpResponse(ibs.get_online_users_count()) elif t == 'f': return HttpResponse(get_new_uploaded_files()) elif t == 't': return HttpResponse(get_new_tickets(request)) else: return HttpResponse('0')
def configure_static_ip_address(user_id, period=1): try: ibm = IBSManager() ibu = IBSUserManager(ibm) user = User.objects.get(pk=user_id) free_pool = IPPool.objects.filter( Q(fk_user_ip_static_ip=None) | Q(fk_user_ip_static_ip__isnull=False, fk_user_ip_static_ip__is_deleted=True)).first() if UserIPStatic.objects.filter( user=user_id, release_date__gte=datetime.today().date(), is_reserved=True).exclude(release_date__isnull=False).exists(): uip = UserIPStatic.objects.get(user=user_id, is_reserved=True) elif UserIPStatic.objects.filter( user=user_id).exists(): # else if this user has any ip ... uip = UserIPStatic.objects.get(user=user_id) if uip.ip_id is None: # if user ip is null then assign uip.ip = free_pool else: # else user has never purchased one uip = UserIPStatic() uip.user = user uip.ip = free_pool uip.service_period = period if ibu.assign_ip_static(user.fk_ibs_user_info_user.get().ibs_uid, uip.ip.ip): exp_date = uip.expire_date if exp_date: # Fix Timezone problem while comparing the time if exp_date.tzinfo: if exp_date >= datetime.today().utcnow().replace( tzinfo=utc): new_exp_date = exp_date + timedelta(days=period * 30) else: new_exp_date = datetime.today() + timedelta( days=period * 30) else: if exp_date >= datetime.today(): new_exp_date = exp_date + timedelta(days=period * 30) else: new_exp_date = datetime.today() + timedelta( days=period * 30) elif uip.is_free: new_exp_date = None else: new_exp_date = datetime.today() + timedelta(days=period * 30) uip.expire_date = new_exp_date uip.is_reserved = False uip.release_date = None uip.start_date = datetime.today() uip.save() return True, 67 # send_to_dashboard(5052, invoice.user_id, 1) return False, 68 except Exception as e: # send_to_dashboard(5052, invoice.user_id, 1) print '[UNEXPECTED] Error on assigning static ip for invoice %s : %s' % ( user_id, e.message) return False, 68
def assign_ip_pool(user_id=None, pool_name=None, ibs_id=None): try: if ibs_id is None and user_id is None: return False if pool_name is None: return False if not ibs_id: ix = IBSUserInfo.objects.filter(user=user_id).first() if not ix: return False ibs_id = ix.ibs_uid ibm = IBSManager() ibm.update_user_attr('ippool', pool_name, ibs_id) return True except Exception as e: logger.error(e.message or e.args) return False
def import_ibs_services(request): try: ibs = IBSManager() ibi = ImportGroup(ibs) ibi.import_all() return HttpResponse('200') except Exception as e: logger.error(e.message) return send_error(request, _('unable to import ibs groups'))
def get_next_charge_transfer(user_id, from_invoice=True): if not user_id: return 0 try: ibs_uid = IBSUserInfo.objects.get(user=user_id).ibs_uid ibs = IBSManager() credit = ibs.get_user_credit_by_user_id(ibs_uid) credit = int(credit) if from_invoice: extra = get_extra_charges(user_id) else: extra = credit if extra >= credit: return credit else: return extra except Exception as e: print e.message return 0
def __get_manager(self): """ Get IBS Manager for future usage in code @return: IBSManager """ if self.__manager is not None: return self.__manager x = IBSManager() self.__manager = x return x
def __update_from_invoice(self): users = IBSUserInfo.objects.all() log = open('/var/CRM/export_ibs.txt', 'a+') for u in users: invoices = u.user.fk_invoice_user.filter( Q(service__service_type=12) | Q(service__service_type=1), extra_data__gt=0, is_paid=True).order_by('pk').last() if invoices is None: continue ibs = IBSManager() try: expire_date = parse_date_from_str_to_julian( ibs.get_expire_date_by_uid(u.ibs_uid)) except Exception as e: print(e.message or e.args) continue if expire_date is None: continue expire_date = make_aware(expire_date) if expire_date <= invoices.pay_time: ds = FloatDiscount.objects.filter( charge_month=invoices.extra_data).first() if ds: extra_charges = ds.extra_charge else: extra_charges = 0 # to_add = to_add_delta.days real_time = invoices.pay_time + timedelta( (invoices.extra_data * 30) + extra_charges) dt = make_naive(real_time) - datetime.today() # to_add_delta = real_time - expire_date to_add = dt.days if 0 >= to_add >= -2: to_add = 2 elif to_add < -3: continue ibs.set_expire_date_by_uid(u.ibs_uid, to_add) res = 'invoice : %s, expires : %s, paid : %s, real : %s, ADDS : %s' % \ (invoices.pk, expire_date, invoices.pay_time, real_time, to_add) log.write(res) print(res)
def get_all(self): """ Get all system status @return: dict contains all status data @rtype: str """ rqu = self.requester res = {} if rqu.has_perm('CRM.view_dashboard') and rqu.is_staff: res['dashboard'] = get_current_user_dashboard(rqu).filter(last_state=0).count() res['today_queue'] = get_today_jobs() if rqu.has_perm('CRM.accept_orders'): res['orders'] = EquipmentOrder.objects.filter(is_processing=False).count() if rqu.has_perm('CRM.view_online_users'): ibs = IBSManager() users = ibs.get_online_users_count() res['online_customers'] = users if rqu.has_perm('CRM.view_online_crm_users'): res['online_personnel'] = UserManager.get_online() res['total_personnel'] = UserManager.get_personnel_count() return json.dumps(list(res))
def view_online_users(request): if request.method == 'GET': try: ibs = IBSManager() users = ibs.get_online_users() if request.GET.get('p') is not None: insert_new_action_log(request, None, _('print online users list')) res = render_to_string('report/pdf/OnlineUsers.html', {'users': users}) pdf = pdfkit.from_string(res, False, options={'encoding': "UTF-8"}) return HttpResponse(pdf, mimetype='application/pdf') insert_new_action_log(request, None, _('view online users list')) return render(request, 'report/OnlineUsers.html', {'users': users}) except Exception as e: print e.message return render(request, 'errors/ServerError.html') else: return render(request, 'errors/AccessDenied.html')
def de_configure_user_static_ip(user_id): ibm = IBSManager() ibu = IBSUserManager(ibm) user_ip = UserIPStatic.objects.get(user=user_id) if ibu.de_configure_user_ip( user_ip.user.fk_ibs_user_info_user.get().ibs_uid): user_ip.is_reserved = True user_ip.release_date = datetime.today() + timedelta(days=30) # user_ip.service_period = 0 user_ip.save() return True return False
def __import_towers(self): towers = Tower.objects.all() ibs = IBSManager() auth = ibs.get_auth_params() data = ibs.get_proxy().user_custom_field.getAllCustomFields(auth) if 'building' not in data: self.stderr.write('Building not found!') return values = data.get('building').get('allowable_values') px = data.get('building') to_add = [] for t in towers: if t.name not in values: to_add.append(t.name) if len(to_add) < 1: self.stdout.write('No Differ found!') return self.stdout.write('%s New Towers Will Write' % len(to_add)) params = auth.copy() params['comment'] = px.get('comment') params['mandatory'] = 'false' # px.get('mandatory') params['name'] = px.get('name') params['interface_type'] = px.get('interface_type') params['value_type'] = px.get('value_type') params['description'] = px.get('description') params['allowable_values'] = values + to_add params['custom_field_id'] = px.get('custom_field_id') try: ibs.get_proxy().user_custom_field.updateCustomField(params) except Exception: self.stderr.write('Error : Unable to complete request')
def import_ibs_users_job(default_price): cache.set("IBS_IMPORTING", 1) try: ibs = IBSManager() users = ibs.get_all_users() # l.debug("Found %s users" % len(users)) default_group = read_config(name='default_customer_group', default=1) group = Group.objects.get(pk=default_group) for uid in users: cid = create_user_from_ibs(uid) if not cid[0]: continue # l.info("Adding user to internet group") u = User.objects.get(pk=cid[2]) if not UserServiceGroup.objects.filter(user=u.pk).exists(): up = UserServiceGroup() up.user = u up.service_group = ServiceGroups.objects.get(pk=default_price) up.save() if u.groups.filter(pk=default_group).exists(): # l.info("User is in group!") continue try: u.groups.add(group) # l.info("User added to internet group : %s" % uid) except Exception as e: # l.error("Unable to add %s to internet group" % uid) if e.args: print(" ".join([str(a) for a in e.args])) else: print(e.message) # return redirect(reverse(search_users)) except Exception as e: if e.args: print (" ".join([str(a) for a in e.args])) else: print(e.message) # return render(request, 'errors/ServerError.html') cache.set("IBS_IMPORTING", 0)
def __export_ip_address(self): ips = UserIPStatic.objects.filter(is_deleted=False, is_reserved=False, ip__isnull=False) for i in ips: ibs = IBSManager() ibm = IBSUserManager(ibs) ibs_info = IBSUserInfo.objects.filter(user=i.user_id).first() if not ibs_info: continue assert isinstance(ibs_info, IBSUserInfo) print('%s has %s' % (ibm.get_user_ip_static(ibs_info.ibs_uid), ibs_info.ibs_uid))
def __assign_user_towers(self): users = UserTower.objects.all() self.stdout.write('%s Users to check...' % users.count()) for u in users: try: self.stdout.write('Setting %s' % u.pk) ibs_id = u.user.fk_ibs_user_info_user.get().ibs_uid tower = u.tower.name ibs = IBSManager() ibu = IBSUserManager(ibs) ibu.change_user_custom_field(ibs_id, 'building', tower) except Exception: self.stderr.write('Error on setting %s' % u.user.pk)
def update_nearest_exp_date(self): users = IBSUserInfo.objects.all() for u in users: try: ibs = IBSManager() ibs.set_expire_date_by_uid(u.ibs_uid, 1) ibs.set_expire_date_by_uid(u.ibs_uid, -1) except Exception: pass
def send_gift_for_users(users, add_days, add_package, add_days_for_limited=False): # assert isinstance(users, User.objects) for u in users: # assert isinstance(u, User) if not u.is_active: continue if not u.fk_user_current_service_user.exists(): continue user_service = u.fk_user_current_service_user.get() if not u.fk_ibs_user_info_user.exists(): continue ibi = u.fk_ibs_user_info_user.get().ibs_uid if not user_service.is_active: continue ibs = IBSManager() gh = GiftHistory() gh.target_user = u gh.extended_days = int(add_days) gh.extended_package = int(add_package) gh.save() if add_days > 0: if user_service.service_property.initial_package > 0 and add_days_for_limited: ibs.set_expire_date_by_uid(ibi, add_days) if user_service.service_property.initial_package == 0: ibs.set_expire_date_by_uid(ibi, add_days) if add_package > 0 and user_service.service_property.initial_package > 0: ibs.change_credit_by_uid(add_package, ibi) add_package = convert_credit(add_package) trm = convert_credit(ibs.get_user_credit_by_user_id(ibi)) else: trm = None kw = {'name': '', 'ta': add_package, 'exp': convert_date(parse_date_from_str_to_julian(str(ibs.get_expire_date_by_uid(ibi)))), 'ads': add_days, 'trm': trm} send_from_template(u.pk, 17, **kw)
def assign_user_to_tower(request): ia = check_ajax(request) if request.method == 'GET': tower_id = request.GET.get('t') user_id = request.GET.get('u') if not validate_integer(tower_id): if ia: return HttpResponseBadRequest(_('invalid tower id')) return render(request, 'errors/CustomError.html', {'error_message': _('invalid tower id')}) if not validate_integer(user_id): if ia: return HttpResponseBadRequest(_('invalid user id')) return render(request, 'errors/CustomError.html', {'error_message': _('invalid user id')}) if not User.objects.filter(pk=user_id).exists(): if ia: return HttpResponseBadRequest(_('no such user found')) return render(request, 'errors/CustomError.html', {'error_message': _('no such user found')}) if not Tower.objects.filter(pk=tower_id).exists(): if ia: return HttpResponseBadRequest(_('no such tower')) return render(request, 'errors/CustomError.html', {'error_message': _('no such tower')}) if UserTower.objects.filter(user=user_id).exists(): ut = UserTower.objects.get(user=user_id) else: ut = UserTower() ut.user_id = int(user_id) ut.tower_id = int(tower_id) ut.save() # print ut.tower.ibs_name if User.objects.filter(fk_ibs_user_info_user=user_id).exists(): ibm = IBSManager() ibu = IBSUserManager(ibm) ibu.change_user_custom_field( User.objects.get( pk=user_id).fk_ibs_user_info_user.get().ibs_uid, 'building', ut.tower.ibs_name) if ia: return HttpResponse('200') return redirect(reverse(view_towers)) if ia: return HttpResponseBadRequest(_('invalid method')) return redirect(reverse(view_towers))
def __init__(self, service_type, user_id, check_type=None): """ Charge Base @param service_type: Service Type To Charge @param user_id: IBS USER ID @param check_type: Check Type and validation """ if not isinstance(service_type, int): raise TypeError('Service Type Must Be INT not %s' % type(service_type)) if not user_id: raise TypeError('user_id is not Set!') if not check_type: check_type = self.CHECK_TYPE_NONE self.__ibs = IBSManager() self.__service_type = service_type self.__user_id = user_id self.__check_type = check_type
def load_towers_from_ibs(): ibm = IBSManager() cf = CustomFieldManager(ibm) rs = cf.get_by_name('building') if rs: values = rs.get_values() description = rs.get_description() cnt = 0 for v in values: if Tower.objects.filter(name__iexact=v): continue t = Tower() t.ibs_name = v t.name = v t.ibs_id = cnt t.description = description t.address = '--' t.save() cnt += 1
def __update_ibs_user_service(self, user_id, ibs_id, update_expire=False, update_credit=False): service = UserCurrentService.objects.filter(user=user_id).first() if not service: return False assert isinstance(service, UserCurrentService) ibs = IBSManager(username='******') if update_expire: if service.expire_date: self.update_expire_date_by_invoice(user_id) # expire_date = make_naive(service.expire_date) - datetime.today() # ibs.set_expire_date_by_uid(ibs_id, expire_date.days, True) ibs.update_service(ibs_id, service.service.ibs_name) if update_credit: if service.service.group_type == 1: ibs.change_credit_by_uid(5120, ibs_id, True) return True
def unlock_account(self): user = self.get_target_user(True) locked = LockedUsers.objects.filter(user=user.pk).first() if locked: if locked.ibs_locked: ibs = IBSManager() ibi = IBSUserInfo.objects.get(user=user.pk).ibs_uid dt = datetime.today().date() - locked.lock_date.date() x = UserServiceStatus(user.pk) a = datetime.today().date( ) - x.current_service.expire_date.date() to_add = a.days if to_add < 0: to_add = a.days * (-1) if dt.days > 20: ibs.set_expire_date_by_uid(ibi, to_add, True) # fire_event(4237, user, None, self.requester.pk) ibs.unlock_user(ibi) locked.delete() user.is_active = True user.save() UnlockAccountEventHandler().fire(user, None, self.requester, True) return True
def update_user_credit(fid): """ updates the user credit by invoice ID @param fid:invoice number @type fid:int @return:bool @rtype: """ factor = None try: factor = Invoice.objects.get(pk=fid) if factor.is_paid: return False reduce_one = False set_to_active = False if factor.user.fk_user_current_service_user.filter().exists(): if not factor.user.fk_user_current_service_user.get( ).is_active: # Service is a test service! if factor.extra_data > 1: reduce_one = True set_to_active = True ibs = IBSManager() if factor.service.service_type == 1: extra_charge = get_next_charge_transfer(factor.user_id) else: extra_charge = 0 if factor.service.service_type == 1: replace = True if UserCurrentService.objects.filter(user=factor.user_id).exists(): cs = UserCurrentService.objects.get(user=factor.user_id) if factor.service.content_object.fk_ibs_service_properties_properties.get( ).service_id == cs.service_id: new_service = False else: new_service = True else: new_service = True else: replace = False new_service = False if new_service or factor.service.service_type == 1: if factor.service.content_object.initial_package > 1: if reduce_one: amount = factor.service.content_object.initial_package * ( factor.extra_data - 1) else: amount = factor.service.content_object.initial_package * factor.extra_data if IBSServiceDiscount.objects.filter( service=factor.service.content_object. fk_ibs_service_properties_properties.get().service_id, charge_days=factor.extra_data).exists(): amount += IBSServiceDiscount.objects.get( service=factor.service.content_object. fk_ibs_service_properties_properties.get().service_id, charge_days=factor.extra_data).extra_traffic else: amount = 0 elif factor.service.service_type == 2: amount = factor.service.content_object.amount if PackageDiscount.objects.filter(package=factor.service.object_id, is_deleted=False).exists(): amount += PackageDiscount.objects.get( package=factor.service.object_id, is_deleted=False).extended_package replace = False else: return True if amount < 1: amount = 1 replace = True # While user in temp charge, we must set it to clear temp charge state uid = factor.user.username add_credit = amount if set_to_active: replace = True if not new_service and extra_charge > 0 and not set_to_active: add_credit += extra_charge ibs.change_credit(add_credit, uid, replace) fire_event(7060, factor, None, factor.user_id) return True except Exception as e: if factor: fire_event(5616, factor, None, factor.user_id) else: fire_event(5616, None, None, 1) if e.args: print(" ".join([str(a) for a in e.args])) else: print(e.message) return False
def import_ip_statics_job(): cache.set("IBS_IMPORTING", 1) try: ibm = IBSManager() ibu = IBSUserManager(ibm) ibs_users = IBSUserInfo.objects.all() for u in ibs_users: ip = ibu.get_user_ip_static(u.ibs_uid) if validate_ip(ip): if IPPool.objects.filter(ip=ip).exists(): pool = IPPool.objects.get(ip=ip) else: pool = IPPool() pool.ip = ip pool.save() print '[IP-STATIC] ADDRESS ADDED : %s' % ip if not UserIPStatic.objects.filter(user=u.user_id).exists(): user_ip = UserIPStatic() user_ip.release_date = datetime.today() + timedelta(days=30) user_ip.expire_date = datetime.today() + timedelta(days=15) user_ip.start_date = datetime.today() user_ip.service_period = 1 else: user_ip = UserIPStatic.objects.get(user=u.user_id) user_ip.ip = pool user_ip.user = User.objects.get(pk=u.user_id) user_ip.is_reserved = False user_ip.request_time = datetime.today() user_ip.save() # if StaticIPRequest.objects.filter(user=u.user_id).exists(): # rq = StaticIPRequest.objects.get(user=u.user_id) # else: # rq = StaticIPRequest() # rq.end_date = datetime.today() + timedelta(days=15) # rq.request_time = datetime.today() # rq.service_period = 1 # rq.start_date = datetime.today() # rq.user = User.objects.get(pk=u.user_id) # rq.address = ip # rq.save() print '[IP-STATIC] IP ASSIGNED TO USER %s %s' % (ip, u.user.username) if exists('/var/CRM/Docs/None/IP.xlsx'): wb = load_workbook('/var/CRM/Docs/None/IP.xlsx') act = wb.get_active_sheet() for i in range(2, act.max_row): row_id1 = 'A%s' % i row_id2 = 'B%s' % i uid = act[row_id1].value if not validate_integer(uid): break exp = act[row_id2].value date0 = exp.split('.') date1 = '13%s-%s-%s' % (date0[2], date0[1], date0[0]) # print(date1) cor_date = parse_date_from_str(date1) # print cor_date # cor_date.hour = 12 # cor_date.minute = 0 if UserIPStatic.objects.filter(user__fk_ibs_user_info_user__ibs_uid=int(uid)).exists(): user_ip_data = UserIPStatic.objects.get(user__fk_ibs_user_info_user__ibs_uid=int(uid)) user_ip_data.expire_date = cor_date user_ip_data.save() # StaticIPRequest.end_date # req = StaticIPRequest.objects.filter(user__fk_ibs_user_info_user__ibs_uid=int(uid)).last() # req.end_date = cor_date # req.save() except Exception as e: print e.message finally: cache.set("IBS_IMPORTING", 0)
def change_password(request): u = request.user granted = False if u.is_superuser or u.is_staff: granted = True if request.method == 'GET': uid = 'invalid' self_edit = True if granted: uid = request.GET.get('uid') if validate_integer(uid): self_edit = False if not granted or not validate_integer(uid): uid = u.pk try: user = User.objects.get(pk=uid) return render(request, 'user/ChangePassword.html', { 'self_password': self_edit, 'u': user }) except Exception as e: logger.error(e.message or e.args) return render(request, 'errors/ServerError.html') elif request.method == 'POST': sid = u.pk new_pass = request.POST.get('txtNewPassword') re_type = request.POST.get('txtRetype') ibs_password = request.POST.get('txtIbsPassword') ibs_retype = request.POST.get('txtIbsRetype') if granted: uid = request.POST.get('uid', 'invalid') else: uid = sid if not validate_integer(uid): uid = sid try: if sid == uid: if not validate_empty_str(new_pass): return render( request, 'errors/CustomError.html', {'error_message': _('please enter new password')}) current_pass = request.POST.get('txtPassword') if not validate_empty_str(current_pass): return render( request, 'errors/CustomError.html', {'error_message': _('please enter current password')}) cp = authenticate(username=u.username, password=current_pass) if cp is not None: if new_pass == re_type: cp.set_password(new_pass) cp.save() # fire_event(4360, cp, None, request.user.pk) PasswordChangedNotification().send(user_id=uid, password=new_pass, change_type='crm') else: return render(request, 'errors/CustomError.html', {'error_message': _('invalid password')}) else: return render(request, 'errors/CustomError.html', {'error_message': _('invalid password')}) else: if validate_empty_str(new_pass): if new_pass != re_type: return render( request, 'errors/CustomError.html', {'error_message': _('passwords are not match')}) ucp = User.objects.get(pk=uid) ucp.set_password(new_pass) ucp.save() # fire_event(5240, ucp, None, request.user.pk) # insert_new_action_log(request, uid, _('crm password changed')) PasswordChangedNotification().send(user_id=uid, password=new_pass, change_type='crm') # send_from_template.delay(uid, 4, cp=new_pass) # send_from_template.delay(uid, 5) if not (ucp.is_superuser and ucp.is_staff): if ibs_password != ibs_retype: return render(request, 'errors/CustomError.html', { 'error_message': _('ibs passwords are not match') }) if validate_empty_str(ibs_password): ibs = IBSManager() ibs_u = IBSUserInfo.objects.get(user=uid) ibs_uid = ibs_u.ibs_uid if ibs.assign_username(username=ibs_u.user.username, password=ibs_password, user_id=ibs_uid): # insert_new_action_log(request, uid, _('ibs password changed')) PasswordChangedNotification().send( user_id=uid, password=ibs_password, change_type='ibs') # send_from_template.delay(uid, 6, cp=ibs_password) # send_from_template.delay(uid, 7) # fire_event(5215, User.objects.get(pk=uid), None, request.user.pk) else: return render(request, 'errors/CustomError.html', { 'error_message': _('unable to change ibs password') }) if not granted: return redirect(reverse(frm_logout)) else: return redirect( reverse(show_user_navigation) + '?uid=' + str(uid)) except Exception as e: logger.error(e.message or e.args) return render(request, 'errors/ServerError.html') else: return render(request, 'errors/AccessDenied.html')
def __expire_user(self, user_id, days): ibs = IBSManager() ibs.set_expire_date_by_uid(user_id, days) print('[OK]')
def create_user_from_ibs(uid, update_mode=False): # l = create_logger(None, InfoCodes.creating_ibs_user) enter_update_mode = False ibs = IBSManager() # l.debug("Getting a list of attributes") attr = ibs.get_user_info(uid) attr = attr[str(uid)] password = get_user_info_by_dic( attr, 'normal_password') # ibs.get_user_password(int(uid)) u = get_user_info_by_dic(attr, 'normal_username') # ibs.get_username(uid) service = ibs.get_user_service(uid) user_is_in_ibs_db = IBSUserInfo.objects.filter(ibs_uid=uid).exists() if u is None: # l.error("No username is assigned for this user : %s" % uid) return False, 1, 'empty username' if (update_mode and user_is_in_ibs_db) or User.objects.filter(username=u).exists(): try: if user_is_in_ibs_db: # l.debug("User found in IBS DB") ibs_id = IBSUserInfo.objects.get(ibs_uid=uid).user.pk i_u = User.objects.get(pk=ibs_id) else: # l.debug("User is NOT in IBS DB") i_u = User.objects.get(username=u) enter_update_mode = True if UserProfile.objects.filter(user__username=u).exists(): # l.debug("Found User profile : %s" % i_u.pk) profile = UserProfile.objects.get(user__username=u) else: # l.debug("Profile Created for : %s" % i_u.pk) profile = UserProfile() except Exception as e: # if e.args: # l.error(" ".join([str(a) for a in e.args])) # else: # l.error(e.message) # l.error("Unable to create or update user : IBI : %s" % uid) return False, 7, 'unable to enter update mode' else: # l.info("Creating a new user") i_u = User() profile = UserProfile() # l.debug("User and Profile instances created") i_u.username = u if not i_u.password: i_u.set_password(password) first_name = get_user_info_by_dic(attr, 'name') if not first_name: first_name = 'UNKNOWN!' if len(first_name) > 30: first_name = first_name[0:30] email = get_user_info_by_dic(attr, 'email') if not email: # l.warning("No email for user : %s" % uid) email = '-' if not first_name: # l.warning("First name is empty for : %s" % uid) first_name = '-' i_u.first_name = first_name i_u.is_active = True address = get_user_info_by_dic(attr, 'address') if not address: address = 'Tehran' str_date = get_user_info_by_dic(attr, 'first_login') if not str_date: date = datetime.today() else: date = parse_date_from_str_to_julian(str_date) i_u.date_joined = date profile.address = address geo_loc = get_user_info_by_dic(attr, 'custom_field_Geo') if not geo_loc: geo_loc = '-' profile.geo_code = geo_loc identity_num = get_user_info_by_dic(attr, 'custom_field_NCode') if not identity_num: # l.warning("No identity Number for user : %s" % uid) identity_num = '-' elif len(identity_num) > 10: identity_num = identity_num[0:9] profile.identity_number = identity_num phone = get_user_info_by_dic(attr, 'phone') mobile = get_user_info_by_dic(attr, 'cell_phone') profile.comment = get_user_info_by_dic(attr, 'comment') if not profile.comment: profile.comment = '-' # print 'Checking mobile' if not mobile: mobile = '-' elif len(mobile) > 12: mobile = mobile[0:12] # print 'Mobile passed' # print 'Checking phone' if not phone: phone = '-' elif len(phone) > 15: phone = phone[0:13] # print 'phone passed' profile.telephone = phone profile.mobile = mobile birth_data = parse_date_from_str_to_julian( get_user_info_by_dic(attr, 'birthdate')) i_u.email = email profile.birth_date = birth_data try: i_u.save() profile.user = i_u if birth_data: profile.birth_date_day = birth_data.day profile.birth_date_month = birth_data.month else: profile.birth_date_day = 1 profile.birth_date_month = 1 profile.marriage_date = datetime.today() profile.marriage_date_day = 1 profile.marriage_date_month = 1 profile.save() crm_uid = i_u.pk # l.info("User has been updated : %s" % crm_uid) except Exception as e: # l.error("Saving user data failed for : %s" % uid) # if e.args: # l.error(" ".join([str(a) for a in e.args])) # else: # l.error(e.message) return False, 4, 'unable to create new user' try: if not user_is_in_ibs_db: # l.info("Adding user to IBS DB") ibi = IBSUserInfo() ibi.ibs_uid = int(uid) ibi.user = i_u ibi.save() # l.info("User added to IBS DB") except Exception as e: # l.error("Error while trying to add user to IBS DB") # if e.args: # l.error(" ".join([str(a) for a in e.args])) # else: # l.error(e.message) return False, 6, 'unable to assign user to ibs details' try: # l.debug("Finding if user has any service") g_info = IBSService.objects.get(ibs_name=service) # i_s = IBSService.objects.get(pk=g_info.service_id) except Exception as e: # l.error("Error while trying to find a service for user") # if e.args: # l.error(" ".join([str(a) for a in e.args])) # else: # l.error(e.message) return False, 5, 'unable to find service' if enter_update_mode and UserCurrentService.objects.filter( user=crm_uid).exists(): # l.info("Preparing for updating user service : %s" % uid) i_cs = UserCurrentService.objects.get(user=crm_uid) if i_cs.service_id != g_info.pk: i_cs.service = g_info i_cs.service_property = ServiceProperty.objects.get( pk=g_info.fk_default_service_property_service.get().default.pk) else: # l.info("Creating service information for : %s" % uid) i_cs = UserCurrentService() i_cs.service_property = ServiceProperty.objects.get( pk=g_info.fk_default_service_property_service.get().default.pk) i_cs.service = g_info i_cs.user = i_u i_cs.is_active = True expire_date = parse_date_from_str_to_julian( get_user_info_by_dic(attr, 'abs_exp_date')) if expire_date: i_cs.expire_date = expire_date try: i_cs.save() # l.info("User Service data has been saved") except Exception as e: # l.error("Unable to save user service data : %s" % uid) # if e.args: # l.error(" ".join([str(a) for a in e.args])) # else: # l.error(e.message) return False, 6, 'unable to assign service' return True, uid, crm_uid