def init_department(license): project_directory = os.path.abspath(".") data_directory = os.path.join(project_directory, "users", "data") department_data_file = os.path.join(data_directory, "departments.json") Department.load_from_json(department_data_file, license) print("dept worked!!")
def test_get(self, rf, mocker): # pylint: disable=no-self-use disable=invalid-name """ test create """ url = reverse('userdepartment-list') #user #department #turn user_test = ApiUser() user_test.username = "******" user_test.password = "******" user_test.email = "*****@*****.**" user_test.save() department_test = Department() department_test.name = "department_test_v" department_test.save() turn_test = Turn() turn_test.name = "turn_test_v" turn_test.description = "Description" turn_test.start_time = dt.datetime.strptime("08:00", '%H:%M').time() turn_test.end_time = dt.datetime.strptime("15:00", '%H:%M').time() turn_test.save() data = { "user": user_test.id, "department": department_test.id, "turn": turn_test.id, 'manager': True } request = rf.post(url, content_type='application/json', data=json.dumps(data)) mocker.patch.object(UserDepartment, 'save') # Renderizamos la vista con nuestro request. response = UserDepartmentViewSet.as_view({'post': 'create'})(request).render() department = Department.objects.get( id=json.loads(response.content).get('department')) turn = Turn.objects.get(id=json.loads(response.content).get('turn')) user = ApiUser.objects.get(id=json.loads(response.content).get('user')) manager = json.loads(response.content).get('manager') assert response.status_code == 201 assert str(department) == 'department_test_v' assert str(turn) == 'turn_test_v' assert str(user.username) == 'test1' assert manager == True # Verificamos si efectivamente se llamo el metodo save assert UserDepartment.save.called
def permissions(): content_type = ContentType.objects.get_for_model(Client) permission_one = Permission.objects.create( codename='test_client_permission_one', name='test client permission one', content_type=content_type, ) permission_two = Permission.objects.create( codename='test_client_permission_two', name='test client permission two', content_type=content_type, ) permission_three = Permission.objects.create( codename='test_client_permission_three', name='test client permission three', content_type=content_type, ) group_one = Group() group_one.name = 'test_group_one' group_one.save() group_one.permissions.add(permission_one) group_two = Group() group_two.name = 'test_group_two' group_two.save() group_two.permissions.add(permission_two) group_three = Group() group_three.name = 'test_group_three' group_three.save() group_three.permissions.add(permission_three) department = Department() department.title = 'managers' department.default_group = group_two department.admin_group = group_three department.save()
def test_update( self, user_department_factory, ): # pylint: disable=no-self-use """ test updated user_department """ department_test = Department() department_test.name = "updated_department" department_test.general_profile = "General Profile 2" department_test.save() user_department_created = user_department_factory() user_department = UserDepartment.objects.get( id=user_department_created.id) user_department.department = department_test user_department.save() assert str( user_department.department.name ) == "updated_department", 'End time should be updated_department'
def handle(self, *args, **options): if settings.USE_LDAP: #ldap.set_option(ldap.OPT_DEBUG_LEVEL, 4095) l = PagedResultsSearchObject(settings.AUTH_LDAP_SERVER_URI) l.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) created_users = 0 updated_users = 0 skipped_users = 0 page_count, users = l.paged_search_ext_s(*settings.LDAP_USER_SEARCH) for dn, userdata in users: saveuser = False created = False try: user = Lageruser.objects.get(username=userdata["sAMAccountName"][0]) except TypeError: continue except Exception as e: saveuser = True created = True user = Lageruser(username=userdata["sAMAccountName"][0]) for field, attr in settings.AUTH_LDAP_USER_ATTR_MAP.iteritems(): try: new_value = userdata[attr][0].decode('unicode_escape').encode('iso8859-1').decode('utf8') if attr == settings.AUTH_LDAP_DEPARTMENT_FIELD: department_name = re.findall(settings.AUTH_LDAP_DEPARTMENT_REGEX, new_value)[-1] try: new_value = Department.objects.get(name=department_name) except Department.DoesNotExist as e: new_value = Department(name=department_name) new_value.save() elif attr == "accountExpires": if int(userdata["accountExpires"][0]) > 0: expires_timestamp = (int(userdata["accountExpires"][0])/10000000)-11644473600 new_value = date.fromtimestamp(expires_timestamp) if created and new_value < date.today(): skipped_users += 1 saveuser = False break if user.is_active != (new_value > date.today()): user.is_active = new_value > date.today() saveuser = True old_value = getattr(user, field) if old_value != new_value and (created or attr not in settings.AUTH_LDAP_ATTR_NOSYNC): saveuser = True setattr(user, field,new_value) except StandardError as e: if attr == "accountExpires": continue if attr == "givenName" or attr == "sn": skipped_users += 1 saveuser = False break if attr == "sn": old_value = getattr(user, field) if old_value != userdata["sAMAccountName"][0]: saveuser = True setattr(user, field, userdata["sAMAccountName"][0]) continue print("{0} does not have a value for the attribute {1}".format(dn, attr)) if saveuser: user.save() if user.main_department: if not user.main_department in user.departments.all(): department_user = DepartmentUser(user=user, department=user.main_department, role="m") department_user.save() if created: created_users += 1 else: updated_users += 1 print("skipped {0} users.".format(skipped_users)) print("imported {0} new users.".format(created_users)) print("updated {0} exisitng users.".format(updated_users)) else: print("You have to enable the USE_LDAP setting to use the ldap import.")
def handle(self, *args, **options): if not settings.USE_LDAP: print( "You have to enable the USE_LDAP setting to use the ldap import." ) return # ldap.set_option(ldap.OPT_DEBUG_LEVEL, 4095) l = PagedResultsSearchObject(settings.AUTH_LDAP_SERVER_URI) l.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) created_users = 0 updated_users = 0 skipped_users = 0 page_count, users = l.paged_search_ext_s(*settings.LDAP_USER_SEARCH) for dn, userdata in users: if dn is not None: dn = dn.decode('utf-8') saveuser = False created = False changes = {} try: user = Lageruser.objects.get( username=userdata["sAMAccountName"][0]) except TypeError: continue except: saveuser = True created = True user = Lageruser(username=userdata["sAMAccountName"][0]) for field, attr in settings.AUTH_LDAP_USER_ATTR_MAP.items(): try: old_value = getattr(user, field) new_value = userdata[attr][0].decode( 'unicode_escape').encode('iso8859-1').decode('utf8') if attr == settings.AUTH_LDAP_DEPARTMENT_FIELD: try: department_name = re.findall( settings.AUTH_LDAP_DEPARTMENT_REGEX, new_value)[-1] new_value = Department.objects.get( name=department_name) except Department.DoesNotExist: new_value = Department(name=department_name) new_value.save() except IndexError: skipped_users += 1 saveuser = False break elif attr == "accountExpires": expired = False if userdata['accountExpires'][0] == '0': new_value = None else: new_value = utils.convert_ad_accountexpires( int(userdata['accountExpires'][0])) if new_value is not None: expired = new_value < date.today() if created and expired: skipped_users += 1 saveuser = False break if user.is_active == expired: user.is_active = not expired saveuser = True if old_value != new_value and ( created or attr not in settings.AUTH_LDAP_ATTR_NOSYNC): saveuser = True setattr(user, field, new_value) changes[field] = (old_value, new_value) except: if attr == "accountExpires": continue if attr == "givenName" or attr == "sn": skipped_users += 1 saveuser = False break if attr == "sn": old_value = getattr(user, field) if old_value != userdata["sAMAccountName"][0]: saveuser = True setattr(user, field, userdata["sAMAccountName"][0]) continue if attr == "mail": # userPrincipalName *might* contain non-ascii # characters but is a sane fallback for when "mail" # does not exist old_value = getattr(user, field) try: new_value = userdata["userPrincipalName"][ 0].decode('ascii') if old_value != new_value: saveuser = True setattr(user, field, new_value) continue except Exception: pass print("{0} does not have a value for the attribute {1}". format(dn, attr)) if saveuser: if user.is_active == expired: if expired: print("{0} has expired".format(dn)) else: print("{0} has been reactivated".format(dn)) for field, (old_value, new_value) in changes.iteritems(): print('{0} changed {1} from {2} to {3}'.format( dn, field, old_value, new_value)) user.save() if user.main_department: if user.main_department not in user.departments.all(): department_user = DepartmentUser( user=user, department=user.main_department, role="m") department_user.save() if created: created_users += 1 else: updated_users += 1 if created_users > 0 or updated_users > 0: print("imported {0} new users.".format(created_users)) print("updated {0} exisitng users.".format(updated_users))
def fake_department(word): return Department(name=word.title())
def post(self,request): dict_root = {'是': '1', '否': '0'} dict_status = {'空闲': '0', '占用': '1', '损坏': '-1','':'0'} form = UploadExcelForm(request.POST,request.FILES) if form.is_valid(): wb = xlrd.open_workbook(filename=None,file_contents=request.FILES['excel'].read()) table = wb.sheets()[0] row =table.nrows for i in range(1,row): col = table.row_values(i) device_type = str(col[1]) device_id = str(col[3]) device_root = dict_root[str(col[4])] department_name = str(col[5]) device_user = str(col[6]) device_status = dict_status[str(col[8])] #borrow_date = xlrd.xldate_as_datetime(col[7], 0).strftime('%Y-%m-%d') if device_status=='1' else None comment = str(col[9]) device_sys = str(col[10]) device_cpu = str(col[11]) device_men = str(col[12]) device_res = str(col[13]) device_mac = str(col[14]) try: buy_time = xlrd.xldate_as_datetime(col[15],0).strftime('%Y-%m-%d') except: buy_time=datetime.datetime.now() dev = Device.objects.filter(device_id=device_id) if not dev: devicetype = DeviceType.objects.filter(device_type=device_type).first() if devicetype: #device_type = DeviceType.objects.filter(device_type=device_type).first() pass else: devicetype = DeviceType(device_type=device_type,device_cpu=device_cpu,device_res=device_res) devicetype.save() if device_status == '1': department = Department.objects.filter(department_name=department_name).first() if department: pass else: department = Department(department_name = department_name) department.save() user = UserProfile.objects.filter(username=device_user).first() if user: pass else: user = UserProfile(username=device_user,department=department,password=make_password(pwd),isadmin='0',is_staff='1') user.save() device = Device(device_id=device_id,device_type=devicetype,buy_time=buy_time, device_mac=device_mac,device_sys=device_sys,device_root=device_root,device_men=device_men, device_status=device_status,device_user=user,comment=comment) device.save() deviceLog(device, '0', device_status, 0, device.device_user) else: admin_user = UserProfile.objects.filter(isadmin='1').first() device = Device(device_type=devicetype, device_id=device_id, buy_time=buy_time, device_mac=device_mac, device_root=device_root,device_sys=device_sys,device_men=device_men, device_status=device_status, device_user=admin_user,comment=comment) device.save() else: pass return HttpResponseRedirect((reverse('devices:device_list')))
def handle(self, *args, **options): if not settings.USE_LDAP: print("You have to enable the USE_LDAP setting to use the ldap import.") return # ldap.set_option(ldap.OPT_DEBUG_LEVEL, 4095) l = PagedResultsSearchObject(settings.AUTH_LDAP_SERVER_URI) l.simple_bind_s(settings.AUTH_LDAP_BIND_DN, settings.AUTH_LDAP_BIND_PASSWORD) created_users = 0 updated_users = 0 skipped_users = 0 page_count, users = l.paged_search_ext_s(*settings.LDAP_USER_SEARCH) for dn, userdata in users: saveuser = False created = False changes = {} try: user = Lageruser.objects.get(username=userdata["sAMAccountName"][0]) except TypeError: continue except: saveuser = True created = True user = Lageruser(username=userdata["sAMAccountName"][0]) for field, attr in settings.AUTH_LDAP_USER_ATTR_MAP.items(): try: old_value = getattr(user, field) new_value = userdata[attr][0].decode('unicode_escape').encode('iso8859-1').decode('utf8') if attr == settings.AUTH_LDAP_DEPARTMENT_FIELD: try: department_name = re.findall(settings.AUTH_LDAP_DEPARTMENT_REGEX, new_value)[-1] new_value = Department.objects.get(name=department_name) except Department.DoesNotExist: new_value = Department(name=department_name) new_value.save() except IndexError: skipped_users += 1 saveuser = False break elif attr == "accountExpires": expired = False if userdata['accountExpires'][0] == '0': new_value = None else: new_value = utils.convert_ad_accountexpires(int(userdata['accountExpires'][0])) if new_value is not None: expired = new_value < date.today() if created and expired: skipped_users += 1 saveuser = False break if user.is_active == expired: user.is_active = not expired saveuser = True if old_value != new_value and (created or attr not in settings.AUTH_LDAP_ATTR_NOSYNC): saveuser = True setattr(user, field, new_value) changes[field] = (old_value, new_value) except: if attr == "accountExpires": continue if attr == "givenName" or attr == "sn": skipped_users += 1 saveuser = False break if attr == "sn": old_value = getattr(user, field) if old_value != userdata["sAMAccountName"][0]: saveuser = True setattr(user, field, userdata["sAMAccountName"][0]) continue if attr == "mail": # userPrincipalName *might* contain non-ascii # characters but is a sane fallback for when "mail" # does not exist old_value = getattr(user, field) try: new_value = userdata["userPrincipalName"][0].decode('ascii') if old_value != new_value: saveuser = True setattr(user, field, new_value) continue except Exception: pass print("{0} does not have a value for the attribute {1}".format(dn, attr)) if saveuser: if user.is_active == expired: if expired: print("{0} has expired".format(dn)) else: print("{0} has been reactivated".format(dn)) for field, (old_value, new_value) in changes.items(): print('{0} changed {1} from {2} to {3}'.format(dn, field, old_value, new_value)) user.save() if user.main_department: if user.main_department not in user.departments.all(): department_user = DepartmentUser(user=user, department=user.main_department, role="m") department_user.save() if created: created_users += 1 else: updated_users += 1 if created_users > 0 or updated_users > 0: print("imported {0} new users.".format(created_users)) print("updated {0} exisitng users.".format(updated_users))