Compare commits

...

363 Commits

Author SHA1 Message Date
40e3078a58 build: bump version 1.0.0-b11 -> 1.0.0-b12 2024-08-10 11:23:21 +00:00
Jon
4ba79c6ae9 Merge pull request #218 from nofusscomputing/162-api-field-validtion
test: api field checks

#128 #162
2024-08-10 20:51:51 +09:30
Jon
b5c31d81d3 fix(api): ensure org mixin is inherited by software view
. #218 fixes #219
2024-08-10 20:35:06 +09:30
Jon
c3b585d416 fix(base): correct project links to github
. #218
2024-08-10 20:24:43 +09:30
Jon
84d21f4af8 test(teams): api field checks
. #162 #218
2024-08-10 19:58:04 +09:30
Jon
262e431834 test(organization): api field checks
. #162
2024-08-10 19:39:28 +09:30
cde2562048 build: bump version 1.0.0-b10 -> 1.0.0-b11 2024-08-10 08:30:02 +00:00
Jon
67d853cf25 Merge pull request #215 from nofusscomputing/dependabot/pip/django-5.0.8
chore(deps): bump django from 5.0.7 to 5.0.8

#209
2024-08-10 17:54:55 +09:30
Jon
3ba6bb5b4b docs(readme): correct build badge
#209 #214
2024-08-10 17:35:53 +09:30
84d4f48c63 chore(deps): bump django from 5.0.7 to 5.0.8
Bumps [django](https://github.com/django/django) from 5.0.7 to 5.0.8.
- [Commits](https://github.com/django/django/compare/5.0.7...5.0.8)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-08-10 17:22:47 +09:30
Jon
5e8bebbeb1 build(python): update installed packages as part of the build
#209
2024-08-10 17:22:07 +09:30
Jon
b66a8644a0 Merge pull request #217 from nofusscomputing/ci-adjustments
ci: migration items
2024-08-10 15:03:45 +09:30
Jon
f0ae185fc5 docs(readme): fix version badges
#217 #214
2024-08-10 14:02:27 +09:30
Jon
43b7e413a6 ci(project): add issue/pr project triage
https://github.com/nofusscomputing/action_project/pull/1 https://github.com/nofusscomputing/centurion_erp/issues/214 #217
2024-08-10 13:45:58 +09:30
Jon
04dc00d79d ci(gitlab): fix includes
https://github.com/nofusscomputing/centurion_erp/issues/214
2024-08-10 13:35:37 +09:30
8e6fd58107 build: bump version 1.0.0-b9 -> 1.0.0-b10 2024-08-09 12:53:39 +00:00
Jon
bfe9a95038 ci: remove docker.io from image publish name
#209
2024-08-09 22:23:03 +09:30
33687791ec build: bump version 1.0.0-b8 -> 1.0.0-b9 2024-08-09 12:43:24 +00:00
Jon
57bc972b0f ci: use correct docker.io credentials
#209
2024-08-09 22:12:19 +09:30
Jon
f437eeccb8 ci: use full docker.io as publish image name
#209
2024-08-09 22:12:19 +09:30
Jon
4e11ad67d0 ci: use docker.io as publish registry
#209
2024-08-09 22:12:19 +09:30
40ba645a35 build: bump version 1.0.0-b7 -> 1.0.0-b8 2024-08-09 12:26:45 +00:00
Jon
27e73e21d1 ci: add org to docker publish registry
#209
2024-08-09 21:55:41 +09:30
a6c0785de0 build: bump version 1.0.0-b6 -> 1.0.0-b7 2024-08-09 12:14:12 +00:00
Jon
83328be22e ci: fix publish registry
#209
2024-08-09 21:39:53 +09:30
c6ed5c8279 build: bump version 1.0.0-b5 -> 1.0.0-b6 2024-08-09 11:58:50 +00:00
Jon
a4dc7f479a Merge pull request #216 from nofusscomputing/gitlab-migration
chore: gitlab migration tasks

#216 #214
2024-08-09 21:16:01 +09:30
Jon
71726035dc ci: Add Bump workflow
#216 #214
2024-08-09 21:05:38 +09:30
Jon
c624a3617c ci: Add Python workflow
#216 #214
2024-08-09 21:05:16 +09:30
Jon
cf00ab6234 ci: Add Docker workflow
#216 #214
2024-08-09 21:05:05 +09:30
Jon
e8684c5206 ci: Add PR checks workflow
#216 #214
2024-08-09 21:04:25 +09:30
Jon
bb388a1969 ci: remove temp workflows
#216 #214
2024-08-09 21:03:58 +09:30
Jon
d99f2d3c6f docs: update readme to reflect Github as project home
. #216
2024-08-09 21:02:48 +09:30
Jon
81a72773cb ci: remove gitlab pipelines
#216
2024-08-09 15:15:54 +09:30
Jon
5fa88a5209 ci(github): add coverage
!43
2024-08-02 10:49:42 +09:30
Jon
366579c12b ci(github): add unit tests
!43
2024-08-02 04:59:54 +09:30
Jon
fed0c5c3e5 chore: artifacthub preperation
!43
2024-08-01 17:31:00 +09:30
c496d10c1a bump: version 1.0.0-b4 → 1.0.0-b5 2024-07-31 17:02:31 +00:00
Jon
3993cc96a5 Merge branch '160-api-config' into 'development'
feat: add Config groups to API

Closes #161 and #160

See merge request nofusscomputing/projects/centurion_erp!45
2024-07-31 16:44:55 +00:00
Jon
a4b37b34a9 docs: Add dets of collection
!45 closes #161
2024-08-01 02:12:42 +09:30
Jon
2f55024f0b fix(api): Ensure device groups is read only
checks for required fields

!45 #160 #162
2024-08-01 01:54:24 +09:30
Jon
213644a51a test(api): Field existence and type checks for device
checks for required fields

!45 #160 #162
2024-08-01 01:12:33 +09:30
Jon
281d839801 feat(api): Add device config groups to devices
!45 #160 nofusscomputing/projects/ansible/collections/centurion_erp_collection!7 nofusscomputing/projects/ansible/collections/centurion_erp_collection#4
2024-08-01 00:32:16 +09:30
Jon
4fd157a785 test(api): test configgroups API fields
tests for type and existence

!45 closes #160
2024-07-31 22:27:45 +09:30
Jon
968b3a0f92 feat(api): Ability to fetch configgroups from api along with config
!45 #160 nofusscomputing/projects/ansible/collections/centurion_erp_collection#4
2024-07-31 22:27:32 +09:30
Jon
f5ba608ed1 ci: var to export for use in script
!45
2024-07-31 21:19:55 +09:30
289668bb7f bump: version 1.0.0-b3 → 1.0.0-b4 2024-07-29 07:54:33 +00:00
Jon
9e28722dba Merge branch 'b3-fixes' into 'development'
fix: release-b3 fixes

Closes #155

See merge request nofusscomputing/projects/centurion_erp!44
2024-07-29 07:38:00 +00:00
Jon
9b673f4a07 fix(api): cleanup team post/get
!44 #159
2024-07-29 17:03:25 +09:30
Jon
3a9e4b29b3 fix(api): confirm HTTP method is allowed before permission check
return HTTP/405 for logged in user ONLY!!

!44 #159
2024-07-29 17:02:52 +09:30
Jon
8d59462561 fix(api): Ensure that organizations can't be created via the API
!44 fixes #155
2024-07-29 17:02:37 +09:30
Jon
098e41e6a1 feat(swagger): remove {format} suffixed doc entries
!44
2024-07-29 16:49:51 +09:30
Jon
fc3f0b39e2 ci: add debug out to extra command
!44
2024-07-29 16:49:24 +09:30
Jon
de53948cea test: confirm that the tenancymanager is called
!43
2024-07-21 13:27:45 +09:30
Jon
823ebc0eb5 fix(access): Team model class inheritance order corrected
!42
2024-07-21 13:27:36 +09:30
41414438d1 bump: version 1.0.0-b2 → 1.0.0-b3 2024-07-21 01:47:05 +00:00
Jon
5704560beb fix(itam): Limit os version count to devices user has access to
!42
2024-07-21 10:07:36 +09:30
Jon
8a48902b64 ci: return command to release
!42
2024-07-20 13:02:21 +09:30
61fe059513 bump: version 1.0.0-b1 → 1.0.0-b2 2024-07-19 10:41:41 +00:00
Jon
94576cc733 ci: fix additional command as part of release
!42
2024-07-19 19:45:50 +09:30
Jon
3a32c62119 fix(itam): only show os version once
!42 fixes #139
2024-07-19 18:01:10 +09:30
Jon
9ea4fe1adc ci: Create Version labels within repo on release
!42
2024-07-19 18:01:10 +09:30
Jon
0798a672c2 docs(administration): spread the love out
!42
2024-07-19 18:01:10 +09:30
f4e68529ba bump: version 1.0.0-a4 → 1.0.0-b1 2024-07-19 07:15:09 +00:00
Jon
92a411baec docs(administration): explain the magic
!42 #74
2024-07-19 16:27:33 +09:30
Jon
034857d088 ci: dev branch releases now beta
preperation for RC. all dev releases are now beta.

!42 #74
2024-07-19 15:35:32 +09:30
Jon
e5ce86a9bb fix(itam): ensure installed operating system count is limited to users organizations
!42
2024-07-19 11:02:56 +09:30
Jon
5188b3d52e fix(itam): ensure installed software count is limited to users organizations
!42
2024-07-19 00:39:05 +09:30
61b9435d1f bump: version 1.0.0-a3 → 1.0.0-a4 2024-07-18 12:59:03 +00:00
Jon
8244676530 test: ensure inventory upload matches by both serial number and uuid if device name different
!42 #15
2024-07-18 22:05:12 +09:30
Jon
ec1e7cca85 test: placeholder for moving organization
!42 #15
2024-07-18 22:04:27 +09:30
Jon
72ab9253d7 feat(api): When processing uploaded inventory and name does not match, update name to one within inventory file
!43
2024-07-18 17:08:52 +09:30
Jon
4f89255c4f feat(config_management): Group name to be entire breadcrumb
!43
2024-07-18 16:51:22 +09:30
8d6d1d0d56 bump: version 1.0.0-a2 → 1.0.0-a3 2024-07-18 06:25:34 +00:00
Jon
2d0c3a660a fix(config_management): dont attempt to do action during save if group being created
!42
2024-07-18 15:34:25 +09:30
Jon
974a208869 chore(config_management): remove org filter as its not required
not required as org filtering is done as part of the initial queryset within the model.

!42
2024-07-18 15:34:25 +09:30
Jon
7f225784c2 chore(settings): remove org filter as its not required
not required as org filtering is done as part of the initial queryset within the model.

!42
2024-07-18 15:34:25 +09:30
Jon
a3be95013c fix(itam): remove org filter for device so that user can see installations
not required as org filtering is done as part of the initial queryset within the model.

!42
2024-07-18 15:34:25 +09:30
Jon
adefbf3960 fix(itam): remove org filter for operating systems so that user can see installations
not required as org filtering is done as part of the initial queryset within the model.

!42
2024-07-18 15:34:25 +09:30
Jon
9a1ca7a104 fix(itam): remove org filter for software so that user can see installations
not required as org filtering is done as part of the initial queryset within the model.

!42
2024-07-18 15:34:25 +09:30
Jon
e84e80cd8f feat(config_management): Prevent a config group from being able to change organization
!42
2024-07-18 15:34:25 +09:30
Jon
ebc266010a feat(itam): On device organization change remove config groups
!42
2024-07-18 15:34:25 +09:30
Jon
519277e18b fix(itam): Device related items should not be global.
!42
2024-07-18 15:34:25 +09:30
Jon
a5a5874211 fix(itam): When changing device organization move related items too.
!42 fixes #137
2024-07-18 15:34:25 +09:30
fa2b90ee7b bump: version 1.0.0-a1 → 1.0.0-a2 2024-07-17 16:53:14 +00:00
Jon
5c74360842 fix(base): dont show user warning bar for non-authenticated user
!42
2024-07-18 01:48:57 +09:30
Jon
8457f15eca fix(api): correct inventory operating system selection by name
!42 #134
2024-07-18 01:48:21 +09:30
Jon
5bc5a4b065 docs(worker): add worker and task logs
!42 fixes #135
2024-07-18 01:28:22 +09:30
Jon
40350d166e feat(api): Inventory matching of device second by uuid
!42 #134
2024-07-18 01:17:51 +09:30
Jon
9a94ba31e4 feat(api): Inventory matching of device first by serial number
!42 #134
2024-07-18 01:17:29 +09:30
Jon
55197e7dcc fix(api): correct inventory operating system and it's linking to device
wasn't updating existing device os

!42 #134
2024-07-18 01:16:34 +09:30
Jon
a67bc70503 fix(api): correct inventory device search to be case insensitive
!42 fixes #134
2024-07-18 01:14:33 +09:30
Jon
60538e1cec feat(base): show warning bar if the user has not set a default organization
!42 fixes #133
2024-07-17 23:51:25 +09:30
Jon
416e029c23 revert: return ci build settings to not include branch alpha
partial revert of a1759ecaaf

!42
2024-07-17 11:00:41 +09:30
fe64c11927 bump: version 0.7.0 → 1.0.0-a1 2024-07-16 05:56:44 +00:00
Jon
1f8244ae40 ci: use updated commitizen
!42 !40 #74
2024-07-16 15:11:39 +09:30
Jon
9871cf248b Merge branch 'v-1-0-0-alpha' into 'development'
refactor: repo preperation for v1.0.0-Alpha-1

See merge request nofusscomputing/projects/centurion_erp!40
2024-07-16 04:24:44 +00:00
Jon
a1759ecaaf ci: add alpha branch to docker builds and publish
!40 !42 #74
2024-07-16 13:39:52 +09:30
Jon
30e0342f52 ci: temp change to release, on dev to be alpha release
!40 !35 #74
2024-07-16 13:31:18 +09:30
Jon
5a201ef548 refactor!: Squash database migrations
BREAKING CHANGE: squashed DB migrations in preparation for v1.0 release.

!40 !35 #74
2024-07-16 13:31:18 +09:30
Jon
7b26fac73d feat: Administratively set global items org/is_global field now read-only
!42 fixes #126
2024-07-16 13:19:30 +09:30
Jon
7c62309a31 fix(core): migrate manufacturer to use new form/view logic
!42 fixes #127
2024-07-16 11:55:25 +09:30
Jon
621cbd2d71 revert: return organization filtering back to forms
!42 #124
2024-07-16 00:02:45 +09:30
Jon
d8e89bee10 test: tenancy objects
!42 #15 closes #124
2024-07-15 23:22:15 +09:30
Jon
4ee62aa399 test: refactor to single abstract model for inclusion.
!42 #15
2024-07-15 23:01:49 +09:30
Jon
f1201e8933 feat(access): Add multi-tennant manager
manager filters results to that of data from the organizations the users is part of.

!42 #124
2024-07-15 16:17:08 +09:30
Jon
9acc4fdfcb docs(gitlab): update MR template
!42 #74
2024-07-14 17:16:16 +09:30
Jon
6776612b66 chore: move docker-compose to deploy directory
intent of dir is that is the location for all avail deploy methods

!42 #74
2024-07-14 17:11:49 +09:30
Jon
af3e770760 fix(settings): correct the permission to view manufacturers
!42 #74
2024-07-14 17:09:18 +09:30
Jon
fbe7e63cc9 fix(access): Correct team form fields
fixes missing name for team

!42 #74
2024-07-14 16:57:25 +09:30
Jon
aec460306b fix(config_management): don't exclude parent from field, only self
!42 #74
2024-07-14 16:48:54 +09:30
46c4419350 bump: version 0.6.0 → 0.7.0 2024-07-14 06:25:37 +00:00
Jon
1f35893db9 chore: footer text to be grey
does not need to be prominent

!35
2024-07-14 15:27:03 +09:30
Jon
935e10dc24 docs(development): add initial forms
!35
2024-07-14 04:56:11 +09:30
Jon
a4617c28f8 chore: complete footer layout
git icon from https://gitlab-org.gitlab.io/gitlab-svgs

!35 closes #25
2024-07-14 04:22:41 +09:30
Jon
d4aaea4dbb docs(development): update views, models and index
!35
2024-07-14 03:10:42 +09:30
Jon
a7168834ba chore: add new exception MissingAttribute
used for development

!35
2024-07-14 02:52:28 +09:30
Jon
329049e81d docs: roadmap update
!35
2024-07-14 01:51:53 +09:30
Jon
e25ec12cb0 ci: correct test report path
!35
2024-07-14 01:15:54 +09:30
Jon
5ae487cd3e fix(config_management): Don't allow a config group to assign itself as its parent
!35 fixes #122
2024-07-14 01:09:19 +09:30
Jon
4c42f77692 feat(core): Filter every form field if associated with an organization to users organizations only
!35 fixes #119
2024-07-14 01:08:00 +09:30
Jon
3aab7b57e8 fix(config_management): correct permission for deleting a host from config group
!35
2024-07-13 23:12:31 +09:30
Jon
931c9864db fix(config_management): use parent group details to work out permissions when adding a host
!35 fixes #120
2024-07-13 23:11:59 +09:30
Jon
65bf994619 fix(config_management): use parent group details to work out permissions
!35 fixes #121
2024-07-13 22:44:54 +09:30
Jon
367c4bebb6 refactor: adjust views missing add/change form to now use forms
!35 #15 #46 #74 #120 #121 fixes #118
2024-07-13 17:32:45 +09:30
Jon
8c1be67974 test: add test test_view_*_attribute_not_exists_fields for add and change views
!25 #15 #46
2024-07-13 17:25:20 +09:30
Jon
789c035a03 test: fix test_view_change_attribute_type_form_class to test if type class
!25 #15 #46
2024-07-13 17:23:56 +09:30
Jon
1cf15f7339 feat(core): add var template_name to common view template for all views that require it
!35
2024-07-13 16:01:12 +09:30
Jon
77ff580f19 fix(itam): Add missing permissions to software categories index view
!35 #74
2024-07-13 16:01:12 +09:30
Jon
423ff11d4c fix(itam): Add missing permissions to device types index view
!35 #74
2024-07-13 16:01:12 +09:30
Jon
9e4b5185b1 fix(itam): Add missing permissions to device model index view
!35 #74
2024-07-13 16:01:12 +09:30
Jon
020441c41a fix(settings): Add missing permissions to app settings view
!35 #74
2024-07-13 16:01:12 +09:30
Jon
d0a3b7b49d fix(itam): Add missing permissions to software index view
!35 #74
2024-07-13 16:01:12 +09:30
Jon
960fa5485d fix(itam): Add missing permissions to operating system index view
!35 #74
2024-07-13 16:01:12 +09:30
Jon
26db463044 fix(itam): Add missing permissions to device index view
!35 #74
2024-07-13 16:01:12 +09:30
Jon
1193f1d86d fix(config_management): Add missing permissions to group views
!35 #74
2024-07-13 16:01:12 +09:30
Jon
9bece0a811 test(views): add test cases for model views
!35  #46 #15 #118 #120 #121
2024-07-13 16:01:12 +09:30
Jon
f29ec63f46 test: Add Test case abstract classes to models
!35 #46 #15
2024-07-13 16:01:12 +09:30
Jon
e48278e6e9 Merge branch 'docs' into 'development'
docs(centurion_docs): update docs

See merge request nofusscomputing/projects/centurion_erp!41
2024-07-13 04:19:40 +00:00
c41c7ed1f0 docs: update mkdocs
Change Repo name
Update URL and URI

!41
2024-07-13 12:04:59 +09:30
c9190e9a7d docs: Update index
Slight re-word

nofusscomputing/projects/centurion_erp!41
2024-07-13 11:58:15 +09:30
0294f5ed65 docs(centurion): replace Django ITSM -> Centurion ERP
nofusscomputing/projects/centurion_erp!41
2024-07-13 11:57:34 +09:30
Jon
ae4fdcfc58 chore: clean-up readme
!35
2024-07-12 13:50:34 +09:30
Jon
a395f30bd4 fix(security) update djangorestframework 3.15.1 -> 3.15.2
[CVE-2024-21520](https://cwe.mitre.org/data/definitions/79.html)

!35
2024-07-12 13:48:06 +09:30
Jon
c057ffdc9c feat(core): add Display view to common forms abstract class
intended to display generic data

!35
2024-07-12 12:47:17 +09:30
Jon
6837c38303 feat(navigation): always show every menu for super admin
!35
2024-07-12 12:44:41 +09:30
Jon
ee8920a464 fix(navigation): always show settings menu entry
!35
2024-07-12 09:27:29 +09:30
Jon
ccfdf005f7 chore: remove issue#13 links for model notes
!35 closes #13
2024-07-12 09:23:12 +09:30
Jon
0276f9454b refactor: add navigation menu expand arrows
!35 closes #21
2024-07-12 09:19:13 +09:30
Jon
45cc34284a feat(core): only display navigation menu item if use can view model
!35 fixes #114
2024-07-12 07:16:05 +09:30
Jon
7329a65ae7 docs: update roadmap
!35
2024-07-12 05:56:22 +09:30
Jon
9a529a64e2 docs: add bug count badge
!35
2024-07-12 05:53:21 +09:30
Jon
f2640df0d3 feat(django): update 5.0.6 -> 5.0.7
!35
2024-07-12 05:51:21 +09:30
Jon
7d172fb4af refactor: migrate views to use new abstract model view classes
!35 fixes #111
2024-07-12 05:50:36 +09:30
Jon
f848d01b34 refactor: migrate forms to use new abstract model form class
!35
2024-07-12 05:47:49 +09:30
Jon
44f20b28be feat(core): add common forms abstract class
form class for inclusion in our forms

!35
2024-07-12 05:45:39 +09:30
Jon
2e22a484a0 feat(core): add common views abstract class
class for our views

!35
2024-07-12 05:03:11 +09:30
Jon
a62a36ba82 fix(itam): cater for fields that are prefixed
!35 fixes #112
2024-07-11 18:27:07 +09:30
Jon
c00cf16bc8 fix(itam): Ability to view software category
Ensure organization filters to list of orgs

!35
2024-07-11 18:12:07 +09:30
Jon
7784dfede9 fix(itam): correct view permission
!35
2024-07-11 18:01:10 +09:30
Jon
03d350e302 fix(access): When adding a new team to org ensure parent model is fetched
!35
2024-07-11 17:56:12 +09:30
Jon
9b79c9d7ff docs: update readme
!35
2024-07-11 16:57:21 +09:30
Jon
1d5c86f13b fix(access): enable org manager to view orgs
corrects http/500

!35 fixes #105
2024-07-11 16:34:19 +09:30
Jon
9e336d368d fix(settings): restrict user visible organizations to ones they are part of
this includes if they are the org manager

!35 fixes #99
2024-07-11 15:53:50 +09:30
Jon
937e935949 fix(access): enable org manager to view orgs
!35 fixes #105
2024-07-11 15:37:16 +09:30
Jon
860eaa6749 fix(access): fetch object if method exists
enables the setting og self.model with get_object method

!35 fixes #105
2024-07-11 14:25:53 +09:30
Jon
aab94431a9 fix(docs): update docs link to new path
!35 fixes #103
2024-07-11 14:08:18 +09:30
Jon
7cfede45b8 refactor(access): Rename Team Button "new user" -> "Assign User"
!35 fixes #110
2024-07-11 14:00:55 +09:30
Jon
65de93715d refactor(access): model pk and name not required context for adding a device
!35
2024-07-11 13:59:58 +09:30
Jon
fea7ea3119 refactor: rename field "model notes" -> "Notes"
!35 fixes #102 #104
2024-07-11 13:58:14 +09:30
Jon
524a70ba18 fix(access): correctly set team user parent model to team
!35 fixes #109
2024-07-11 13:43:27 +09:30
Jon
29c4b4a0ca fix(access): fallback to django permissions if org permissions check is false
!35 #109 fixes #101
2024-07-11 13:41:36 +09:30
Jon
f5ae01b08d fix(access): Correct logic so that org managers can see orgs they manage
!35 fixes #100
2024-07-10 17:23:24 +09:30
Jon
ee3dd68cfe fix(base): add missing content_title to context
!35 #74
2024-07-10 15:58:18 +09:30
Jon
25efa31493 fix(access): Enable Organization Manager to view organisations they are assigned to
!35 fixes #100
2024-07-10 15:14:53 +09:30
Jon
4a6ce35332 fix(api): correct logic for adding inventory UUID and serial number to device
!35
2024-07-10 14:45:46 +09:30
Jon
332810ffd6 feat: add postgreSQL database support
!35
2024-07-10 14:05:34 +09:30
Jon
f0bbd22cf4 refactor: remove settings model
wasnt required, so removed

!35
2024-07-10 12:02:06 +09:30
Jon
6bf681530d chore: fix docs indent
!35
2024-07-10 03:04:04 +09:30
Jon
9dd2f6a341 docs: fix mkdocs navigation
!35
2024-07-10 02:13:32 +09:30
Jon
23c640a460 docs: add roadmap
!35
2024-07-10 02:13:12 +09:30
Jon
3c6092f776 chore: rename to Centurion ERP
!35
2024-07-10 01:58:19 +09:30
Jon
cb66b9303a feat(ui): add config groups navigation icon
!35
2024-07-09 22:50:38 +09:30
Jon
2d80f02634 fix(ui): navigation alignment and software icon
!35
2024-07-09 22:34:35 +09:30
Jon
abe1ce6948 fix(ui): display organization manager name instead of ID
!35
2024-07-09 22:31:55 +09:30
Jon
fb907283b0 refactor(ui): increase indentation to sub-menu items
!35
2024-07-09 17:32:29 +09:30
Jon
86ed7318ec fix(access): ensure name param exists before attempting to access
!35
2024-07-09 17:29:48 +09:30
Jon
a2a8e12046 feat(ui): add some navigation icons
!35 #21 #22 #23
2024-07-09 17:21:46 +09:30
Jon
c1a8ee65f2 refactor(itam): rename old inventory status icon for use with security
!35
2024-07-09 16:24:52 +09:30
Jon
6a14f78bf7 feat(itam): update inventory status icon
!35
2024-07-09 16:24:10 +09:30
Jon
90a01911da fix(itam): dont show none/nil for device fields containing no value
!35
2024-07-09 15:47:27 +09:30
Jon
de3ed3a881 fix(itam): show device model name instead of ID
!35
2024-07-09 15:42:46 +09:30
Jon
656807e410 feat(itam): ensure device software pagination links keep interface on software tab
!35 closes #81
2024-07-09 14:33:22 +09:30
Jon
f64be2ea33 fix(api): Ensure if serial number from inventory is null that it's not used
!35 fixes #78
2024-07-09 13:21:19 +09:30
Jon
ef9c596ec7 fix(api): ensure checked uuid and serial number is used for updating
!35
2024-07-09 05:28:48 +09:30
Jon
f22e886d92 Merge branch '76-background-worker' into 'development'
feat: "Migrate inventory processing to background worker"

See merge request nofusscomputing/projects/django_template!39
2024-07-08 18:34:33 +00:00
Jon
a2c67541ec test(inventory): add mocks?? for calling background worker
!39 #76
2024-07-09 03:51:21 +09:30
Jon
5f4231ab04 test(view): view permission checks
!39 #76
2024-07-09 02:29:35 +09:30
Jon
b0405c8fd0 test(inventory): update tests for background worker changes
!39 #76
2024-07-09 02:27:24 +09:30
Jon
b42bb3a30e feat(access): enable non-organization django permission checks
!39 #76
2024-07-09 02:26:21 +09:30
Jon
27eb54cc37 docs(api): update swagger docs with inventory changes
!39 #76
2024-07-08 23:10:34 +09:30
Jon
a8e2c687b1 docs(administration): notate rabbitMQ setup
!39 #76
2024-07-08 23:06:51 +09:30
Jon
7aeba34787 refactor(api): migrate inventory processing to background worker
!39 #76
2024-07-08 22:54:34 +09:30
Jon
090c4a5425 feat(settings): Add celery task results index and view page
!39 #76
2024-07-08 22:52:34 +09:30
Jon
87a1f2aa20 feat(base): Add background worker
!39 #76
2024-07-08 22:38:06 +09:30
Jon
70135eaa91 Merge branch 'fixes-inventory' into 'development'
fix: inventory

See merge request nofusscomputing/projects/django_template!38
2024-07-06 06:17:54 +00:00
Jon
f47b97e2a0 refactor(itam): only perform actions on device inventory if DB matches inventory item
!38 #75
2024-07-06 15:45:48 +09:30
Jon
67f20ecb66 fix(itam): only remove device software when not found during inventory upload
!38 #75
2024-07-06 15:45:48 +09:30
Jon
3bceb66600 fix(itam): only update software version if different
!38 #75
2024-07-06 15:45:48 +09:30
Jon
fe34b8274d chore: update submodules to head
!35
2024-07-01 04:03:05 +09:30
Jon
a235aa7ec3 ci: add submodule update job
!35
2024-07-01 04:02:51 +09:30
Jon
f69f883439 Merge branch '66-fix-inventory-uuid-update' into 'development'
fix: existing device without uuid not updated when uploading an inventory

Closes #66

See merge request nofusscomputing/projects/django_template!37
2024-06-30 15:06:02 +00:00
Jon
7b4ed7b135 feat(itam): Update Serial Number from inventory if present and Serial Number not set
!37
2024-07-01 00:27:46 +09:30
Jon
b801c9a49e feat(itam): Update UUID from inventory if present and UUID not set
!37 fixes #66
2024-07-01 00:27:28 +09:30
Jon
583e1767a1 Merge branch '67-fix-device-software-pagination' into 'development'
fix: Device Software tab pagination does not work

Closes #67

See merge request nofusscomputing/projects/django_template!36
2024-06-30 14:33:19 +00:00
Jon
241ba47c80 fix(itam): correct device software pagination
!36 fixes #67
2024-07-01 00:01:28 +09:30
c2d673ca1b bump: version 0.5.0 → 0.6.0 2024-06-30 07:13:40 +00:00
Jon
05c46df0a9 Merge branch '63-feat-user-api-token' into 'development'
feat: user api token

Closes #63 and #65

See merge request nofusscomputing/projects/django_template!34
2024-06-30 06:51:16 +00:00
Jon
53284d456f test(token_auth): test authentication method token
!34 closes #63
2024-06-30 16:16:29 +09:30
Jon
6cfcf1580c fix(user_token): conduct user check on token view access
!34 #63
2024-06-30 16:05:31 +09:30
Jon
4d3a238583 docs: Add user settings documentation
!34 #63
2024-06-30 12:35:58 +09:30
Jon
47d6a3beff docs(api): API Token authentication
!34 #63
2024-06-29 16:24:18 +09:30
Jon
111791438a feat(api): API token authentication
!34 #63
2024-06-29 15:09:30 +09:30
Jon
ce2c6f3b13 feat(api): abilty for user to create/delete api token
!34 #63
2024-06-28 15:52:55 +09:30
Jon
e655f22fac feat(api): create token model
!34 #63
2024-06-28 03:57:09 +09:30
Jon
66b8d9362d refactor(settings): use seperate change/view views
!34
2024-06-28 02:06:30 +09:30
Jon
37d277e149 refactor(settings): use form for user settings
!34
2024-06-28 01:18:48 +09:30
Jon
f686691232 fix(itam): use same form for edit and add
!34 fixes #65
2024-06-27 17:53:38 +09:30
Jon
802f2c410d fix(itam): dont add field inventorydate if adding new item
!34
2024-06-27 17:52:18 +09:30
Jon
be559d3d9d Merge branch 'testing' into 'development'
test: more tests

See merge request nofusscomputing/projects/django_template!33
2024-06-19 19:47:33 +00:00
Jon
d6cfef3a0b test: add .coveragerc to remove non-code files from coverage report
!33 #15
2024-06-20 05:12:04 +09:30
Jon
4fdb3df06e test: Unit Tests TenancyObjects
!33 #15
2024-06-20 03:12:43 +09:30
Jon
7eb0651b89 test: Test Cases for TenancyObjects
!33 #15
2024-06-20 03:07:39 +09:30
Jon
6d3984f6e1 test: tests for checking links from rendered templetes
!33 #15
2024-06-20 02:09:15 +09:30
Jon
58b134ae30 refactor(tests): move unit tests to unit test sub-directory
!33 #15
2024-06-19 22:58:50 +09:30
Jon
50384044c8 test(core): test cases for notes permissions
!33 #15
2024-06-19 17:08:42 +09:30
Jon
2cda4228ce test(config_management): config groups history permissions
!33 #15
2024-06-19 16:09:23 +09:30
Jon
67585b9f89 test(api): Majority of Inventory upload tests
!33 #15
2024-06-19 15:48:10 +09:30
Jon
4e42856027 fix(api): inventory upload requires sanitization
!33
2024-06-19 15:00:30 +09:30
Jon
58051f297f test(access): TenancyObject field tests
!33 #15
2024-06-19 11:51:03 +09:30
Jon
0a9a5b20fa test(access): remove skipped api tests for team users
teamusers not accessible from api

!33 #15
2024-06-19 10:52:24 +09:30
Jon
a0874356fd ci(git_sync): sync on push ro feature branch 14-feat-project-management
!29 !31
2024-06-18 08:55:56 +09:30
Jon
5d8f5e3a51 ci: remove dockerhub publish on bot push
!29
2024-06-18 01:21:30 +09:30
19ae56d92c bump: version 0.4.0 → 0.5.0 2024-06-17 15:14:24 +00:00
Jon
488a12df45 Merge branch '39-org-manager' into 'development'
feat: Setup Organization Managers

Closes #39

See merge request nofusscomputing/projects/django_template!28
2024-06-17 14:50:00 +00:00
Jon
a94856879e docs: correct testing link
!28
2024-06-18 00:18:00 +09:30
Jon
94375dc30e chore: add default MR template
!28
2024-06-18 00:14:23 +09:30
Jon
108398da4b docs: rejig
!28
2024-06-18 00:10:51 +09:30
Jon
8abbf2ff9e docs(access): correct doc warnings
!28
2024-06-17 23:42:54 +09:30
Jon
27b62d1018 docs(access): add link to docs on team page
!28 closes #39
2024-06-17 23:27:11 +09:30
Jon
aef276b76c docs(access): add link to docs on organization page
!28 #39
2024-06-17 23:26:52 +09:30
Jon
c15eca2e58 test(access): team user model permission check for organization manager
!28 #39 #15
2024-06-17 22:59:26 +09:30
Jon
33b10f7109 test(access): team model permission check for organization manager
!28 #39 #15
2024-06-17 22:53:23 +09:30
Jon
9a40d095e8 test(access): organization model permission check for organization manager
!28 #39 #15
2024-06-17 22:52:57 +09:30
Jon
991ddc3d7f refactor(access): relocate permission check to own function
!28 #39
2024-06-17 22:52:02 +09:30
Jon
35c11ed6f0 test(access): add test cases for model delete as organization manager
!28 #39 #15
2024-06-17 22:41:40 +09:30
Jon
e4f5ec4892 test(access): add test cases for model addd as organization manager
!28 #39 #15
2024-06-17 22:40:35 +09:30
Jon
109fc49d76 test(access): add test cases for model change as organization manager
!28 #39 #15
2024-06-17 22:17:59 +09:30
Jon
da8946fcb6 test(access): add test cases for model view as organization manager
!28 #39 #15
2024-06-17 22:13:41 +09:30
Jon
848661856a feat(access): add notes field to organization
!28 #39 #13
2024-06-17 19:40:46 +09:30
Jon
14acea31f2 feat(access): add organization manger
org managager regardless of permissions can conduct all operations against an organization.

!28 #39
2024-06-17 19:38:11 +09:30
Jon
2bbf78d888 Merge branch '15-tests' into 'development'
test: write some more

Closes #57 and #52

See merge request nofusscomputing/projects/django_template!27
2024-06-17 08:44:15 +00:00
Jon
afb5a709d7 docs: add badges to index
!27
2024-06-17 17:58:21 +09:30
Jon
ddead8eb56 docs: restructure to sections administration, user and devlopment
!27 nofusscomputing/infrastructure/website!62
2024-06-17 17:39:01 +09:30
Jon
e517c5fd76 refactor(itam): move device os tab to details tab
!27 #22
2024-06-17 15:23:38 +09:30
Jon
a6e569eaef test(core): skip invalid tests
tests for notes belong within the models that rx notes

!27 #15 #52
2024-06-17 14:46:48 +09:30
Jon
78216116df fix(itam): remove requirement that user needs change device to add notes
!27 fixes #52
2024-06-17 14:35:36 +09:30
Jon
b20b426432 test(itam): tests for device type history entries
!27 #15
2024-06-17 14:10:12 +09:30
Jon
44afa4f7de test(core): tests for manufacturer history entries
!27 #15
2024-06-17 14:06:25 +09:30
Jon
2be4810ed4 test: move manufacturer to it's parent
!27
2024-06-17 13:59:21 +09:30
Jon
f861295b1c docs(development): add device model to api docs
!27
2024-06-16 06:26:37 +09:30
Jon
320d3f1a13 test: refactor api model permission tests to use an abstract class of test cases
!27 #15
2024-06-16 03:43:17 +09:30
Jon
3613318217 test: move tests to the module they belong to
!27 #15
2024-06-16 01:44:33 +09:30
Jon
ceb1929d8c test: refactor history permission tests to use an abstract class of test cases
!27 #15
2024-06-16 01:43:07 +09:30
Jon
dbcb282548 docs: docstrings show category headings
!27
2024-06-16 01:10:17 +09:30
Jon
5eec41fe57 docs(development): Add test case documentation
!27 #15 nofusscomputing/infrastructure/website-template!16 nofusscomputing/projects/django_template#57 nofusscomputing/projects/gitlab-ci!83
2024-06-16 00:15:01 +09:30
Jon
e72eedf077 test: refactor model permission tests to use an abstract class of test cases
!27 #15
2024-06-15 21:40:33 +09:30
Jon
6286b06270 test: refactor history entry to have test cases in abstract classes
!27 #15
2024-06-15 18:50:10 +09:30
Jon
d2bf0e54d7 test(itam): history entry tests for software category
!27 #15
2024-06-15 17:40:31 +09:30
Jon
7f1a7eaa0d test(itam): history entry tests for device operating system version
!27 #15
2024-06-15 17:31:24 +09:30
Jon
29b104a6ce test(itam): history entry tests for device operating system
!27 #15
2024-06-15 17:17:07 +09:30
Jon
1220ddbd00 test(itam): history entry tests for device software
!27 #15
2024-06-15 17:03:51 +09:30
Jon
da746b8977 test(itam): ensure child history is removed on config group software delete
!27 #15
2024-06-15 16:37:18 +09:30
Jon
34db5f863a test: add placeholder tests
!27 #15
2024-06-15 16:31:23 +09:30
Jon
92fe05d083 test(itam): ensure history is removed on software delete
!27 #15
2024-06-15 16:25:38 +09:30
Jon
5280db8767 test(itam): ensure history is removed on operating system delete
!27 #15
2024-06-15 16:24:51 +09:30
Jon
9eda12c232 test(itam): ensure history is removed on device model delete
!27 #15
2024-06-15 16:23:51 +09:30
Jon
54c34a95f5 fix(core): dont attempt to access parent_object if 'None' during history save
!27
2024-06-15 16:19:55 +09:30
Jon
b7a2bfc612 test(config_management): test history on delete for config groups
!27 #15
2024-06-15 16:18:59 +09:30
Jon
3b3ee9fc3d fix(config_management): Add missing parent item getter to model
!27
2024-06-15 16:17:19 +09:30
Jon
d64108331f test(itam): ensure history is removed on device delete
!27 #15
2024-06-15 15:55:28 +09:30
Jon
372eefa5c4 test(access): test team history
!27 #15
2024-06-15 15:54:32 +09:30
Jon
733a31ad71 test(access): ensure team user history is created and removed as required
!27 #15
2024-06-15 15:06:51 +09:30
Jon
4a19bb2ecc test(access): ensure history is removed on team delete
!27 #15
2024-06-15 14:13:37 +09:30
Jon
29a8969288 test(access): ensure history is removed on item delete
!27 #15
2024-06-15 14:12:19 +09:30
Jon
0a1aba7ca8 fix(core): overridden save within SaveHistory to use default attributes
!27
2024-06-15 14:09:17 +09:30
Jon
eb8dca9806 fix(access): overridden save to use default attributes
!27
2024-06-15 14:08:53 +09:30
Jon
8af5975428 feat(config_management): Use breadcrumbs for child group name display
formatted as '<parent name> > <child name>'

!21
2024-06-14 09:13:14 +09:30
Jon
4a10409551 refactor(itam): add device change form and adjust view to be non-form
!21
2024-06-14 09:02:17 +09:30
Jon
ac70715752 feat(config_management): ability to add host to global group
!21
2024-06-14 07:03:59 +09:30
Jon
8ccdf9a8f3 feat(itam): add a status of "bad" for devices
indicates inventory is older than 72-hours

!21
2024-06-14 06:31:27 +09:30
Jon
1200a87913 feat(itam): paginate device software tab
!21
2024-06-14 06:20:13 +09:30
Jon
dfba01aed9 chore: add itim module skeleton
!21 #61
2024-06-14 06:00:13 +09:30
Jon
e8cb685da1 feat(itam): status of device visible on device index page
!21
2024-06-14 04:43:12 +09:30
Jon
7798deaf27 Merge branch '58-browser' into 'development'
feat: API Browser

See merge request nofusscomputing/projects/django_template!26
2024-06-13 17:26:57 +00:00
Jon
8b47d95614 feat(core): add skeleton http browser
get and post intrim functions

!26 #58
2024-06-14 02:20:33 +09:30
Jon
d4c07d08f1 Merge branch '54-fix-delete-history' into 'development'
fix: History does not delete when item deleted

Closes #54

See merge request nofusscomputing/projects/django_template!25
2024-06-13 15:29:11 +00:00
Jon
7239f572a3 fix(core): on object delete remove history entries
!25 fixes #54
2024-06-13 23:38:30 +09:30
Jon
904234c581 refactor(itam): migrate device vie to use manual entered fields in two columns
!21 #13 #22
2024-06-12 12:49:25 +09:30
Jon
fe1a9d07f7 chore: planning for project management
!21 #14
2024-06-12 12:08:03 +09:30
Jon
c570fb114f feat(core): Add a notes field to manufacturer/ publisher
!21 #13
2024-06-12 05:59:33 +09:30
Jon
ea1727f2c7 feat(itam): Add a notes field to software category
!21 #13
2024-06-12 05:59:12 +09:30
Jon
36d7e54547 feat(itam): Add a notes field to device types
!21 #13
2024-06-12 05:58:58 +09:30
Jon
a02fda8413 feat(itam): Add a notes field to device models
!21 #13
2024-06-12 05:58:50 +09:30
Jon
b5bc76b0ab feat(itam): Add a notes field to software
!21 #13
2024-06-12 05:58:32 +09:30
Jon
36c13e18c7 feat(itam): Add a notes field to operating system
!21 #13
2024-06-12 05:58:22 +09:30
Jon
6969b61164 feat(itam): Add a notes field to devices
!21 #13
2024-06-12 05:58:11 +09:30
Jon
85bf1b9907 feat(access): Add a notes field to teams
!21 #13
2024-06-12 05:57:55 +09:30
Jon
ca8e0c07ea feat(base): Add a notes field to TenancyObjetcs class
!21 #13
2024-06-12 05:57:37 +09:30
Jon
da93425c0b feat(settings): add docs icon to application settings page
!21
2024-06-12 05:08:22 +09:30
Jon
8a9899cf66 feat(itam): add docs icon to software page
!21
2024-06-12 05:08:00 +09:30
Jon
38db558be2 feat(itam): add docs icon to operating system page
!21
2024-06-12 05:07:48 +09:30
Jon
67b204e40c feat(itam): add docs icon to devices page
!21
2024-06-12 05:07:36 +09:30
Jon
456fed80a9 feat(config_management): add docs icon to config groups page
!21
2024-06-12 05:07:19 +09:30
Jon
87282ce41c feat(base): add dynamic docs icon
specifying `context['model_docs_path']` with the path will add the docs icon

!21
2024-06-12 05:06:22 +09:30
Jon
4016d4c200 refactor(access): migrate team users view to use forms
!21
2024-06-12 04:31:02 +09:30
Jon
f36662ca82 refactor(access): migrate teams view to use forms
!21
2024-06-12 04:25:32 +09:30
Jon
3e340a47b8 refactor(access): migrate organization view to use form
!21
2024-06-12 04:23:24 +09:30
Jon
60a22f5574 Merge branch '55-fix-inventory' into 'development'
fix: inventory upload cant determin object organization

Closes #55

See merge request nofusscomputing/projects/django_template!24
2024-06-11 16:30:08 +00:00
Jon
2eb50311b4 docs(api): document the inventory endpoint
!24 #55
2024-06-12 01:48:30 +09:30
Jon
36fa364d04 docs(api): notate inventory permission
!24 #55
2024-06-11 22:21:54 +09:30
Jon
65c6065ba1 test(api): Inventory upload permission checks
!24 #55
2024-06-11 22:19:06 +09:30
Jon
505f4cfdd9 fix(api): ensure proper permission checking
!24 fixes #55
2024-06-11 22:18:50 +09:30
Jon
2252c86f71 Merge branch 'ui-minor' into 'development'
chore: Ui minor

See merge request nofusscomputing/projects/django_template!23
2024-06-10 01:08:45 +00:00
Jon
dc4968ee7b fix: dont throw an exception during settings load for an item django already checks
!23
2024-06-10 09:57:10 +09:30
Jon
3fb2706321 refactor(base): cleanup form and prettyfy
!23 #24
2024-06-10 09:37:54 +09:30
Jon
f05e51510a Merge branch 'feat-43-config-group-software' into 'development'
feat: config group software

Closes #43 and #53

See merge request nofusscomputing/projects/django_template!22
2024-06-09 19:10:10 +00:00
Jon
193dbf1e8b test(config_management): testing of config_groups rendered config
!22 #43
2024-06-10 04:25:29 +09:30
Jon
05bb6f8a51 docs: update contributing with further test info
!22
2024-06-10 03:02:51 +09:30
Jon
6b851ded0e test(config_management): history save tests for config groups software
!22 closes #43
2024-06-10 02:58:33 +09:30
Jon
8d6826f7c0 fix(core): Add overrides for delete so delete history saved for items with parent model
!22 fixes #53
2024-06-10 02:44:57 +09:30
Jon
fe0696fee6 feat(models): add property parent_object to models that have a parent
!22
2024-06-10 00:51:59 +09:30
Jon
11ec62feb6 test(config_management): config group software permission for add, change and delete
!22 #43
2024-06-09 18:11:16 +09:30
Jon
e62a570be3 docs(config_management): notate software group actions
!22 #43
2024-06-08 08:46:32 +09:30
Jon
36962109d1 test(base): placeholder tests for config groups software
!22 #43
2024-06-08 08:37:11 +09:30
Jon
b3b5ad6372 test(base): basic test for merge_software helper
!22 #43
2024-06-08 08:31:55 +09:30
Jon
23c43ed8dc fix(config_management): correct delete success url
!22 #43
2024-06-08 08:31:20 +09:30
Jon
1069211d1b feat(config_management): add config group software to group history
!22 #43
2024-06-08 08:30:55 +09:30
Jon
460eff1f71 feat(itam): render group software config within device rendered config
!22 #43
2024-06-08 07:18:16 +09:30
Jon
0c382a73e5 feat(config_management): assign software action to config group
!22 #43
2024-06-08 07:17:20 +09:30
Jon
ae81ee8863 refactor(config_management): relocate groups views to own directory
!22
2024-06-08 04:07:40 +09:30
Jon
07e93243a0 fix(base): remove social auth from nav menu
!21
2024-06-08 02:22:42 +09:30
Jon
579e44f834 fix(access): add a team user permissions to use team organization
use the parent models organization for permissions to work

!21 fixes #51
2024-06-08 02:20:17 +09:30
Jon
156e446608 Merge branch 'feat-sso' into 'development'
feat: sso

See merge request nofusscomputing/projects/django_template!20
2024-06-07 13:19:10 +00:00
Jon
158eb17907 test: during unit tests add SECRET_KEY
required so that tests run

!20
2024-06-07 22:41:23 +09:30
Jon
8b887575c9 feat: add configuration value 'SESSION_COOKIE_AGE'
!20
2024-06-07 21:27:33 +09:30
Jon
d0e8e9a674 feat: remove development SECRET_KEY and enforce checking for user configured one
!20
2024-06-07 21:13:39 +09:30
Jon
d8d75c7db0 feat(base): build CSRF trusted origins from configuration
!20
2024-06-07 20:36:59 +09:30
Jon
3b743a847c refactor: login to use base template
!20
2024-06-07 20:08:07 +09:30
Jon
95a08b2d2c refactor: adjust template block names
renamed so they make sense

!20
2024-06-07 20:01:56 +09:30
Jon
b38984fcb9 feat(base): Enforceable SSO ONLY
this setting removes the login form and forces a redirect to the SSO signin page.

!20 #1
2024-06-07 19:33:57 +09:30
Jon
3040d4afe7 feat(base): configurable SSO
!20 #1
2024-06-07 19:23:39 +09:30
Jon
fa28fd436e ci: dont rebuild on dev on git tag
!19
2024-06-06 07:27:51 +09:30
454 changed files with 20097 additions and 13666 deletions

View File

@ -1,7 +1,8 @@
---
commitizen:
name: cz_conventional_commits
prerelease_offset: 1
tag_format: $version
update_changelog_on_bump: false
version: 0.4.0
version: 1.0.0-b12
version_scheme: semver

31
.github/workflows/bump.yaml vendored Normal file
View File

@ -0,0 +1,31 @@
---
name: 'Bump'
on:
workflow_dispatch:
inputs:
CZ_PRE_RELEASE:
default: none
required: false
description: Create Pre-Release {alpha,beta,rc,none}
CZ_INCREMENT:
default: none
required: false
description: Type of bump to conduct {MAJOR,MINOR,PATCH,none}
push:
branches:
- 'master'
jobs:
bump:
name: 'Bump'
uses: nofusscomputing/action_bump/.github/workflows/bump.yaml@development
with:
CZ_PRE_RELEASE: ${{ inputs.CZ_PRE_RELEASE }}
CZ_INCREMENT: ${{ inputs.CZ_INCREMENT }}
secrets:
WORKFLOW_TOKEN: ${{ secrets.WORKFLOW_TOKEN }}

33
.github/workflows/ci.yaml vendored Normal file
View File

@ -0,0 +1,33 @@
---
name: 'CI'
on:
push:
branches:
- '**'
tags:
- '*'
jobs:
docker:
name: 'Docker'
uses: nofusscomputing/action_docker/.github/workflows/docker.yaml@development
with:
DOCKER_BUILD_IMAGE_NAME: "nofusscomputing/centurion-erp"
DOCKER_PUBLISH_REGISTRY: "docker.io"
DOCKER_PUBLISH_IMAGE_NAME: "nofusscomputing/centurion-erp"
secrets:
DOCKER_PUBLISH_USERNAME: ${{ secrets.NFC_DOCKERHUB_USERNAME }}
DOCKER_PUBLISH_PASSWORD: ${{ secrets.NFC_DOCKERHUB_TOKEN }}
python:
name: 'Python'
uses: nofusscomputing/action_python/.github/workflows/python.yaml@development
secrets:
WORKFLOW_TOKEN: ${{ secrets.WORKFLOW_TOKEN }}

14
.github/workflows/pull-requests.yaml vendored Normal file
View File

@ -0,0 +1,14 @@
---
name: Pull Requests
on:
pull_request: {}
jobs:
pull-request:
name: pull-request
uses: nofusscomputing/action_pull_requests/.github/workflows/pull-requests.yaml@development

37
.github/workflows/triage.yaml vendored Normal file
View File

@ -0,0 +1,37 @@
---
name: Triage
on:
issues:
types:
- opened
- reopened
- transferred
- milestoned
- demilestoned
- closed
- assigned
pull_request:
types:
- opened
- edited
- assigned
- reopened
- closed
jobs:
project:
name: Project
uses: nofusscomputing/action_project/.github/workflows/project.yaml@development
with:
PROJECT_URL: https://github.com/orgs/nofusscomputing/projects/3
secrets:
WORKFLOW_TOKEN: ${{ secrets.WORKFLOW_TOKEN }}

5
.gitignore vendored
View File

@ -1,8 +1,11 @@
venv/**
*/static/**
__pycache__
**db.sqlite3
**.sqlite3
**.sqlite
**.coverage
artifacts/
**.tmp.*
volumes/
build/
pages/

View File

@ -2,137 +2,293 @@
variables:
MY_PROJECT_ID: "57560288"
GIT_SYNC_URL: "https://$GITHUB_USERNAME_ROBOT:$GITHUB_TOKEN_ROBOT@github.com/NoFussComputing/django_template.git"
# GIT_SYNC_URL: "https://$GITHUB_USERNAME_ROBOT:$GITHUB_TOKEN_ROBOT@github.com/NoFussComputing/centurion_erp.git"
# Docker Build / Publish
DOCKER_IMAGE_BUILD_TARGET_PLATFORMS: "linux/amd64,linux/arm64"
DOCKER_IMAGE_BUILD_NAME: django-template
DOCKER_IMAGE_BUILD_REGISTRY: $CI_REGISTRY_IMAGE
DOCKER_IMAGE_BUILD_TAG: $CI_COMMIT_SHA
# # Docker Build / Publish
# DOCKER_IMAGE_BUILD_TARGET_PLATFORMS: "linux/amd64,linux/arm64"
# DOCKER_IMAGE_BUILD_NAME: centurion-erp
# DOCKER_IMAGE_BUILD_REGISTRY: $CI_REGISTRY_IMAGE
# DOCKER_IMAGE_BUILD_TAG: $CI_COMMIT_SHA
# Docker Publish
DOCKER_IMAGE_PUBLISH_NAME: django-template
DOCKER_IMAGE_PUBLISH_REGISTRY: docker.io/nofusscomputing
DOCKER_IMAGE_PUBLISH_URL: https://hub.docker.com/r/nofusscomputing/$DOCKER_IMAGE_PUBLISH_NAME
# # Docker Publish
# DOCKER_IMAGE_PUBLISH_NAME: centurion-erp
# DOCKER_IMAGE_PUBLISH_REGISTRY: docker.io/nofusscomputing
# DOCKER_IMAGE_PUBLISH_URL: https://hub.docker.com/r/nofusscomputing/$DOCKER_IMAGE_PUBLISH_NAME
# # Extra release commands
# MY_COMMAND: ./.gitlab/additional_actions_bump.sh
# Docs NFC
PAGES_ENVIRONMENT_PATH: projects/django-template/
PAGES_ENVIRONMENT_PATH: projects/centurion_erp/
# RELEASE_ADDITIONAL_ACTIONS_BUMP: ./.gitlab/additional_actions_bump.sh
include:
- local: .gitlab/pytest.gitlab-ci.yml
# - local: .gitlab/pytest.gitlab-ci.yml
# - local: .gitlab/unit-test.gitlab-ci.yml
- project: nofusscomputing/projects/gitlab-ci
ref: development
file:
- .gitlab-ci_common.yaml
- template/automagic.gitlab-ci.yaml
Docker Container:
extends: .build_docker_container
resource_group: build
needs: []
script:
- update-binfmts --display
- |
echo "[DEBUG] building multiarch/specified arch image";
docker buildx build --platform=$DOCKER_IMAGE_BUILD_TARGET_PLATFORMS . \
--label org.opencontainers.image.created="$(date '+%Y-%m-%d %H:%M:%S%:z')" \
--label org.opencontainers.image.documentation="$CI_PROJECT_URL" \
--label org.opencontainers.image.source="$CI_PROJECT_URL" \
--label org.opencontainers.image.revision="$CI_COMMIT_SHA" \
--push \
--build-arg CI_PROJECT_URL=$CI_PROJECT_URL \
--build-arg CI_COMMIT_SHA=$CI_COMMIT_SHA \
--build-arg CI_COMMIT_TAG=$CI_COMMIT_TAG \
--file $DOCKER_DOCKERFILE \
--tag $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
docker buildx imagetools inspect $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
# during docker multi platform build there are >=3 additional unknown images added to gitlab container registry. cleanup
# - template/automagic.gitlab-ci.yaml
- automation/.gitlab-ci-ansible.yaml
- template/mkdocs-documentation.gitlab-ci.yaml
- lint/ansible.gitlab-ci.yaml
DOCKER_MULTI_ARCH_IMAGES=$(docker buildx imagetools inspect "$DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG" --format "{{ range .Manifest.Manifests }}{{ if ne (print .Platform) \"&{unknown unknown [] }\" }}$DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG@{{ println .Digest }}{{end}} {{end}}");
docker buildx imagetools create $DOCKER_MULTI_ARCH_IMAGES --tag $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
docker buildx imagetools inspect $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
rules: # rules manually synced from docker/publish.gitlab-ci.yaml removing git tag
# - if: # condition_master_branch_push
# $CI_COMMIT_BRANCH == "master" &&
# $CI_PIPELINE_SOURCE == "push"
# exists:
# - '{dockerfile,dockerfile.j2}'
# when: always
- if: # condition_not_master_or_dev_push
$CI_COMMIT_BRANCH != "master" &&
$CI_COMMIT_BRANCH != "development" &&
$CI_PIPELINE_SOURCE == "push"
exists:
- '{dockerfile,dockerfile.j2}'
changes:
paths:
- '{dockerfile,dockerfile.j2,includes/**/*}'
compare_to: 'development'
when: always
- if: $CI_COMMIT_TAG
exists:
- '{dockerfile,dockerfile.j2}'
when: always
- if: # condition_dev_branch_push
(
$CI_COMMIT_BRANCH == "development"
||
$CI_COMMIT_BRANCH == "master"
)
&&
$CI_PIPELINE_SOURCE == "push"
exists:
- '{dockerfile,dockerfile.j2}'
allow_failure: true
when: on_success
- when: never
Docker.Hub.Branch.Publish:
extends: .publish-docker-hub
needs: [ "Docker Container" ]
resource_group: build
rules: # rules manually synced from docker/publish.gitlab-ci.yaml removing git tag
# Update Git Submodules:
# extends: .ansible_playbook_git_submodule
# - if: # condition_master_branch_push
# $CI_COMMIT_BRANCH == "master" &&
# $CI_PIPELINE_SOURCE == "push"
# exists:
# - '{dockerfile,dockerfile.j2}'
# when: always
- if: $CI_COMMIT_TAG
exists:
- '{dockerfile,dockerfile.j2}'
when: always
# Docker Container:
# extends: .build_docker_container
# resource_group: build
# needs: []
# script:
# - update-binfmts --display
# - |
- if: # condition_dev_branch_push
$CI_COMMIT_BRANCH == "development" &&
$CI_PIPELINE_SOURCE == "push"
exists:
- '{dockerfile,dockerfile.j2}'
allow_failure: true
when: on_success
# echo "[DEBUG] building multiarch/specified arch image";
- when: never
# docker buildx build --platform=$DOCKER_IMAGE_BUILD_TARGET_PLATFORMS . \
# --label org.opencontainers.image.created="$(date '+%Y-%m-%d %H:%M:%S%:z')" \
# --label org.opencontainers.image.documentation="$CI_PROJECT_URL" \
# --label org.opencontainers.image.source="$CI_PROJECT_URL" \
# --label org.opencontainers.image.revision="$CI_COMMIT_SHA" \
# --push \
# --build-arg CI_PROJECT_URL=$CI_PROJECT_URL \
# --build-arg CI_COMMIT_SHA=$CI_COMMIT_SHA \
# --build-arg CI_COMMIT_TAG=$CI_COMMIT_TAG \
# --file $DOCKER_DOCKERFILE \
# --tag $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
# docker buildx imagetools inspect $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
# # during docker multi platform build there are >=3 additional unknown images added to gitlab container registry. cleanup
# DOCKER_MULTI_ARCH_IMAGES=$(docker buildx imagetools inspect "$DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG" --format "{{ range .Manifest.Manifests }}{{ if ne (print .Platform) \"&{unknown unknown [] }\" }}$DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG@{{ println .Digest }}{{end}} {{end}}");
# docker buildx imagetools create $DOCKER_MULTI_ARCH_IMAGES --tag $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
# docker buildx imagetools inspect $DOCKER_IMAGE_BUILD_REGISTRY/$DOCKER_IMAGE_BUILD_NAME:$DOCKER_IMAGE_BUILD_TAG;
# rules: # rules manually synced from docker/publish.gitlab-ci.yaml removing git tag
# # - if: # condition_master_branch_push
# # $CI_COMMIT_BRANCH == "master" &&
# # $CI_PIPELINE_SOURCE == "push"
# # exists:
# # - '{dockerfile,dockerfile.j2}'
# # when: always
# - if:
# $CI_COMMIT_AUTHOR =='nfc_bot <helpdesk@nofusscomputing.com>'
# &&
# $CI_COMMIT_BRANCH == "development"
# when: never
# - if: # condition_not_master_or_dev_push
# $CI_COMMIT_BRANCH != "master" &&
# $CI_COMMIT_BRANCH != "development" &&
# $CI_PIPELINE_SOURCE == "push"
# exists:
# - '{dockerfile,dockerfile.j2}'
# changes:
# paths:
# - '{dockerfile,dockerfile.j2,includes/**/*}'
# compare_to: 'development'
# when: always
# - if: $CI_COMMIT_TAG
# exists:
# - '{dockerfile,dockerfile.j2}'
# when: always
# - if: # condition_dev_branch_push
# (
# $CI_COMMIT_BRANCH == "development"
# ||
# $CI_COMMIT_BRANCH == "master"
# )
# &&
# $CI_PIPELINE_SOURCE == "push"
# exists:
# - '{dockerfile,dockerfile.j2}'
# allow_failure: true
# when: on_success
# - when: never
# .gitlab_release:
# stage: release
# image: registry.gitlab.com/gitlab-org/release-cli:latest
# before_script:
# - if [ "0$JOB_ROOT_DIR" == "0" ]; then ROOT_DIR=gitlab-ci; else ROOT_DIR=$JOB_ROOT_DIR ; fi
# - echo "[DEBUG] ROOT_DIR[$ROOT_DIR]"
# - mkdir -p "$CI_PROJECT_DIR/artifacts/$CI_JOB_STAGE/$CI_JOB_NAME"
# - mkdir -p "$CI_PROJECT_DIR/artifacts/$CI_JOB_STAGE/tests"
# - apk update
# - apk add git curl
# - apk add --update --no-cache python3 && ln -sf python3 /usr/bin/python
# - python -m ensurepip && ln -sf pip3 /usr/bin/pip
# - pip install --upgrade pip
# - pip install -r $ROOT_DIR/gitlab_release/requirements.txt
# # - pip install $ROOT_DIR/gitlab_release/python-module/cz_nfc/.
# - pip install commitizen --force
# - 'CLONE_URL="https://gitlab-ci-token:$GIT_COMMIT_TOKEN@gitlab.com/$CI_PROJECT_PATH.git"'
# - echo "[DEBUG] CLONE_URL[$CLONE_URL]"
# - git clone -b development $CLONE_URL repo
# - cd repo
# - git branch
# - git config --global user.email "helpdesk@nofusscomputing.com"
# - git config --global user.name "nfc_bot"
# - git push --set-upstream origin development
# - RELEASE_VERSION_CURRENT=$(cz version --project)
# script:
# - if [ "$CI_COMMIT_BRANCH" == "development" ] ; then RELEASE_CHANGELOG=$(cz bump --changelog --changelog-to-stdout --prerelease beta); else RELEASE_CHANGELOG=$(cz bump --changelog --changelog-to-stdout); fi
# - RELEASE_VERSION_NEW=$(cz version --project)
# - RELEASE_TAG=$RELEASE_VERSION_NEW
# - echo "[DEBUG] RELEASE_VERSION_CURRENT[$RELEASE_VERSION_CURRENT]"
# - echo "[DEBUG] RELEASE_CHANGELOG[$RELEASE_CHANGELOG]"
# - echo "[DEBUG] RELEASE_VERSION_NEW[$RELEASE_VERSION_NEW]"
# - echo "[DEBUG] RELEASE_TAG[$RELEASE_TAG]"
# - RELEASE_TAG_SHA1=$(git log -n1 --format=format:"%H")
# - echo "[DEBUG] RELEASE_TAG_SHA1[$RELEASE_TAG_SHA1]"
# - |
# if [ "0$RELEASE_VERSION_CURRENT" == "0$RELEASE_VERSION_NEW" ]; then
# echo "[DEBUG] not running extra actions, no new version";
# else
# echo "[DEBUG] Creating new Version Label";
# echo "----------------------------";
# echo ${MY_COMMAND};
# echo "----------------------------";
# cat ${MY_COMMAND};
# echo "----------------------------";
# ${MY_COMMAND};
# echo "----------------------------";
# fi
# - if [ "0$RELEASE_VERSION_CURRENT" == "0$RELEASE_VERSION_NEW" ]; then echo "[DEBUG] No tag to delete, version was not bumped"; else git tag -d $RELEASE_TAG; fi
# - if [ "0$RELEASE_VERSION_CURRENT" == "0$RELEASE_VERSION_NEW" ]; then echo "[DEBUG] No push will be conducted, version was not bumped"; else git push; fi
# - if [ "0$RELEASE_VERSION_CURRENT" == "0$RELEASE_VERSION_NEW" ]; then echo "[DEBUG] No release will be created, version was not bumped"; else release-cli create --name "Release $RELEASE_TAG" --tag-name "$RELEASE_TAG" --tag-message "$RELEASE_CHANGELOG" --ref "$RELEASE_TAG_SHA1" --description "$RELEASE_CHANGELOG"; fi
# - if [ "$CI_COMMIT_BRANCH" == "master" ] ; then git checkout master; fi
# - if [ "$CI_COMMIT_BRANCH" == "master" ] ; then git push --set-upstream origin master; fi
# - if [ "$CI_COMMIT_BRANCH" == "master" ] ; then git merge --no-ff development; fi
# - if [ "$CI_COMMIT_BRANCH" == "master" ] ; then git push origin master; fi
# after_script:
# - rm -Rf repo
# rules:
# - if: '$JOB_STOP_GITLAB_RELEASE'
# when: never
# - if: "$CI_COMMIT_AUTHOR =='nfc_bot <helpdesk@nofusscomputing.com>'"
# when: never
# - if: # condition_master_branch_push
# $CI_COMMIT_BRANCH == "master" &&
# $CI_PIPELINE_SOURCE == "push"
# allow_failure: false
# when: on_success
# - if: # condition_dev_branch_push
# $CI_COMMIT_BRANCH == "development" &&
# $CI_PIPELINE_SOURCE == "push"
# when: manual
# allow_failure: true
# # for testing
# # - if: '$CI_COMMIT_BRANCH != "master"'
# # when: always
# # allow_failure: true
# - when: never
# #
# # Release
# #
# Gitlab Release:
# extends:
# - .gitlab_release
# Docker.Hub.Branch.Publish:
# extends: .publish-docker-hub
# needs: [ "Docker Container" ]
# resource_group: build
# rules: # rules manually synced from docker/publish.gitlab-ci.yaml removing git tag
# # - if: # condition_master_branch_push
# # $CI_COMMIT_BRANCH == "master" &&
# # $CI_PIPELINE_SOURCE == "push"
# # exists:
# # - '{dockerfile,dockerfile.j2}'
# # when: always
# - if:
# $CI_COMMIT_AUTHOR =='nfc_bot <helpdesk@nofusscomputing.com>'
# &&
# $CI_COMMIT_BRANCH == "development"
# when: never
# - if: $CI_COMMIT_TAG
# exists:
# - '{dockerfile,dockerfile.j2}'
# when: always
# - if: # condition_dev_branch_push
# $CI_COMMIT_BRANCH == "development" &&
# $CI_PIPELINE_SOURCE == "push"
# exists:
# - '{dockerfile,dockerfile.j2}'
# allow_failure: true
# when: on_success
# - when: never
# Github (Push --mirror):
# extends:
# - .git_push_mirror
# needs: []
# rules:
# - if: '$JOB_STOP_GIT_PUSH_MIRROR'
# when: never
# - if: $GIT_SYNC_URL == null
# when: never
# - if: # condition_master_or_dev_push
# $CI_COMMIT_BRANCH
# &&
# $CI_PIPELINE_SOURCE == "push"
# when: always
# - when: never
Website.Submodule.Deploy:

View File

@ -0,0 +1,7 @@
#!/bin/sh
# Create Version label wtihn repo
curl \
--data "name=v${RELEASE_TAG}&color=#eee600&description=Version%20that%20is%20affected" \
--header "PRIVATE-TOKEN: $GIT_COMMIT_TOKEN" \
"https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}/labels"

View File

@ -0,0 +1,37 @@
### :books: Summary
<!-- your summary here emojis ref: https://github.com/yodamad/gitlab-emoji -->
### :link: Links / References
<!--
using a list as any links to other references or links as required. if relevent, describe the link/reference
Include any issues or related merge requests. Note: dependent MR's also to be added to "Merge request dependencies"
-->
### :construction_worker: Tasks
- [ ] Add your tasks here if required (delete)
<!-- dont remove tasks below strike through including the checkbox by enclosing in double tidle '~~' -->
- [ ] Contains ~"breaking-change" Any Breaking change(s)?
_Breaking Change must also be notated in the commit that introduces it and in [Conventional Commit Format](https://www.conventionalcommits.org/en/v1.0.0/)._
- [ ] Release notes updated
- [ ] ~Documentation Documentation written
_All features to be documented within the correct section(s). Administration, Development and/or User_
- [ ] Milestone assigned
- [ ] [Unit Test(s) Written](https://nofusscomputing.com/projects/centurion_erp/development/testing/)
_ensure test coverage delta is not less than zero_

View File

@ -1,29 +1,21 @@
Unit:
.pytest:
stage: test
image: python:3.11-alpine3.19
needs: []
script:
before_script:
- pip install -r requirements.txt
- pip install -r requirements_test.txt
- cd app
- pytest --cov --cov-report term --cov-report xml:../artifacts/coverage.xml --cov-report html:../artifacts/coverage/ --junit-xml=../artifacts/unit.JUnit.xml
coverage: '/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/'
artifacts:
expire_in: "30 days"
when: always
reports:
coverage_report:
coverage_format: cobertura
path: artifacts/coverage.xml
junit:
- artifacts/*.JUnit.xml
paths:
- artifacts/
environment:
name: PyTest Coverage Report
url: https://nofusscomputing.gitlab.io/-/projects/django_template/-/jobs/${CI_JOB_ID}/artifacts/artifacts/coverage/index.html
rules:
- if: # Occur on merge
@ -38,3 +30,52 @@ Unit:
- when: never
Unit:
extends: .pytest
script:
- pytest --cov --cov-report term --cov-report xml:../artifacts/coverage.xml --cov-report html:../artifacts/coverage/ --junit-xml=../artifacts/unit.JUnit.xml **/tests/unit
coverage: '/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/'
artifacts:
expire_in: "30 days"
when: always
reports:
coverage_report:
coverage_format: cobertura
path: artifacts/coverage.xml
junit:
- artifacts/*.JUnit.xml
paths:
- artifacts/
environment:
name: Unit Test Coverage Report
url: https://nofusscomputing.gitlab.io/-/projects/centurion_erp/-/jobs/${CI_JOB_ID}/artifacts/artifacts/coverage/index.html
UI:
extends: .pytest
script:
- apk update
- apk add chromium-chromedriver
- pytest --junit-xml=../artifacts/ui.JUnit.xml **/tests/ui
artifacts:
expire_in: "30 days"
when: always
reports:
junit:
- artifacts/*.JUnit.xml
paths:
- artifacts/
rules:
- if: # Occur on merge
$CI_COMMIT_BRANCH
&&
(
$CI_PIPELINE_SOURCE == "push"
||
$CI_PIPELINE_SOURCE == "web"
)
allow_failure: true
when: always
- when: never

17
.vscode/launch.json vendored
View File

@ -15,6 +15,23 @@
"django": true,
"autoStartBrowser": false,
"program": "${workspaceFolder}/app/manage.py"
},
{
"name": "Debug: Celery",
"type": "python",
"request": "launch",
"module": "celery",
"console": "integratedTerminal",
"args": [
"-A",
"app",
"worker",
"-l",
"INFO",
"-n",
"debug-itsm@%h"
],
"cwd": "${workspaceFolder}/app"
}
]
}

10
.vscode/settings.json vendored
View File

@ -5,8 +5,16 @@
"!python"
],
"python.testing.pytestArgs": [
// "-v",
// "--cov",
// "--cov-report xml",
"app"
],
"python.testing.unittestEnabled": true,
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"testing.coverageToolbarEnabled": true,
"cSpell.words": [
"ITSM"
],
"cSpell.language": "en-AU",
}

View File

@ -1,284 +1,526 @@
## 1.0.0-b12 (2024-08-10)
### Fix
- **api**: ensure org mixin is inherited by software view
- **base**: correct project links to github
## 1.0.0-b11 (2024-08-10)
## 1.0.0-b10 (2024-08-09)
## 1.0.0-b9 (2024-08-09)
## 1.0.0-b8 (2024-08-09)
## 1.0.0-b7 (2024-08-09)
## 1.0.0-b6 (2024-08-09)
## 1.0.0-b5 (2024-07-31)
### Feat
- **api**: Add device config groups to devices
- **api**: Ability to fetch configgroups from api along with config
### Fix
- **api**: Ensure device groups is read only
## 1.0.0-b4 (2024-07-29)
### Feat
- **swagger**: remove `{format}` suffixed doc entries
### Fix
- **api**: cleanup team post/get
- **api**: confirm HTTP method is allowed before permission check
- **api**: Ensure that organizations can't be created via the API
- **access**: Team model class inheritance order corrected
## 1.0.0-b3 (2024-07-21)
### Fix
- **itam**: Limit os version count to devices user has access to
## 1.0.0-b2 (2024-07-19)
### Fix
- **itam**: only show os version once
## 1.0.0-b1 (2024-07-19)
### Fix
- **itam**: ensure installed operating system count is limited to users organizations
- **itam**: ensure installed software count is limited to users organizations
## 1.0.0-a4 (2024-07-18)
### Feat
- **api**: When processing uploaded inventory and name does not match, update name to one within inventory file
- **config_management**: Group name to be entire breadcrumb
## 1.0.0-a3 (2024-07-18)
### Feat
- **config_management**: Prevent a config group from being able to change organization
- **itam**: On device organization change remove config groups
### Fix
- **config_management**: dont attempt to do action during save if group being created
- **itam**: remove org filter for device so that user can see installations
- **itam**: remove org filter for operating systems so that user can see installations
- **itam**: remove org filter for software so that user can see installations
- **itam**: Device related items should not be global.
- **itam**: When changing device organization move related items too.
## 1.0.0-a2 (2024-07-17)
### Feat
- **api**: Inventory matching of device second by uuid
- **api**: Inventory matching of device first by serial number
- **base**: show warning bar if the user has not set a default organization
### Fix
- **base**: dont show user warning bar for non-authenticated user
- **api**: correct inventory operating system selection by name
- **api**: correct inventory operating system and it's linking to device
- **api**: correct inventory device search to be case insensitive
## 1.0.0-a1 (2024-07-16)
### BREAKING CHANGE
- squashed DB migrations in preparation for v1.0 release.
### Feat
- Administratively set global items org/is_global field now read-only
- **access**: Add multi-tennant manager
### Fix
- **core**: migrate manufacturer to use new form/view logic
- **settings**: correct the permission to view manufacturers
- **access**: Correct team form fields
- **config_management**: don't exclude parent from field, only self
### Refactor
- Squash database migrations
## 0.7.0 (2024-07-14)
### Feat
- **core**: Filter every form field if associated with an organization to users organizations only
- **core**: add var `template_name` to common view template for all views that require it
- **core**: add Display view to common forms abstract class
- **navigation**: always show every menu for super admin
- **core**: only display navigation menu item if use can view model
- **django**: update 5.0.6 -> 5.0.7
- **core**: add common forms abstract class
- **core**: add common views abstract class
- add postgreSQL database support
- **ui**: add config groups navigation icon
- **ui**: add some navigation icons
- **itam**: update inventory status icon
- **itam**: ensure device software pagination links keep interface on software tab
- **access**: enable non-organization django permission checks
- **settings**: Add celery task results index and view page
- **base**: Add background worker
- **itam**: Update Serial Number from inventory if present and Serial Number not set
- **itam**: Update UUID from inventory if present and UUID not set
### Fix
- **config_management**: Don't allow a config group to assign itself as its parent
- **config_management**: correct permission for deleting a host from config group
- **config_management**: use parent group details to work out permissions when adding a host
- **config_management**: use parent group details to work out permissions
- **itam**: Add missing permissions to software categories index view
- **itam**: Add missing permissions to device types index view
- **itam**: Add missing permissions to device model index view
- **settings**: Add missing permissions to app settings view
- **itam**: Add missing permissions to software index view
- **itam**: Add missing permissions to operating system index view
- **itam**: Add missing permissions to device index view
- **config_management**: Add missing permissions to group views
- **navigation**: always show settings menu entry
- **itam**: cater for fields that are prefixed
- **itam**: Ability to view software category
- **itam**: correct view permission
- **access**: When adding a new team to org ensure parent model is fetched
- **access**: enable org manager to view orgs
- **settings**: restrict user visible organizations to ones they are part of
- **access**: enable org manager to view orgs
- **access**: fetch object if method exists
- **docs**: update docs link to new path
- **access**: correctly set team user parent model to team
- **access**: fallback to django permissions if org permissions check is false
- **access**: Correct logic so that org managers can see orgs they manage
- **base**: add missing content_title to context
- **access**: Enable Organization Manager to view organisations they are assigned to
- **api**: correct logic for adding inventory UUID and serial number to device
- **ui**: navigation alignment and software icon
- **ui**: display organization manager name instead of ID
- **access**: ensure name param exists before attempting to access
- **itam**: dont show none/nil for device fields containing no value
- **itam**: show device model name instead of ID
- **api**: Ensure if serial number from inventory is `null` that it's not used
- **api**: ensure checked uuid and serial number is used for updating
- **itam**: only remove device software when not found during inventory upload
- **itam**: only update software version if different
- **itam**: correct device software pagination
### Refactor
- adjust views missing add/change form to now use forms
- add navigation menu expand arrows
- migrate views to use new abstract model view classes
- migrate forms to use new abstract model form class
- **access**: Rename Team Button "new user" -> "Assign User"
- **access**: model pk and name not required context for adding a device
- rename field "model notes" -> "Notes"
- remove settings model
- **ui**: increase indentation to sub-menu items
- **itam**: rename old inventory status icon for use with security
- **api**: migrate inventory processing to background worker
- **itam**: only perform actions on device inventory if DB matches inventory item
## 0.6.0 (2024-06-30)
### Feat
- **api**: API token authentication
- **api**: abilty for user to create/delete api token
- **api**: create token model
### Fix
- **user_token**: conduct user check on token view access
- **itam**: use same form for edit and add
- **itam**: dont add field inventorydate if adding new item
- **api**: inventory upload requires sanitization
### Refactor
- **settings**: use seperate change/view views
- **settings**: use form for user settings
- **tests**: move unit tests to unit test sub-directory
## 0.5.0 (2024-06-17)
### Feat
- **access**: add notes field to organization
- **access**: add organization manger
- **config_management**: Use breadcrumbs for child group name display
- **config_management**: ability to add host to global group
- **itam**: add a status of "bad" for devices
- **itam**: paginate device software tab
- **itam**: status of device visible on device index page
- **core**: add skeleton http browser
- **core**: Add a notes field to manufacturer/ publisher
- **itam**: Add a notes field to software category
- **itam**: Add a notes field to device types
- **itam**: Add a notes field to device models
- **itam**: Add a notes field to software
- **itam**: Add a notes field to operating system
- **itam**: Add a notes field to devices
- **access**: Add a notes field to teams
- **base**: Add a notes field to `TenancyObjetcs` class
- **settings**: add docs icon to application settings page
- **itam**: add docs icon to software page
- **itam**: add docs icon to operating system page
- **itam**: add docs icon to devices page
- **config_management**: add docs icon to config groups page
- **base**: add dynamic docs icon
- **models**: add property parent_object to models that have a parent
- **config_management**: add config group software to group history
- **itam**: render group software config within device rendered config
- **config_management**: assign software action to config group
- add configuration value 'SESSION_COOKIE_AGE'
- remove development SECRET_KEY and enforce checking for user configured one
- **base**: build CSRF trusted origins from configuration
- **base**: Enforceable SSO ONLY
- **base**: configurable SSO
### Fix
- **itam**: remove requirement that user needs change device to add notes
- **core**: dont attempt to access parent_object if 'None' during history save
- **config_management**: Add missing parent item getter to model
- **core**: overridden save within SaveHistory to use default attributes
- **access**: overridden save to use default attributes
- **core**: on object delete remove history entries
- **api**: ensure proper permission checking
- dont throw an exception during settings load for an item django already checks
- **core**: Add overrides for delete so delete history saved for items with parent model
- **config_management**: correct delete success url
- **base**: remove social auth from nav menu
- **access**: add a team user permissions to use team organization
### Refactor
- **access**: relocate permission check to own function
- **itam**: move device os tab to details tab
- **itam**: add device change form and adjust view to be non-form
- **itam**: migrate device vie to use manual entered fields in two columns
- **access**: migrate team users view to use forms
- **access**: migrate teams view to use forms
- **access**: migrate organization view to use form
- **base**: cleanup form and prettyfy
- **config_management**: relocate groups views to own directory
- login to use base template
- adjust template block names
## 0.4.0 (2024-06-05)
### Bug Fixes
### Feat
- **itam**: [dd0c13a6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/dd0c13a65f4cc55e2047f1b654dd228147eac183) - ensure device type saves history [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) ]
- **core**: [4cafa34d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/4cafa34d69332995307faf29eff42efd81e569d6) - correct history view permissions [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) [#48](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/48) [#15](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/15) ]
- **config_management**: [2c1bbbfc](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2c1bbbfc15babdc22d67285dae1c18a4b6f3cc96) - set config dict keys to be valid ansible variables [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) [#47](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/47) ]
- **itam**: [dd30a57a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/dd30a57a9db7f5d6aa318651d9e252dae7f73b58) - correct logic for device add dynamic success url [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) ]
- **itam**: [18e84db6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/18e84db63c992c142f31f44fcc650561a16045fe) - correct config group link for device [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) ]
- **config_management**: [c9098f5d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c9098f5d2fe1817d7d33b7ffd30aeffa4077cdd2) - correct model permissions [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **config_management**: [d422f2fe](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/d422f2feee4a5013ced153c43e0858098890d90b) - add config management to navigation [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **ui**: [8061b7c8](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8061b7c8e29b0f1ad12969a3d4e6a3e27cd85b2d) - remove api entries from navigation [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) ]
- **api**: [f41282d0](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/f41282d08b6a417a12d22268a67b27425bed2361) - check for org must by by type None [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **api**: [8dfb996b](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8dfb996b24c26f3697a8d3c787faab4f190953eb) - correct software permissions [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **api**: [95dc9794](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/95dc979419c7cb0f6bfeff71169201149c9341fb) - corrct device permissions [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **api**: [09cc1db6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/09cc1db665af30c32d043644806f65e56f80c510) - permissions for teams [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **api**: [e7c535c4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e7c535c48d73f7f3dbde6a0c191afb134ba2dd72) - correct reverse url lookup to use NS API [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **api**: [e9cd111a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e9cd111af6299dee24b7c917726c54f7e7be8fe2) - permissions for organization [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **database**: add mysql support
- **api**: move invneotry api endpoint to '/api/device/inventory'
- **core**: support more history types
- **core**: function to fetch history entry item
- **config_management**: Add button to groups ui for adding child group
- **access**: throw error if no organization added
- **itam**: add delete button to config group within ui
- **itam**: Config groups rendered configuration now part of devices rendered configuration
- **config_management**: Ability to delete a host from a config group
- **config_management**: Ability to add a host to a config group
- **config_management**: ensure config doesn't use reserved config keys
- **config_management**: Config groups rendered config
- **config_management**: add configuration groups
- **api**: add swagger ui for documentation
- **api**: filter software to users organizations
- **api**: filter devices to users organizations
- **api**: add org team view page
- **api**: configure team permissions
### Code Refactor
### Fix
- **access**: [6650434c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6650434c63a7fc620f98ed79b32fe4bbd52b1ada) - cache object so it doesnt have to be called multiple times [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) ]
- **config_management**: [58738971](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/5873897184e906ae1fd3419a018441de78c5741d) - move groups to nav menu [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **api**: [e257c114](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e257c1148808d6159bd6c8396a22168aa88c3b2f) - migrate devices and software to viewsets [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **api**: [33b1a6c9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/33b1a6c91dc6d7f47738b96f7ce08b616e0749bb) - move permission check to mixin [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **access**: [5f3b48ea](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/5f3b48ea982588e39137a3e695a2bbe65fd4c0a2) - add team option to org permission check [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) ]
- **itam**: ensure device type saves history
- **core**: correct history view permissions
- **config_management**: set config dict keys to be valid ansible variables
- **itam**: correct logic for device add dynamic success url
- **itam**: correct config group link for device
- **config_management**: correct model permissions
- **config_management**: add config management to navigation
- **ui**: remove api entries from navigation
- **api**: check for org must by by type None
- **api**: correct software permissions
- **api**: corrct device permissions
- **api**: permissions for teams
- **api**: correct reverse url lookup to use NS API
- **api**: permissions for organization
### Continious Integration
### Refactor
- [8e338c7c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8e338c7ca02057728089a8dabceae4348d3cb04a) - add pytest coverage report as environment [ [!15](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/15) [#37](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/37) ]
- [9b811ede](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9b811ede266631a297bf84851b68f8b11a5d9f39) - run container build/publish on git tag [ [!15](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/15) ]
### Documentaton / Guides
- **config_management**: [0a17329a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0a17329a710e7f94ea3054857975467236130d1c) - notate future feature [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- [0d18e974](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0d18e974dda10490f0b2b95f416fd8af8351a58a) - correct liniting errors [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) ]
- **config_management**: [62e605d4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/62e605d4172c114d9d14a6aebf2bc122cee21866) - document module [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **api**: [fbdbede4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/fbdbede4295005ab861b1ef3c0fe552c516b8738) - add team/org paths [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) [#41](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/41) ]
### Features
- **database**: [adeffff4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/adeffff42c666243ce7e3b84ca2de3140bb350ca) - add mysql support [ [!19](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/19) [#16](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/16) ]
- **api**: [c0173d6f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c0173d6feb22e1dae42d596c8e916d3083e63c4d) - move invneotry api endpoint to '/api/device/inventory' [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) ]
- **core**: [eb6ae13c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/eb6ae13c58d45240c0ad99fcde2bc1c3fbaef035) - support more history types [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) ]
- **core**: [46bdd488](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/46bdd488ecedde9aeac97947caf96a5efb8c437f) - function to fetch history entry item [ [!18](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/18) [#48](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/48) [#15](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/15) ]
- **config_management**: [55f0db22](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/55f0db2217e247d7f76edd1c2e81bfd9b7570698) - Add button to groups ui for adding child group [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **access**: [7fe12603](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7fe12603080d649bedb5d29f7084083271c9c982) - throw error if no organization added [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) ]
- **itam**: [df27a7df](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/df27a7dfd365faed6ee1194433e0d8da9499600b) - add delete button to config group within ui [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **itam**: [5cb155e0](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/5cb155e01f72680c8249690be885f386679d458a) - Config groups rendered configuration now part of devices rendered configuration [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **config_management**: [39bfbd25](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/39bfbd25cbc2f936f54600d508cfd8c67a4e023b) - Ability to delete a host from a config group [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **config_management**: [fff51e38](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/fff51e38d2503bf4741b3734bfffad6d537fd862) - Ability to add a host to a config group [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **config_management**: [746b7ac7](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/746b7ac747fbb39657912225135dc1d4d4178c8c) - ensure config doesn't use reserved config keys [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **config_management**: [a7d195df](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/a7d195dfcbd38d14e04b1f45faeba09baca21696) - Config groups rendered config [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **config_management**: [fdeae217](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/fdeae217fa8883031b67df12c1f0f8b06ff92bbd) - add configuration groups [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#42](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/42) ]
- **api**: [3f68d67b](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/3f68d67ba581e11cfe8ec88d2a1cdb7c6ba63e46) - add swagger ui for documentation [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) ]
- **api**: [4151e0af](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/4151e0afdc6cbc9a253f41441ab0074fe947db01) - filter software to users organizations [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#45](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/45) ]
- **api**: [89a5e0f4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/89a5e0f4cc1336e042f242dfeef9a88c37b1d9f4) - filter devices to users organizations [ [!17](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/17) [#45](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/45) ]
- **api**: [3fef74e7](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/3fef74e7000bcd7e90a15d40e68f667c4a882114) - add org team view page [ [!16](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/16) [#41](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/41) ]
- **api**: [c0a09d5d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c0a09d5d505dedc5562be08844ccd3e7fc5b589a) - configure team permissions [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) [#36](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/36) ]
- **access**: cache object so it doesnt have to be called multiple times
- **config_management**: move groups to nav menu
- **api**: migrate devices and software to viewsets
- **api**: move permission check to mixin
- **access**: add team option to org permission check
## 0.3.0 (2024-05-29)
### Bug Fixes
### Feat
- **settings**: [d379205b](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/d379205bffcc808031e8227d08220ef5d6c4e130) - Add correct permissions for team user delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [ebf4cb7a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/ebf4cb7a5daf6fcf2f39f912203ac9ed31d7fca6) - Add correct permissions for team user view/change [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [b5669c83](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b5669c83869b38463f7c99008eb9e2b29b59faf2) - Add correct permissions for team view/change [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [58e688e0](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/58e688e0a5f44a63d1526b1a73f6ce63d67d3e07) - Add correct permissions for team add [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [e3c2f712](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e3c2f712c19bd1040c311891bd766311e302be6f) - Add correct permissions for team delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [0abcb462](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0abcb4628e5c5fac3d7997b457df7589772b929f) - correct back link within team view [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [b9a2d2ac](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b9a2d2ac59d8e31c99a268375b51d866186dc8bf) - correct url name to be within naming conventions [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [8bfc952f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8bfc952f2eaac67bb1c40a40fdfd8046b8580eed) - Add correct permissions for manufacturer / publisher delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [6e6bd107](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6e6bd1070e5c0b63f8b97c6617098b21823f609c) - Add correct permissions for manufacturer / publisher add [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [42fd648e](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/42fd648e4c6817af88248343312a1232bbfa22d3) - Add correct permissions for manufacturer / publisher view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [9893e5f9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9893e5f95270ebc3476a5c7c070080399304afab) - Add correct permissions for software category delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [e35a2300](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e35a2300e261586be5aa209e5cc70ad190d8d00c) - Add correct permissions for software category add [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [0aa78a4c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0aa78a4c514faaddeb7501c1824ccdedc896c39c) - Add correct permissions for software category view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [84d895c2](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/84d895c214c8109b70b3bb764c26bcc488e0a85d) - Add correct permissions for device type delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [cba28108](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/cba28108e04f3e9007f904c8038fa07edbf5d0ea) - Add correct permissions for device type add [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [18339547](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/18339547ba8450d7ba25872085a7efda39049a87) - Add correct permissions for device type view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [d2e9e107](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/d2e9e1070e72e0aaf9dacb2cfff5d4d5c0bfb679) - Add correct permissions for device model delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [6880c5e9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6880c5e90b8dbd8969b00b6571bb38f004f2db13) - Add correct permissions for device model add [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **settings**: [608a3838](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/608a38384db6415162d155b951abad743e03a10d) - Add correct permissions for device model view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [cb7987f8](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/cb7987f841626687c8ec5b1ad17df3fcf2698257) - Add correct permissions for organization view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [98885a32](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/98885a32e71463403f1bb9c535cb6cab39d09733) - use established view naming [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [6b37c952](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6b37c952f82367e5178ed926757e47c07436ebd5) - Add correct permissions for operating system delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [d81d1ba3](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/d81d1ba32a51a592193f013b0a2eb45178e9fa49) - Add correct permissions for operating system add [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [01c6cd4b](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/01c6cd4bdf3a167179be4a7e07ed59751ccf44ed) - Add correct permissions for operating system view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [88058234](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/880582340561060a8466c619b191d01cff261f65) - Add correct permissions for software delete [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [7dd2634f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7dd2634facf6708b5aef5c22413b2fb7f5b5da44) - Add correct permissions for software add [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [b1cfb9fa](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b1cfb9fa59d009a0dfba6a64184264166ace5a11) - for non-admin user use correct order by fields for software view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [550e6f40](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/550e6f40801071b8c5222e809d9e922de0cb0c74) - Add correct permissions for software view/update [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [94116fa1](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/94116fa173c8ed05d84d84aa09467d10fe02cd4c) - ensure permission_required parameter for view is a list [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **core**: [0e726684](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0e7266845402d07d0cd289f268ae22e4a977362a) - dont save history when no user information available [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [37ceffcb](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/37ceffcb3bd196557d3fe0cc90b7c6722113e092) - during organization permission check, check the entire list of permissions [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **core**: [c656f5bc](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c656f5bce597fc333a6549a2159b847a7338de29) - dont save history for anonymous user [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [6cb69c62](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6cb69c627ff54eb1b5bfa11da2b60d4bb0b45b19) - during permission check use post request params for an add action [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **user**: [80c3af32](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/80c3af32d533995679854d7a20984c8dd4904fd0) - on new-user signal create settings row if not exist [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [9d6bd6db](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9d6bd6db83c56b8904d86829ef1134d689c5fb3e) - ensure only user with change permission can change a device [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **user**: [2750750a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2750750a0c3f384ab384d409d90f00afc44cc619) - if user settings row doesn't exist on access create [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [664ad0ec](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/664ad0ec7d220fd20aea1ad405b27546ac62b57f) - adding/deleting team group actions moved to model save/delete method override [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **api**: [1c9d8b1c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/1c9d8b1c7e72a15e6186aa6d95a30e4ba3fbfac4) - add teams and permissions to org and teams respectively [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **ui**: [a3716b01](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/a3716b01584cb7842b782b0e9dd986c5542d8b6c) - correct repo url used [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **api**: [752770ec](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/752770ec32b6330ddd6060dc71dcbf3e60aacd83) - device inventory date set to read only [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **software**: [46af675f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/46af675f3c87d975a8dab3da70090fa3ab3f7033) - ensure management command query correct for migration [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) [#32](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/32) ]
- **device**: [7f4a036a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7f4a036a32630599ef95bbe801d24e6204c61fcf) - OS form trying to add last inventory date when empty [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) ]
- [249b9cba](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/249b9cbab9e8f917e0e1ecd97fbcc5300c1c832f) - add static files path to urls [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) ]
- **inventory**: [f5d5529c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/f5d5529c173d64ef839e9db638600e963ec6a0aa) - Dont select device_type, use 'null' [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) [#17](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/17) ]
- **base**: [d2dba2f7](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/d2dba2f7b8b38370da0dae18cab752789ac2e5e8) - show "content_title - SITE_TITLE" as site title [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) [#18](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/18) ]
- **device**: [2689c35d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2689c35db36455982e57b08fd418ab2244280af0) - Read Only field set as required=false [ [!9](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/9) ]
- [7ae7ffae](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7ae7ffaef46cc27a2bae9acdcfa70dff80a05f7a) - correct typo in notes templates [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#7](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/7) ]
- **ui**: [5273b58a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/5273b58afb383843de6da3faca552fe143fff8eb) - Ensure navigation menu entry highlighted for sub items [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) ]
- **access**: during organization permission check, check to ensure user is logged on
- **history**: always create an entry even if user=none
- **itam**: device uuid must be unique
- **itam**: device serial number must be unique
- **setting**: Enable super admin to set ALL manufacturer/publishers as global
- **setting**: Enable super admin to set ALL device types as global
- **setting**: Enable super admin to set ALL device models as global
- **setting**: Enable super admin to set ALL software categories as global
- **UI**: show build details with page footer
- **software**: Add output to stdout to show what is and has occurred
- **base**: Add delete icon to content header
- **itam**: Populate initial organization value from user default organization for software category creation
- **itam**: Populate initial organization value from user default organization for device type creation
- **itam**: Populate initial organization value from user default organization for device model creation
- **api**: Populate initial organization value from user default organization inventory
- **itam**: Populate initial organization value from user default organization for Software creation
- **itam**: Populate initial organization value from user default organization for operating system creation
- **device**: Populate initial organization value from user default organization
- Add management command software
- **setting**: Enable super admin to set ALL software as global
- **user**: Add user settings panel
- **itam**: Add publisher to software
- **itam**: Add publisher to operating system
- **itam**: Add device model
- **core**: Add manufacturers
- **settings**: add dummy model for permissions
- **settings**: new module for whole of application settings/globals
- **access**: Save changes to history for organization and teams
- **software**: Save changes to history
- **operating_system**: Save changes to history
- **device**: Save changes to history
- **core**: history model for saving model history
- **itam**: Ability to add notes to software
- **itam**: Ability to add notes to operating systems
- **itam**: Ability to add notes on devices
- **core**: notes model added to core
- **device**: Record inventory date and show as part of details
- **ui**: Show inventory details if they exist
- **api**: API accept computer inventory
### Code Refactor
### Fix
- **access**: [dd0eaae6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/dd0eaae6b3c112bf9746b7ab37b996ba693650fc) - add to models a get_organization function [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **access**: [e34d2998](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e34d29987e128190cefd1af9cd1c504123c59170) - remove change view [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [668e871e](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/668e871e4fd52abb20426b8dafa988c423d3d3a7) - relocation item delete from list to inside device [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#23](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/23) ]
- **context_processor**: [900412b3](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/900412b31706fbba0040139dd5a04b76aeb32af2) - relocate as base [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) ]
- **itam**: [23e661ce](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/23e661cef04627912363492955b004920748edb6) - software index does not require created and modified date [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) ]
- **organizations**: [a6a0da72](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/a6a0da72b223ca64b6e7361db6e250ebbceedddb) - set org field to null if not set [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) ]
- **itam**: [66e8b290](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/66e8b290146cb241455792cb70d5de184b59819a) - move software categories to settings app [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) ]
- **itam**: [c83b8836](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c83b8836730babd497b185c3ccf28176cd298ba7) - move device types to settings app [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) ]
- **template**: [191244ed](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/191244ed40f8feacf8885f0eb9fff5b32ef91252) - content_title can be rendered in base [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) ]
- **settings**: Add correct permissions for team user delete
- **settings**: Add correct permissions for team user view/change
- **settings**: Add correct permissions for team view/change
- **settings**: Add correct permissions for team add
- **settings**: Add correct permissions for team delete
- **access**: correct back link within team view
- **access**: correct url name to be within naming conventions
- **settings**: Add correct permissions for manufacturer / publisher delete
- **settings**: Add correct permissions for manufacturer / publisher add
- **settings**: Add correct permissions for manufacturer / publisher view/update
- **settings**: Add correct permissions for software category delete
- **settings**: Add correct permissions for software category add
- **settings**: Add correct permissions for software category view/update
- **settings**: Add correct permissions for device type delete
- **settings**: Add correct permissions for device type add
- **settings**: Add correct permissions for device type view/update
- **settings**: Add correct permissions for device model delete
- **settings**: Add correct permissions for device model add
- **settings**: Add correct permissions for device model view/update
- **access**: Add correct permissions for organization view/update
- **access**: use established view naming
- **itam**: Add correct permissions for operating system delete
- **itam**: Add correct permissions for operating system add
- **itam**: Add correct permissions for operating system view/update
- **itam**: Add correct permissions for software delete
- **itam**: Add correct permissions for software add
- **itam**: for non-admin user use correct order by fields for software view/update
- **itam**: Add correct permissions for software view/update
- **itam**: ensure permission_required parameter for view is a list
- **core**: dont save history when no user information available
- **access**: during organization permission check, check the entire list of permissions
- **core**: dont save history for anonymous user
- **access**: during permission check use post request params for an add action
- **user**: on new-user signal create settings row if not exist
- **itam**: ensure only user with change permission can change a device
- **user**: if user settings row doesn't exist on access create
- **access**: adding/deleting team group actions moved to model save/delete method override
- **api**: add teams and permissions to org and teams respectively
- **ui**: correct repo url used
- **api**: device inventory date set to read only
- **software**: ensure management command query correct for migration
- **device**: OS form trying to add last inventory date when empty
- add static files path to urls
- **inventory**: Dont select device_type, use 'null'
- **base**: show "content_title - SITE_TITLE" as site title
- **device**: Read Only field set as required=false
- correct typo in notes templates
- **ui**: Ensure navigation menu entry highlighted for sub items
### Continious Integration
### Refactor
- **docker**: [19d24b54](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/19d24b54a2cb9f4f81692b863260089caed12772) - build on any change [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) ]
- **docker**: [2c81007c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2c81007c0ae73586fdaabe9387cc625486dee8f4) - always build on dev branch [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) ]
### Documentaton / Guides
- [3af254d9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/3af254d9e83093b91200a2b6ef9b6f92975a6ad8) - update software and os [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) [#12](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/12) ]
- **core**: [f7444892](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/f7444892d06bb25c6a7de92ecf0410a2109ae0f5) - Add history docs [ [!9](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/9) [#5](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/5) ]
- **core**: [5dadc3fe](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/5dadc3fe98e3317c83305b73c1f9763617f486a8) - Add details about model notes [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#7](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/7) ]
- [6b5acc0d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6b5acc0d575706d30a41d26f51dfe7d6f7bdf945) - add inventory details [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#2](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/2) ]
### Features
- **access**: [7f7f7197](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7f7f719731ce1214582f69f55544a1059b874a80) - during organization permission check, check to ensure user is logged on [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **history**: [8d786d4d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8d786d4dea2ed3b290a83f90c863bbe46e53cefd) - always create an entry even if user=none [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [353117aa](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/353117aa74f0e0aac3ad687628cc7a21af690f0e) - device uuid must be unique [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **itam**: [c4fe2185](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c4fe218592fe25ebad842e8bb24ce1f2062debaa) - device serial number must be unique [ [!13](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/13) ]
- **setting**: [bf69a301](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/bf69a30163e6bafd0f951dde5fd058a31c327c09) - Enable super admin to set ALL manufacturer/publishers as global [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) ]
- **setting**: [ece6b9e3](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/ece6b9e354a149ff1aa73d147bedcb3c406603c0) - Enable super admin to set ALL device types as global [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) [#31](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/31) ]
- **setting**: [abbda7b4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/abbda7b400d7c06fee5165157d2bf545c00d4bbe) - Enable super admin to set ALL device models as global [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) [#29](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/29) ]
- **setting**: [935e119e](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/935e119e6418d561739fff4e8b1fdbb399588a18) - Enable super admin to set ALL software categories as global [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) [#30](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/30) ]
- **UI**: [da0d3a81](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/da0d3a816d398d45d729ad9bcd5c0f2c625a3469) - show build details with page footer [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) [#25](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/25) ]
- **software**: [51e52e69](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/51e52e69a48fefc792b8556aa20d84652a53afe7) - Add output to stdout to show what is and has occurred [ [!12](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/12) [#32](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/32) ]
- **base**: [b2f7c831](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b2f7c831551469445d091cd176ab6f210ec862e1) - Add delete icon to content header [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#23](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/23) ]
- **itam**: [e66e9b8d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e66e9b8dca740ffe411b74c8f50c53c732acef2f) - Populate initial organization value from user default organization for software category creation [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- **itam**: [4c002bc2](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/4c002bc259062fc4926deda8a943d165496c8a25) - Populate initial organization value from user default organization for device type creation [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- **itam**: [90f95672](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/90f95672aa71c0a5358238f491949fb356503ff3) - Populate initial organization value from user default organization for device model creation [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- **api**: [7f3bf95b](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7f3bf95b4627be434732b1045120e59fcae21cf3) - Populate initial organization value from user default organization inventory [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- **itam**: [9f5e5d25](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9f5e5d25ec574caa0aeec91c5763f7f64c8b11c2) - Populate initial organization value from user default organization for Software creation [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- **itam**: [62c0bb77](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/62c0bb77fe5134669e77b198acc02c28ea073696) - Populate initial organization value from user default organization for operating system creation [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- **device**: [abbd6a49](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/abbd6a49d64fc24eb2c27191b594e8cefdb9042b) - Populate initial organization value from user default organization [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- [395f24f2](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/395f24f22c5418eed99d59659b7c60726c2ade53) - Add management command software [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#27](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/27) ]
- **setting**: [f36400db](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/f36400dbb98d305e1ec54f62493f7f2cff0359b1) - Enable super admin to set ALL software as global [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#27](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/27) ]
- **user**: [ee7977fe](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/ee7977fe4a5e78844e8652c313af49eda901bdad) - Add user settings panel [ [!11](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/11) [#28](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/28) ]
- **itam**: [2fcbb1ea](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2fcbb1ead72cfa294ad26f63688b4344df56b0db) - Add publisher to software [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) [#12](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/12) ]
- **itam**: [53baeb59](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/53baeb59c9e0d0eff681ba36996e47c22bd7afe7) - Add publisher to operating system [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) [#12](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/12) ]
- **itam**: [99a559fe](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/99a559fe6dd8b234cf860c7a44fd65dc178c1bc7) - Add device model [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) [#12](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/12) ]
- **core**: [ef463b84](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/ef463b845d1738a6067c786bf410f5109d832a5c) - Add manufacturers [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) [#12](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/12) ]
- **settings**: [bf0fa3f4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/bf0fa3f41dda11a02d6ae2c9b58a9e21900d2a9f) - add dummy model for permissions [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) ]
- **settings**: [ac233e43](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/ac233e432f7222c59a0bb62a1cd85a6a7770c13c) - new module for whole of application settings/globals [ [!10](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/10) ]
- **access**: [724c52b7](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/724c52b777896600fc8ed5a71bb3e3f6429f9e56) - Save changes to history for organization and teams [ [!9](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/9) [#5](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/5) ]
- **software**: [b5470f2c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b5470f2cefeddac2dd154ef37975902fe511e9f6) - Save changes to history [ [!9](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/9) [#5](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/5) ]
- **operating_system**: [e16a4212](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e16a4212ccd8c7ed04d34a87bbef78a4f5565166) - Save changes to history [ [!9](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/9) [#5](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/5) ]
- **device**: [6cbcd4aa](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6cbcd4aa56441efce29c8dfe2489794716a72e8b) - Save changes to history [ [!9](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/9) [#5](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/5) ]
- **core**: [9b2abeca](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9b2abecac37f9b2ea12a56ad2023afedc6dd78fc) - history model for saving model history [ [!9](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/9) [#5](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/5) ]
- **itam**: [dec29429](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/dec2942996073746f78463b69156e67c8d879b72) - Ability to add notes to software [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#7](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/7) ]
- **itam**: [4d5f229f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/4d5f229fc737606bf272b0ccea6390ad2737dae1) - Ability to add notes to operating systems [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#7](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/7) ]
- **itam**: [725e6b8c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/725e6b8c922e0c1a6fd9d96a0f2581a8aad4a737) - Ability to add notes on devices [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#7](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/7) ]
- **core**: [8e0df948](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8e0df948d5006976981eb2ac3918c38fe74aff14) - notes model added to core [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#7](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/7) ]
- **device**: [fb041f77](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/fb041f77ebb9b9b44b0ebbed955252e22d3ee4dc) - Record inventory date and show as part of details [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#2](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/2) ]
- **ui**: [e93ce07d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/e93ce07d887b3d3151cb6714df27fd5cf9fdcd67) - Show inventory details if they exist [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#2](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/2) ]
- **api**: [c52fd080](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c52fd0802ed2395fa3a62ec41ec0297b0bca373e) - API accept computer inventory [ [!8](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/8) [#2](https://gitlab.com/nofusscomputing/projects/django_template/-/issues/2) ]
- **access**: add to models a get_organization function
- **access**: remove change view
- **itam**: relocation item delete from list to inside device
- **context_processor**: relocate as base
- **itam**: software index does not require created and modified date
- **organizations**: set org field to null if not set
- **itam**: move software categories to settings app
- **itam**: move device types to settings app
- **template**: content_title can be rendered in base
## 0.2.0 (2024-05-18)
### Bug Fixes
### Feat
- **device**: [9e801fa9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9e801fa9eb0244d413d1555bff8e206b2ff6acd7) - correct software link [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **itam**: Add Operating System to ITAM models
- **api**: force content type to be JSON for req/resp
- **software**: view software
- **device**: Prevent devices from being set global
- **software**: if no installations found, denote
- **device**: configurable software version
- **software_version**: name does not need to be unique
- **software_version**: set is_global to match software
- **software**: prettify device software action
- **software**: ability to add software versions
- **base**: add stylised action button/text
- **software**: add pagination for index
- **device**: add pagination for index
### Continious Integration
### Fix
- [ce18edaa](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/ce18edaa398bfca5f38ae9320a6a98d6a6338318) - correct junit collection to use wildcard name [ [!6](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/6) ]
- [8b746bb9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8b746bb9ff607950a73850d3cb0432f3d5538c63) - correct junit report name [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
### Documentaton / Guides
- [fa97286d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/fa97286dc885dacbf2e56bab02cb42c67c70f9ab) - start to document features [ [!6](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/6) ]
- [7d007f72](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7d007f721af5e3a192c9a713069bec8c7a602d12) - update [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
### Features
- **itam**: [a0b5a08f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/a0b5a08f0d27f8676998eaf818c449961ccc42dd) - Add Operating System to ITAM models [ [!6](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/6) ]
- **api**: [377c78d6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/377c78d6b84398e2bbae01a91478a8ab8f94a0a2) - force content type to be JSON for req/resp [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **software**: [95405283](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/95405283b98ec6b39faedd509619dcdc39b82fc0) - view software [ [!6](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/6) ]
- **device**: [aade1e80](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/aade1e80d7d0b5bf5d45c7fe202a360d325bc396) - Prevent devices from being set global [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **software**: [0e69a0ac](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0e69a0accc32ea1513394da38e78066b0e09a5ed) - if no installations found, denote [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **device**: [b811eedb](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b811eedb338712e1e8ddfba3b032dbdd3513dda5) - configurable software version [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **software_version**: [b0e69ee6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b0e69ee64b929466a41d69b523641e17928188e7) - name does not need to be unique [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **software_version**: [b1c4e570](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b1c4e570cfb92ce6c72bd6df28f4c9d6d9eb30e6) - set is_global to match software [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **software**: [b2e1a460](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b2e1a460c853f57397c615707575f9b87b174e9c) - prettify device software action [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **software**: [7f35292f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7f35292f64656830208b097388516b13e8b91613) - ability to add software versions [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **base**: [7302f997](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7302f997530c9caba8e534877eba65dfa3659f9c) - add stylised action button/text [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **software**: [6f6031fb](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/6f6031fb1eb789e86afb7c9cbb8c12e7f1563f56) - add pagination for index [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **device**: [789b4a55](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/789b4a55d657c6c7a23af4c5d499b2be0a20481b) - add pagination for index [ [!5](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/5) ]
- **device**: correct software link
## 0.1.0 (2024-05-17)
### Bug Fixes
### Feat
- **itam**: [d3cafe08](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/d3cafe08aa7e817d5511d8f455cbd8efe5294be2) - device software to come from device org or global not users orgs [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [5a3450f3](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/5a3450f3c0f84fc32781338ef0c644356072366e) - correct team required permissions [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **fields**: [2fe15778](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2fe15778cb638eb420e5f3312ca24e33bfc601c5) - correct autoslug field so it works [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **docker**: [69aec7ba](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/69aec7ba6a5ea43fb3ec7f359744e30ac4a945ed) - build wheels then install [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **api**: initial token authentication implementation
- **docker**: add settings to store data in separate volume
- **django**: add split settings for specifying additional settings paths
- **api**: Add device config to device
- **itam**: add organization to device installs
- **itam**: migrate app from own repo
- Enable API by default
- **admin**: remove team management
- **admin**: remove group management
- **access**: adjustable team permissions
- **api**: initial work on API
- **template**: add header content icon block
- **tenancy**: Add is_ global field
- **access**: when modifying a team ad/remove user from linked group
- **auth**: include python social auth django application
- Build docker container for release
- **access**: add permissions to team and user
- **style**: format check boxes
- **access**: delete team user form
- **view**: new user
- user who is 'is_superuser' to view everything and not be denied access
- **access**: add org mixin to current views
- **access**: add views for each action for teams
- **access**: add mixin to check organization permissions against user and object
- **account**: show admin site link if user is staff
- **development**: added the debug django app
- **access**: rename structure to access and remove organization app in favour of own implementation
- **account**: Add user password change form
- **urls**: provide option to exclude navigation items
- **structure**: unregister admin pages from organization app not required
- **auth**: Custom Login Page
- **auth**: Add User Account Menu
- **auth**: Setup Login required
- Dyno-magic build navigation from application urls.py
- **structure**: Select and View an individual Organization
- **structure**: View Organizations
- **app**: Add new app structure for organizations and teams
- **template**: add base template
- **django**: add organizations app
### Code Refactor
### Fix
- [761afb6f](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/761afb6f2bc592f29870a8eaac86c70a32086af3) - button to use same selection colour [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [30e7c8de](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/30e7c8de42eafeacba02c221ad855ca0fb68f50d) - remove inline form for org teams [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- [0edfba60](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0edfba604aba7f7810dbb038b836770b888f9d15) - rename app from itsm -> app [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [86046d6e](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/86046d6e923a32145869c1cb6cc0661eec9bd1d6) - dont use inline formset [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **views**: [c7986328](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c7986328f7c36ae6a817c4e7321d41daaa9423bd) - move views to own directory [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [c9f147d8](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c9f147d805d7d2e94cb9177b61fcb608efd5deb8) - addjust org and teams to use different view per action [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **itam**: device software to come from device org or global not users orgs
- **access**: correct team required permissions
- **fields**: correct autoslug field so it works
- **docker**: build wheels then install
### Continious Integration
### Refactor
- [de83d749](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/de83d7490b9e6118beaf2eec303d38ac49332d16) - sync project to github [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- [8e2542f9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8e2542f9a50e64a2bc966d85a96d561cc1de8e67) - correct test path [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **coverage**: [eb9eeff4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/eb9eeff4ed63e09a4670c3b3ac07f98f2575694b) - add test coverage to ci [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
### Documentaton / Guides
- [f59ffa58](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/f59ffa581c5711fcb414aa4aa3ae9a3695ce4786) - add base itam pages [ [!2](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/2) ]
- [c43f41d9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c43f41d9587e060ea7f3c4e51a72f5c928c9384b) - notate global object [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- [db5d7e18](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/db5d7e18ad77c7402a8d73495ddaa9bbe626754b) - update and include permissions [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
### Features
- **api**: [962ae2b8](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/962ae2b8dfaf7cccdfd449e2a7db087f9b3542c9) - initial token authentication implementation [ [!3](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/3) ]
- **docker**: [4b77e2e6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/4b77e2e63dcc57534e821386584c3b6896d44173) - add settings to store data in separate volume [ [!2](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/2) ]
- **django**: [a96fc062](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/a96fc062f209e86bf4a8f40dd4a738ad8d889cf2) - add split settings for specifying additional settings paths [ [!2](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/2) ]
- **api**: [0c38155c](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0c38155c4453d89c552eaf16aaf7d7e2092b2431) - Add device config to device [ [!2](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/2) ]
- **itam**: [2d67f93d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2d67f93d882d1ebe7782d9425c915e31f3a16453) - add organization to device installs [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **itam**: [195bb5e4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/195bb5e4ab29540647cf30d22fcbb6e6c06e6db6) - migrate app from own repo [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- [f98e3bc9](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/f98e3bc9c2ff5f3627dc2f49df6eb7e6afdc974c) - Enable API by default [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **admin**: [4b214d0b](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/4b214d0b8cc10f43c708ef45ce5e20225f9b6c21) - remove team management [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **admin**: [736d3930](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/736d3930dff9705c3d27f853ed9a5f0000108164) - remove group management [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [50371267](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/50371267c1fb02e066d9a4ac066f54128ce957ea) - adjustable team permissions [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **api**: [102aa981](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/102aa981ce0a72fa263016139076e87778255226) - initial work on API [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **template**: [50cc050a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/50cc050adf4cfcf43303350850caa56bf649874b) - add header content icon block [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **tenancy**: [857aa7af](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/857aa7af72f9e92be04d9cc258fc5875e4223ffd) - Add is_ global field [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [070ba47d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/070ba47de284d912fc86aabb323a1639e4328d4a) - when modifying a team ad/remove user from linked group [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **auth**: [a0f4940a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/a0f4940a09fb00486ed8280eb17ec35811839947) - include python social auth django application [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- [b3b12638](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/b3b12638ad85fe1b3744561a2220d255cf9e105c) - Build docker container for release [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [ca68c258](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/ca68c2589a8cabdc11fbe7e95b0a5d58f5fd8a0e) - add permissions to team and user [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **style**: [9d507d82](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9d507d82df745a057f7903d76bf439b142e71494) - format check boxes [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [7445d880](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7445d8807ce7e995fdb2f7443e59b407e1cf92dd) - delete team user form [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **view**: [fa5703cb](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/fa5703cb794b010d46dfdce1bd03243ca260cde1) - new user [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- [8a62c3f6](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/8a62c3f6ee061add16ae165857735a44cb0bb085) - user who is 'is_superuser' to view everything and not be denied access [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [af858dcc](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/af858dcc43c414f6c523a757345537149eb4178e) - add org mixin to current views [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [2b5047db](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/2b5047db2db18bfb10ccaadbf9adce12802b9c11) - add views for each action for teams [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [d715038a](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/d715038a884cad87fba0a55f0d30ea66fda322b0) - add mixin to check organization permissions against user and object [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **account**: [0446d391](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/0446d39190406fb54baf85bc031708a03473e020) - show admin site link if user is staff [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **development**: [c0212178](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/c0212178111f000c20b0b60426d3542dd704e8ce) - added the debug django app [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **access**: [af5175c4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/af5175c4e198f5431d3f7b0d5b94f78818366053) - rename structure to access and remove organization app in favour of own implementation [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **account**: [f7bbb122](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/f7bbb122e6651635a4cb8e74246a8e155be6dcd1) - Add user password change form [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **urls**: [789777a2](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/789777a270bbd46e0a3126026e7236222f38da35) - provide option to exclude navigation items [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **structure**: [dae7f3c4](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/dae7f3c47a3c511ac30decb647461902e0dc248f) - unregister admin pages from organization app not required [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **auth**: [96a99c9d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/96a99c9df181367498e3f8d8031a0c1e4304a312) - Custom Login Page [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **auth**: [65bd32df](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/65bd32dfad3d7f8f867aea84dd4ad31133aa8fc1) - Add User Account Menu [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **auth**: [283ef9a7](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/283ef9a7145d424bca2c898935e08cdc83038fff) - Setup Login required [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- [71bcd192](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/71bcd192b3e9d6616ff8dca5d8b5745ad371de92) - Dyno-magic build navigation from application urls.py [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **structure**: [7cdfdab1](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/7cdfdab1fc966f3c92e69baf1162033c7d2e9bc4) - Select and View an individual Organization [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **structure**: [dd54eae8](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/dd54eae8d747ab0a17e71797d675a45eeaaae813) - View Organizations [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **app**: [9092445d](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/9092445d0bcbe3215f675eb5e4794cfefb710913) - Add new app structure for organizations and teams [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **template**: [1a886184](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/1a8861846bb16255c204729438057e42b3c81d7a) - add base template [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- **django**: [81b170ca](https://gitlab.com/nofusscomputing/projects/django_template/-/commit/81b170cabf2398304861fa5b68fadb962630d4cb) - add organizations app [ [!1](https://gitlab.com/nofusscomputing/projects/django_template/-/merge_requests/1) ]
- button to use same selection colour
- **access**: remove inline form for org teams
- rename app from itsm -> app
- **access**: dont use inline formset
- **views**: move views to own directory
- **access**: addjust org and teams to use different view per action
## 0.0.1 (2024-05-06)

View File

@ -15,7 +15,7 @@ pip install -r requirements.txt
```
To setup the django test server run the following
To setup the centurion erp test server run the following
``` bash
@ -41,46 +41,7 @@ Updates to python modules will need to be captured with SCM. This can be done by
!!! danger "Requirement"
All models **are** to have tests written for them, Including testing between dependent models.
To ensure consistency and reliability of this application, tests are to be written. Each test is to test one item ONLY and no more. Each module is to contain a tests directory of the model being tested with a single file for grouping of what is being tested. for items that depend upon a parent model, the test file is to be within the child-models test directory named with format `test_<model>_<parent app>_<parent model name>`
_example structure for the device model that relies upon access app model organization, core app model history and model notes._
``` text
├── tests
│   ├── device
│   │   ├── test_device_access_organization.py
│   │   ├── test_device_api_permission.py
│   │   ├── test_device_core_history.py
│   │   ├── test_device_core_notes.py
│   │   ├── test_device_permission.py
│   │   └── test_device.py
```
Items to test include but are not limited to:
- CRUD permissions admin site
- CRUD permissions api site
- CRUD permissions main site
- can only access organization object
- can access global object (still to require model CRUD permission)
- parent models
### Running Tests
test can be run by running the following:
1. `pip install -r requirements_test.txt -r requirements.txt`
1. `pytest --cov --cov-report html --cov=./`
See [Documentation](https://nofusscomputing.com/projects/django-template/development/testing/) for further information
## Docker Container
@ -89,9 +50,9 @@ test can be run by running the following:
cd app
docker build . --tag django-app:dev
docker build . --tag centurion-erp:dev
docker run -d --rm -v ${PWD}/db.sqlite3:/app/db.sqlite3 -p 8002:8000 --name app django-app:dev
docker run -d --rm -v ${PWD}/db.sqlite3:/app/db.sqlite3 -p 8002:8000 --name app centurion-erp:dev
```

View File

@ -1,8 +1,74 @@
<span style="text-align: center;">
![GitLab Bugs](https://img.shields.io/gitlab/issues/open/nofusscomputing%2Fprojects%2Fdjango_template?labels=type%3A%3Abug&style=plastic&logo=gitlab&label=Bug%20Fixes%20Required&color=fc6d26)
# No Fuss Computing - Centurion ERP
<br>
![Project Status - Active](https://img.shields.io/badge/Project%20Status-Active-green?logo=gitlab&style=plastic)
![GitLab Issues](https://img.shields.io/gitlab/issues/open/nofusscomputing%2Fprojects%2Fdjango_template?style=plastic&logo=gitlab&label=Issues&color=fc6d26)
[![Docker Pulls](https://img.shields.io/docker/pulls/nofusscomputing/centurion-erp?style=plastic&logo=docker&color=0db7ed)](https://hub.docker.com/r/nofusscomputing/centurion-erp) [![Artifact Hub](https://img.shields.io/endpoint?url=https://artifacthub.io/badge/repository/centurion-erp)](https://artifacthub.io/packages/container/centurion-erp/centurion-erp)
![Docker Pulls](https://img.shields.io/docker/pulls/nofusscomputing/django-template?style=plastic&logo=docker&color=0db7ed)
----
<br>
![GitHub forks](https://img.shields.io/github/forks/NofussComputing/centurion_erp?logo=github&style=plastic&color=000000&labell=Forks) ![GitHub stars](https://img.shields.io/github/stars/NofussComputing/centurion_erp?color=000000&logo=github&style=plastic) ![Github Watchers](https://img.shields.io/github/watchers/NofussComputing/centurion_erp?color=000000&label=Watchers&logo=github&style=plastic)
![Gitlab forks count](https://img.shields.io/badge/dynamic/json?label=Forks&query=%24.forks_count&url=https%3A%2F%2Fgitlab.com%2Fapi%2Fv4%2Fprojects%2F57560288%2F&color=ff782e&logo=gitlab&style=plastic) ![Gitlab stars](https://img.shields.io/badge/dynamic/json?label=Stars&query=%24.star_count&url=https%3A%2F%2Fgitlab.com%2Fapi%2Fv4%2Fprojects%2F57560288%2F&color=ff782e&logo=gitlab&style=plastic)
<br>
![GitHub Issues or Pull Requests](https://img.shields.io/github/issues/nofusscomputing/centurion_erp?style=plastic&logo=github&label=Open%20Issues&color=000) ![GitHub Issues or Pull Requests by label](https://img.shields.io/github/issues/nofusscomputing/centurion_erp/type%3A%3Abug?style=plastic&logo=github&label=Bug%20Fixes%20Required&color=000)
This project is hosted on [Github](https://github.com/NofussComputing/centurion_erp) and has a read-only copy hosted on [gitlab](https://gitlab.com/nofusscomputing/projects/centurion_erp).
----
**Stable Branch**
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/nofusscomputing/centurion_erp/ci.yaml?branch=master&style=plastic&logo=github&label=Build&color=%23000) ![GitHub Release](https://img.shields.io/github/v/release/nofusscomputing/centurion_erp?sort=date&style=plastic&logo=github&label=Release&color=000) ![Endpoint Badge](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fnofusscomputing%2F.github%2Fmaster%2Frepositories%2Fnofusscomputing%2Fcenturion_erp%2Fmaster%2Fbadge_endpoint_coverage.json&style=plastic)
![Endpoint Badge](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fnofusscomputing%2F.github%2Fmaster%2Frepositories%2Fnofusscomputing%2Fcenturion_erp%2Fmaster%2Fbadge_endpoint_unit_test.json)
----
**Development Branch**
![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/nofusscomputing/centurion_erp/ci.yaml?branch=development&style=plastic&logo=github&label=Build&color=%23000) ![GitHub Release](https://img.shields.io/github/v/release/nofusscomputing/centurion_erp?include_prereleases&sort=date&style=plastic&logo=github&label=Release&color=000) ![Endpoint Badge](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fnofusscomputing%2F.github%2Fmaster%2Frepositories%2Fnofusscomputing%2Fcenturion_erp%2Fdevelopment%2Fbadge_endpoint_coverage.json&style=plastic)
![Endpoint Badge](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fnofusscomputing%2F.github%2Fmaster%2Frepositories%2Fnofusscomputing%2Fcenturion_erp%2Fdevelopment%2Fbadge_endpoint_unit_test.json)
----
<br>
</div>
links:
- [Issues](https://github.com/nofusscomputing/centurion_erp/issues)
- [Merge Requests (Pull Requests)](https://github.com/nofusscomputing/centurion_erp/pulls)
An ERP with a large emphasis on the IT Service Management (ITSM) and Automation.
## Contributing
All contributions for this project must conducted from [GitHub](https://github.com/nofusscomputing/centurion_erp).
For further details on contributing please refer to the [contribution guide](CONTRIBUTING.md).
## Other
This repo is release under this [license](LICENSE)

7
Release-Notes.md Normal file
View File

@ -0,0 +1,7 @@
# Version 1.0.0
Initial Release of Centurion ERP.
## Breaking changes
- Nil

17
app/.coveragerc Normal file
View File

@ -0,0 +1,17 @@
[run]
source = .
omit =
*migrations/*
*tests/*/*
[report]
omit =
*/tests/*/*
*/migrations/*
*apps.py
*manage.py
*__init__.py
*asgi*
*wsgi*
*admin.py
*urls.py

View File

@ -17,7 +17,7 @@ class TeamInline(admin.TabularInline):
class OrganizationAdmin(admin.ModelAdmin):
fieldsets = [
(None, {"fields": ["name", "slug"]}),
(None, {"fields": ["name", 'manager', "slug"]}),
#("Date information", {"fields": ["slug"], "classes": ["collapse"]}),
]
inlines = [TeamInline]

View File

@ -0,0 +1,38 @@
from django import forms
from django.db.models import Q
from app import settings
from access.models import Organization
from core.forms.common import CommonModelForm
class OrganizationForm(CommonModelForm):
class Meta:
model = Organization
fields = [
'name',
'manager',
'model_notes',
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['created'] = forms.DateTimeField(
label="Created",
input_formats=settings.DATETIME_FORMAT,
initial=kwargs['instance'].created,
disabled=True,
required=False,
)
self.fields['modified'] = forms.DateTimeField(
label="Modified",
input_formats=settings.DATETIME_FORMAT,
initial=kwargs['instance'].modified,
disabled=True,
required=False,
)

102
app/access/forms/team.py Normal file
View File

@ -0,0 +1,102 @@
from django import forms
from django.contrib.auth.models import Permission
from django.db.models import Q
from django.forms import inlineformset_factory
from app import settings
from .team_users import TeamUsersForm, TeamUsers
from access.models import Team
from core.forms.common import CommonModelForm
TeamUserFormSet = inlineformset_factory(
model=TeamUsers,
parent_model= Team,
extra = 1,
fields=[
'user',
'manager'
]
)
class TeamFormAdd(CommonModelForm):
class Meta:
model = Team
fields = [
'team_name',
'model_notes',
]
class TeamForm(CommonModelForm):
class Meta:
model = Team
fields = [
'team_name',
'permissions',
'model_notes',
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['created'] = forms.DateTimeField(
label="Created",
input_formats=settings.DATETIME_FORMAT,
initial=kwargs['instance'].created,
disabled=True,
required=False,
)
self.fields['modified'] = forms.DateTimeField(
label="Modified",
input_formats=settings.DATETIME_FORMAT,
initial=kwargs['instance'].modified,
disabled=True,
required=False,
)
self.fields['permissions'].widget.attrs = {'style': "height: 200px;"}
apps = [
'access',
'config_management',
'core',
'django_celery_results',
'itam',
'settings',
]
exclude_models = [
'appsettings',
'chordcounter',
'groupresult',
'organization'
'settings',
'usersettings',
]
exclude_permissions = [
'add_organization',
'add_taskresult',
'change_organization',
'change_taskresult',
'delete_organization',
'delete_taskresult',
]
self.fields['permissions'].queryset = Permission.objects.filter(
content_type__app_label__in=apps,
).exclude(
content_type__model__in=exclude_models
).exclude(
codename__in = exclude_permissions
)

View File

@ -0,0 +1,16 @@
from django.db.models import Q
from app import settings
from access.models import TeamUsers
from core.forms.common import CommonModelForm
class TeamUsersForm(CommonModelForm):
class Meta:
model = TeamUsers
fields = [
'user',
'manager',
]

View File

@ -1,6 +1,7 @@
# Generated by Django 5.0.4 on 2024-05-13 16:08
# Generated by Django 5.0.7 on 2024-07-12 03:54
import access.fields
import access.models
import django.contrib.auth.models
import django.db.models.deletion
import django.utils.timezone
@ -23,9 +24,11 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(primary_key=True, serialize=False, unique=True)),
('name', models.CharField(max_length=50, unique=True)),
('model_notes', models.TextField(blank=True, default=None, null=True, verbose_name='Notes')),
('slug', access.fields.AutoSlugField()),
('created', access.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False)),
('modified', access.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False)),
('manager', models.ForeignKey(help_text='Organization Manager', null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'Organizations',
@ -37,10 +40,11 @@ class Migration(migrations.Migration):
fields=[
('group_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='auth.group')),
('is_global', models.BooleanField(default=False)),
('model_notes', models.TextField(blank=True, default=None, null=True, verbose_name='Notes')),
('team_name', models.CharField(default='', max_length=50, verbose_name='Name')),
('created', access.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False)),
('modified', access.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False)),
('organization', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='access.organization')),
('organization', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='access.organization', validators=[access.models.TenancyObject.validatate_organization_exists])),
],
options={
'verbose_name_plural': 'Teams',

View File

@ -1,19 +0,0 @@
# Generated by Django 5.0.6 on 2024-05-23 10:37
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('access', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='team',
name='organization',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='access.organization'),
),
]

View File

@ -1,20 +0,0 @@
# Generated by Django 5.0.6 on 2024-06-05 09:16
import access.models
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('access', '0002_alter_team_organization'),
]
operations = [
migrations.AlterField(
model_name='team',
name='organization',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='access.organization', validators=[access.models.TenancyObject.validatate_organization_exists]),
),
]

View File

@ -4,9 +4,7 @@ from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from django.utils.functional import cached_property
from .models import Team
from .models import Organization, Team
class OrganizationMixin():
@ -16,6 +14,21 @@ class OrganizationMixin():
user_groups = []
def get_parent_obj(self):
""" Get the Parent Model Object
Use in views where the the model has no organization and the organization should be fetched from the parent model.
Requires attribute `parent_model` within the view with the value of the parent's model class
Returns:
parent_model (Model): with PK from kwargs['pk']
"""
return self.parent_model.objects.get(pk=self.kwargs['pk'])
def object_organization(self) -> int:
id = None
@ -26,9 +39,8 @@ class OrganizationMixin():
self.get_queryset()
if hasattr(self, 'get_object'):
obj = self.get_object()
if hasattr(self, 'parent_model'):
obj = self.get_parent_obj()
id = obj.get_organization().id
@ -37,6 +49,19 @@ class OrganizationMixin():
id = 0
if hasattr(self, 'get_object') and id is None:
obj = self.get_object()
id = obj.get_organization().id
if hasattr(obj, 'is_global'):
if obj.is_global:
id = 0
except AttributeError:
if self.request.method == 'POST':
@ -45,6 +70,21 @@ class OrganizationMixin():
id = int(self.request.POST.get("organization", ""))
for field in self.request.POST.dict(): # cater for fields prefixed '<prefix>-<field name>'
a_field = str(field).split('-')
if len(a_field) == 2:
if a_field[1] == 'organization':
id = int(self.request.POST.get(field))
except:
pass
return id
@ -101,11 +141,8 @@ class OrganizationMixin():
Get All groups the user is part of, fetch the associated team,
iterate over the results adding the organization ID to a list to be returned.
Args:
request (_type_): Current http request
Returns:
_type_: _description_
_type_: User Organizations.
"""
user_organizations = []
@ -124,7 +161,7 @@ class OrganizationMixin():
# ToDo: Ensure that the group has access to item
def has_organization_permission(self, organization=None) -> bool:
def has_organization_permission(self, organization: int=None) -> bool:
has_permission = False
@ -152,20 +189,174 @@ class OrganizationMixin():
return has_permission
def permission_check(self, request, permissions_required: list = None) -> bool:
class OrganizationPermission(AccessMixin, OrganizationMixin):
"""checking organization membership"""
def dispatch(self, request, *args, **kwargs):
self.request = request
if not request.user.is_authenticated:
return self.handle_no_permission()
if permissions_required:
self.permission_required = permissions_required
organization_manager_models = [
'access.organization',
'access.team',
'access.teamusers',
]
is_organization_manager = False
queryset = None
if hasattr(self, 'get_queryset'):
queryset = self.get_queryset()
obj = None
if hasattr(self, 'get_object'):
if not self.has_organization_permission() and not request.user.is_superuser:
try:
obj = self.get_object()
except:
pass
if hasattr(self, 'model'):
if self.model._meta.label_lower in organization_manager_models:
organization = Organization.objects.get(pk=self.object_organization())
if organization.manager == request.user:
is_organization_manager = True
return True
if request.user.is_superuser:
return True
perms = self.get_permission_required()
if self.has_organization_permission():
return True
if self.request.user.has_perms(perms) and len(self.kwargs) == 0 and str(self.request.method).lower() == 'get':
return True
for required_permission in self.permission_required:
if required_permission.replace(
'view_', ''
) == 'access.organization' and len(self.kwargs) == 0:
return True
return False
class OrganizationPermission(AccessMixin, OrganizationMixin):
"""## Permission Checking
The base django permissions have not been modified with this app providing Multi-Tenancy. This is done by a mixin, that checks if the item is apart of an organization, if it is; confirmation is made that the user is part of the same organization and as long as they have the correct permission within the organization, access is granted.
### How it works
The overall permissions system of django has not been modified with it remaining fully functional. The multi-tenancy has been setup based off of an organization with teams. A team to the underlying django system is an extension of the django auth group and for every team created a django auth group is created. THe group name is set using the following format: `<organization>_<team name>` and contains underscores `_` instead of spaces.
A User who is added to an team as a "Manager" can modify the team members or if they have permission `access.change_team` which also allows the changing of team permissions. Modification of an organization can be done by the django administrator (super user) or any user with permission `access._change_organization`.
Items can be set as `Global`, meaning that all users who have the correct permission regardless of organization will be able to take action against the object.
Permissions that can be modified for a team have been limited to application permissions only unless adjust the permissions from the django admin site.
### Multi-Tenancy workflow
The workflow is conducted as part of the view and has the following flow:
1. Checks if user is member of organization the object the action is being performed on. Will also return true if the object has field `is_global` set to `true`.
1. Fetches all teams the user is part of.
1. obtains all permissions that are linked to the team.
1. checks if user has the required permission for the action.
1. confirms that the team the permission came from is part of the same organization as the object the action is being conducted on.
1. ONLY on success of the above items, grants access.
"""
permission_required: list = []
""" Permission required for the view
Not specifying this property adjusts the permission check logic so that you can
use the `permission_check()` function directly.
An example of a get request....
``` py
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
if not self.permission_check(request, [ 'access.view_organization' ]):
raise PermissionDenied('You are not part of this organization')
return super().get(request, *args, **kwargs)
```
this example details manual usage of the `permission_check()` function for a get request.
"""
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
if len(self.permission_required) > 0:
non_organization_models = [
'TaskResult'
]
if hasattr(self, 'model'):
if hasattr(self.model, '__name__'):
if self.model.__name__ in non_organization_models:
if hasattr(self, 'get_object'):
self.get_object()
perms = self.get_permission_required()
if not self.request.user.has_perms(perms):
return self.handle_no_permission()
return super().dispatch(self.request, *args, **kwargs)
if not self.permission_check(request):
raise PermissionDenied('You are not part of this organization')
return super().dispatch(self.request, *args, **kwargs)

View File

@ -37,6 +37,21 @@ class Organization(SaveHistory):
unique = True,
)
manager = models.ForeignKey(
User,
on_delete=models.SET_NULL,
blank = False,
null = True,
help_text = 'Organization Manager'
)
model_notes = models.TextField(
blank = True,
default = None,
null= True,
verbose_name = 'Notes',
)
slug = AutoSlugField()
created = AutoCreatedField()
@ -48,13 +63,103 @@ class Organization(SaveHistory):
return self
class TenancyObject(models.Model):
class TenancyManager(models.Manager):
"""Multi-Tennant Object Manager
This manager specifically caters for the multi-tenancy features of Centurion ERP.
"""
def get_queryset(self):
""" Fetch the data
This function filters the data fetched from the database to that which is from the organizations
the user is a part of.
!!! danger "Requirement"
This method may be overridden however must still be called from the overriding function. i.e. `super().get_queryset()`
## Workflow
This functions workflow is as follows:
- Fetch the user from the request
- Check if the user is authenticated
- Iterate over the users teams
- Store unique organizations from users teams
- return results
Returns:
(queryset): **super user**: return unfiltered data.
(queryset): **not super user**: return data from the stored unique organizations.
"""
request = get_request()
user_organizations: list(str()) = []
if request:
user = request.user._wrapped if hasattr(request.user,'_wrapped') else request.user
if user.is_authenticated:
for team_user in TeamUsers.objects.filter(user=user):
if team_user.team.organization.name not in user_organizations:
if not user_organizations:
self.user_organizations = []
user_organizations += [ team_user.team.organization.id ]
if len(user_organizations) > 0 and not user.is_superuser:
return super().get_queryset().filter(
models.Q(organization__in=user_organizations)
|
models.Q(is_global = True)
)
return super().get_queryset()
class TenancyObject(SaveHistory):
""" Tenancy Model Abstrct class.
This class is for inclusion wihtin **every** model within Centurion ERP.
Provides the required fields, functions and methods for multi tennant objects.
Unless otherwise stated, **no** object within this class may be overridden.
Raises:
ValidationError: User failed to supply organization
"""
objects = TenancyManager()
""" Multi-Tenanant Objects """
class Meta:
abstract = True
def validatate_organization_exists(self):
"""Ensure that the user did provide an organization
Raises:
ValidationError: User failed to supply organization.
"""
if not self:
raise ValidationError('You must provide an organization')
@ -73,11 +178,19 @@ class TenancyObject(models.Model):
blank = False
)
model_notes = models.TextField(
blank = True,
default = None,
null= True,
verbose_name = 'Notes',
)
def get_organization(self) -> Organization:
return self.organization
class Team(Group, TenancyObject, SaveHistory):
class Team(Group, TenancyObject):
class Meta:
# proxy = True
verbose_name_plural = "Teams"
@ -86,11 +199,12 @@ class Team(Group, TenancyObject, SaveHistory):
def __str__(self):
return self.name
def save(self, *args, **kwargs):
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
self.name = self.organization.name.lower().replace(' ', '_') + '_' + self.team_name.lower().replace(' ', '_')
super().save(*args, **kwargs)
super().save(force_insert=force_insert, force_update=force_update, using=using, update_fields=update_fields)
team_name = models.CharField(
@ -106,6 +220,13 @@ class Team(Group, TenancyObject, SaveHistory):
modified = AutoLastModifiedField()
@property
def parent_object(self):
""" Fetch the parent object """
return self.organization
def permission_list(self) -> list:
permission_list = []
@ -190,3 +311,10 @@ class TeamUsers(SaveHistory):
user.groups.add(group)
@property
def parent_object(self):
""" Fetch the parent object """
return self.team

View File

@ -1,9 +1,8 @@
{% extends 'base.html.j2' %}
{% block title %}Organizations{% endblock %}
{% block content_header_icon %}{% endblock %}
{% block body%}
{% block content %}
<table class="data">
<tr>

View File

@ -1,19 +1,89 @@
{% extends 'base.html.j2' %}
{% load markdown %}
{% block title %}Organization - {{ organization.name }}{% endblock %}
{% block body%}
{% block content %}
<style>
form div .helptext {
background-color: rgb(0, 140, 255);
display: block;
}
<section class="content-header">
<fieldset><label>Name</label><!-- <input type="text" value="{{ organization.name }}" /> -->{{form.name}}</fieldset>
<fieldset><label>Created</label><input type="text" value="{{ organization.created }}" readonly /></fieldset>
<fieldset><label>Modified</label><input type="text" value="{{ organization.modified }}" readonly /></fieldset>
</section>
{% include 'icons/issue_link.html.j2' with issue=13 %}<br>
<input type="button" value="<< Back" onclick="window.location='{% url 'Access:Organizations' %}';">
<input type="button" value="New Team" onclick="window.location='{% url 'Access:_team_add' organization.id %}';">
.detail-view-field {
display:unset;
height: 30px;
line-height: 30px;
padding: 0px 20px 40px 20px;
}
.detail-view-field label {
display: inline-block;
font-weight: bold;
width: 200px;
margin: 10px;
/*padding: 10px;*/
height: 30px;
line-height: 30px;
}
.detail-view-field span {
display: inline-block;
width: 340px;
margin: 10px;
/*padding: 10px;*/
border-bottom: 1px solid #ccc;
height: 30px;
line-height: 30px;
}
</style>
<div style="align-items:flex-start; align-content: center; display: flexbox; width: 100%">
<div style="display: inline; width: 40%; margin: 30px;">
<div class="detail-view-field">
<label>{{ form.name.label }}</label>
<span>{{ form.name.value }}</span>
</div>
<div class="detail-view-field">
<label>{{ form.manager.label }}</label>
<span>{{ organization.manager }}</span>
</div>
<div class="detail-view-field">
<label>{{ form.created.label }}</label>
<span>{{ form.created.value }}</span>
</div>
<div class="detail-view-field">
<label>{{ form.modified.label }}</label>
<span>{{ form.modified.value }}</span>
</div>
</div>
<div style="display: inline; width: 40%; margin: 30px; text-align: left;">
<div>
<label style="font-weight: bold; width: 100%; border-bottom: 1px solid #ccc; display: block; text-align: inherit;">{{ form.model_notes.label }}</label>
<div style="display: inline-block; text-align: left;">{{ form.model_notes.value | markdown | safe }}</div>
</div>
</div>
<div style="display: block;">
<input type="button" value="<< Back" onclick="window.location='{% url 'Access:Organizations' %}';">
<input type="button" value="New Team" onclick="window.location='{% url 'Access:_team_add' organization.id %}';">
</div>
<hr />
<table>

View File

@ -2,27 +2,12 @@
{% block title %}Team - {{ team.team_name }}{% endblock %}
{% block body%}
{% block content %}
<form method="post">
{% csrf_token %}
<div>
<input name="organization" id="id_organization" type="hidden" value="{{ organization.id }}">
<section class="content-header">
<fieldset><label>Name</label><input name="name" required id="id_name" type="text" value="{{ team.team_name }}" /></fieldset>
<fieldset><label>Created</label><input name="created" type="text" value="{{ team.created }}" readonly /></fieldset>
<fieldset><label>Modified</label><input name="modified" type="text" value="{{ team.modified }}" readonly /></fieldset>
<fieldset><label>Permissions</label>
<select name="permissions" id="id_permissions" style="height: 200px;" multiple>
{% for permission in permissions %}
{% if 'administration' not in permission.content_type|lower and 'authorization' not in permission.content_type|lower and 'content types' not in permission.content_type|lower and 'session' not in permission.content_type|lower and 'python social auth' not in permission.content_type|lower and 'add_organization' not in permission.codename|lower and 'delete_organization' not in permission.codename|lower %}
<option value="{{ permission.id }}" {% for team_permission in team.permissions.all %}{% if permission.id == team_permission.id %}selected{% endif %}{% endfor %}>{{ permission.content_type }} | {{ permission.name }}</option>
{% endif %}
{% endfor %}
</select>
</fieldset>
</section>
</div>
{% include 'icons/issue_link.html.j2' with issue=13 %}<br>
{{ form.as_div }}
<input style="display:unset;" type="submit" value="Submit">
</form>
@ -32,7 +17,7 @@
<input type="button" value="<< Back" onclick="window.location='{% url 'Access:_organization_view' pk=organization.id %}';">
<input type="button" value="Delete Team"
onclick="window.location='{% url 'Access:_team_delete' organization_id=organization.id pk=team.id %}';">
<input type="button" value="New User"
<input type="button" value="Assign User"
onclick="window.location='{% url 'Access:_team_user_add' organization_id=organization.id pk=team.id %}';">
{{ formset.management_form }}

View File

View File

View File

@ -0,0 +1,251 @@
import pytest
import unittest
from django.test import Client
from django.shortcuts import reverse
class OrganizationManagerModelPermissionView:
""" Tests for checking Organization Manager model permissions """
app_namespace: str = None
""" Application namespace of the model being tested """
different_organization_is_manager: object
""" User whom is organization Manager of different organization than object """
url_name_view: str
""" url name of the model view to be tested """
url_view_kwargs: dict = None
""" View URL kwargs for model being tested """
user_is_organization_manager: object
""" User whom is organization Manager of the object"""
def test_model_view_different_organizaiton_is_organization_manager_denied(self):
""" Check correct permission for view
Attempt to view with user from different organization whom is an organization Manager.
"""
client = Client()
if self.app_namespace:
url = reverse(self.app_namespace + ':' + self.url_name_view, kwargs=self.url_view_kwargs)
else:
url = reverse(self.url_name_view, kwargs=self.url_view_kwargs)
client.force_login(self.different_organization_is_manager)
response = client.get(url)
assert response.status_code == 403
def test_model_view_has_no_permission_is_organization_manager(self):
""" Confirm that an organization manager can view the model
Attempt to view as user who is an organization manager and has no permissions assigned.
Object to be within same organization the user is a manager of.
"""
client = Client()
if self.app_namespace:
url = reverse(self.app_namespace + ':' + self.url_name_view, kwargs=self.url_view_kwargs)
else:
url = reverse(self.url_name_view, kwargs=self.url_view_kwargs)
client.force_login(self.user_is_organization_manager)
response = client.get(url)
assert response.status_code == 200
class OrganizationManagerModelPermissionAdd:
""" Tests for checking model Add permissions """
app_namespace: str = None
""" Application namespace of the model being tested """
different_organization_is_manager: object
""" User whom is organization Manager of different organization than object """
url_name_view: str
""" url name of the model view to be tested """
url_view_kwargs: dict = None
""" View URL kwargs for model being tested """
user_is_organization_manager: object
""" User whom is organization Manager of the object"""
def test_model_add_different_organization_is_organization_manager_denied(self):
""" Check correct permission for add
attempt to add as user from different organization whom is an organization Manager.
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name_add, kwargs=self.url_add_kwargs)
client.force_login(self.different_organization_is_manager)
response = client.post(url, data=self.add_data)
assert response.status_code == 403
def test_model_add_has_no_permission_is_organization_manager(self):
""" Check correct permission for add
Attempt to add as user who is an organization manager and has no permissions assigned.
Object to be within same organization the user is a manager of.
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name_add, kwargs=self.url_add_kwargs)
client.force_login(self.user_is_organization_manager)
response = client.post(url, data=self.add_data)
assert response.status_code == 200
class OrganizationManagerModelPermissionChange:
""" Tests for checking model change permissions """
app_namespace: str = None
""" Application namespace of the model being tested """
different_organization_is_manager: object
""" User whom is organization Manager of different organization than object """
url_name_change: str
""" url name of the model view to be tested """
url_change_kwargs: dict = None
""" View URL kwargs for model being tested """
user_is_organization_manager: object
""" User whom is organization Manager of the object"""
def test_model_change_different_organization_is_organization_manager_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization whom is an organization Manager.
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name_change, kwargs=self.url_change_kwargs)
client.force_login(self.different_organization_is_manager)
response = client.post(url, data=self.change_data)
assert response.status_code == 403
def test_model_change_has_no_permission_is_organization_manager(self):
""" Check correct permission for change
Make change as user who is an organization manager and has no permissions assigned.
Object to be within same organization the user is a manager of.
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name_change, kwargs=self.url_change_kwargs)
client.force_login(self.user_is_organization_manager)
response = client.post(url, data=self.change_data)
assert response.status_code == 200
class OrganizationManagerModelPermissionDelete:
""" Tests for checking model delete permissions """
app_namespace: str = None
""" Application namespace of the model being tested """
different_organization_is_manager: object
""" User whom is organization Manager of different organization than object """
url_name_view: str
""" url name of the model view to be tested """
url_view_kwargs: dict = None
""" View URL kwargs for model being tested """
user_is_organization_manager: object
""" User whom is organization Manager of the object"""
def test_model_delete_different_organization_is_organization_manager_denied(self):
""" Check correct permission for delete
Attempt to delete as user from different organization whom is an organization Manager.
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name_delete, kwargs=self.url_delete_kwargs)
client.force_login(self.different_organization_is_manager)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 403
def test_model_delete_has_no_permission_is_organization_manager(self):
""" Check correct permission for delete
Delete item as user who is an organization manager and has no permissions assigned.
Object to be within same organization the user is a manager of.
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name_delete, kwargs=self.url_delete_kwargs)
client.force_login(self.user_is_organization_manager)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 302 and response.url == self.url_delete_response
class OrganizationManagerModelPermissions(
OrganizationManagerModelPermissionView,
OrganizationManagerModelPermissionAdd,
OrganizationManagerModelPermissionChange,
OrganizationManagerModelPermissionDelete
):
""" Tests for checking Organization Manager model permissions
This class includes all test cases for: Add, Change, Delete and View.
"""
app_namespace: str = None

View File

@ -0,0 +1,88 @@
import pytest
import unittest
from access.models import TenancyManager
class TenancyObject:
""" Tests for checking TenancyObject """
model = None
""" Model to be tested """
def test_has_attr_get_organization(self):
""" TenancyObject attribute check
TenancyObject has function get_organization
"""
assert hasattr(self.model, 'get_organization')
def test_has_attr_is_global(self):
""" TenancyObject attribute check
TenancyObject has field is_global
"""
assert hasattr(self.model, 'is_global')
def test_has_attr_model_notes(self):
""" TenancyObject attribute check
TenancyObject has field model_notes
"""
assert hasattr(self.model, 'model_notes')
def test_has_attr_organization(self):
""" TenancyObject attribute check
TenancyObject has field organization
"""
assert hasattr(self.model, 'organization')
@pytest.mark.skip(reason="to be written")
def test_create_no_organization_fails(self):
""" Devices must be assigned an organization
Must not be able to create an item without an organization
"""
pass
@pytest.mark.skip(reason="to be written")
def test_edit_no_organization_fails(self):
""" Devices must be assigned an organization
Must not be able to edit an item without an organization
"""
pass
def test_has_attr_organization(self):
""" TenancyObject attribute check
TenancyObject has function objects
"""
assert hasattr(self.model, 'objects')
def test_attribute_is_type_objects(self):
""" Attribute Check
attribute `objects` must be set to `access.models.TenancyManager()`
"""
assert type(self.model.objects) is TenancyManager

View File

@ -1,532 +0,0 @@
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
class OrganizationPermissions(TestCase):
model = Organization
model_name = 'organization'
app_label = 'access'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a device
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
# self.item = self.model.objects.create(
# organization=organization,
# name = 'deviceone'
# )
self.item = organization
view_permissions = Permission.objects.get(
codename = 'view_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
def test_organization_auth_view_user_anon_denied(self):
""" Check correct permission for view
Attempt to view as anon user
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
response = client.get(url)
assert response.status_code == 302 and response.url.startswith('/account/login')
def test_organization_auth_view_no_permission_denied(self):
""" Check correct permission for view
Attempt to view with user missing permission
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.get(url)
assert response.status_code == 403
def test_organization_auth_view_different_organizaiton_denied(self):
""" Check correct permission for view
Attempt to view with user from different organization
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.get(url)
assert response.status_code == 403
def test_organization_auth_view_has_permission(self):
""" Check correct permission for view
Attempt to view as user with view permission
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.get(url)
assert response.status_code == 200
@pytest.mark.skip(reason="No Add view exists")
def test_organization_auth_add_user_anon_denied(self):
""" Check correct permission for add
Attempt to add as anon user
"""
client = Client()
url = reverse('Access:_organization_add')
response = client.put(url, data={'device': 'device'})
assert (
response.status_code == 302
or
response.status_code == 403
)
@pytest.mark.skip(reason="No Add view exists")
def test_organization_auth_add_no_permission_denied(self):
""" Check correct permission for add
Attempt to add as user with no permissions
"""
client = Client()
url = reverse('Access:_organization_add')
client.force_login(self.no_permissions_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="No Add view exists")
def test_organization_auth_add_different_organization_denied(self):
""" Check correct permission for add
attempt to add as user from different organization
"""
client = Client()
url = reverse('Access:_organization_add')
client.force_login(self.different_organization_user)
response = client.post(url, data={'name': 'device', 'organization': self.organization.id})
assert response.status_code == 403
@pytest.mark.skip(reason="No Add view exists")
def test_organization_auth_add_permission_view_denied(self):
""" Check correct permission for add
Attempt to add a user with view permission
"""
client = Client()
url = reverse('Access:_organization_add')
client.force_login(self.view_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="No Add view exists")
def test_organization_auth_add_has_permission(self):
""" Check correct permission for add
Attempt to add as user with no permission
"""
client = Client()
url = reverse('Access:_organization_add')
client.force_login(self.add_user)
response = client.post(url, data={'device': 'device', 'organization': self.organization.id})
assert response.status_code == 200
def test_organization_auth_change_user_anon_denied(self):
""" Check correct permission for change
Attempt to change as anon
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 302 and response.url.startswith('/account/login')
def test_organization_auth_change_no_permission_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user without permissions
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_different_organization_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_permission_view_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with view permission
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_permission_add_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with add permission
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.add_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_has_permission(self):
""" Check correct permission for change
Make change with user who has change permission
"""
client = Client()
url = reverse('Access:_organization_view', kwargs={'pk': self.item.id})
client.force_login(self.change_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 200
@pytest.mark.skip(reason="No Delete view exists")
def test_organization_auth_delete_user_anon_denied(self):
""" Check correct permission for delete
Attempt to delete item as anon user
"""
client = Client()
url = reverse('Access:_organization_delete', kwargs={'pk': self.item.id})
response = client.delete(url, data={'device': 'device'})
assert (
response.status_code == 302
or
response.status_code == 403
)
@pytest.mark.skip(reason="No Delete view exists")
def test_organization_auth_delete_no_permission_denied(self):
""" Check correct permission for delete
Attempt to delete as user with no permissons
"""
client = Client()
url = reverse('Access:_organization_delete', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="No Delete view exists")
def test_organization_auth_delete_different_organization_denied(self):
""" Check correct permission for delete
Attempt to delete as user from different organization
"""
client = Client()
url = reverse('Access:_organization_delete', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="No Delete view exists")
def test_organization_auth_delete_permission_view_denied(self):
""" Check correct permission for delete
Attempt to delete as user with veiw permission only
"""
client = Client()
url = reverse('Access:_organization_delete', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="No Delete view exists")
def test_organization_auth_delete_permission_add_denied(self):
""" Check correct permission for delete
Attempt to delete as user with add permission only
"""
client = Client()
url = reverse('Access:_organization_delete', kwargs={'pk': self.item.id})
client.force_login(self.add_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="No Delete view exists")
def test_organization_auth_delete_permission_change_denied(self):
""" Check correct permission for delete
Attempt to delete as user with change permission only
"""
client = Client()
url = reverse('Access:_organization_delete', kwargs={'pk': self.item.id})
client.force_login(self.change_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="No Delete view exists")
def test_organization_auth_delete_has_permission(self):
""" Check correct permission for delete
Delete item as user with delete permission
"""
client = Client()
url = reverse('Access:_organization_delete', kwargs={'pk': self.item.id})
client.force_login(self.delete_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 302 and response.url == reverse('Access:Devices')

View File

@ -1,526 +0,0 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase
from rest_framework.test import APIClient as Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
class OrganizationPermissionsAPI(TestCase):
model = Organization
model_name = 'organization'
app_label = 'access'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a device
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.item = organization
view_permissions = Permission.objects.get(
codename = 'view_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
def test_organization_auth_view_user_anon_denied_api(self):
""" Check correct permission for view
Attempt to view as anon user
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
response = client.get(url)
assert response.status_code == 401
def test_organization_auth_view_no_permission_denied(self):
""" Check correct permission for view
Attempt to view with user missing permission
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.get(url)
assert response.status_code == 403
def test_organization_auth_view_different_organizaiton_denied(self):
""" Check correct permission for view
Attempt to view with user from different organization
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.get(url)
assert response.status_code == 403
def test_organization_auth_view_has_permission(self):
""" Check correct permission for view
Attempt to view as user with view permission
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.get(url)
assert response.status_code == 200
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_add_user_anon_denied(self):
# """ Check correct permission for add
# Attempt to add as anon user
# """
# client = Client()
# url = reverse('API:_api_orgs')
# response = client.post(url, data={'device': 'device'})
# assert (
# response.status_code == 302
# or
# response.status_code == 403
# )
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_add_no_permission_denied(self):
# """ Check correct permission for add
# Attempt to add as user with no permissions
# """
# client = Client()
# url = reverse('API:_api_orgs')
# client.force_login(self.no_permissions_user)
# response = client.post(url, data={'device': 'device'})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_add_different_organization_denied(self):
# """ Check correct permission for add
# attempt to add as user from different organization
# """
# client = Client()
# url = reverse('API:_api_orgs')
# client.force_login(self.different_organization_user)
# response = client.post(url, data={'name': 'device', 'organization': self.organization.id})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_add_permission_view_denied(self):
# """ Check correct permission for add
# Attempt to add a user with view permission
# """
# client = Client()
# url = reverse('API:_api_orgs')
# client.force_login(self.view_user)
# response = client.post(url, data={'device': 'device'})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_add_has_permission(self):
# """ Check correct permission for add
# Attempt to add as user with no permission
# """
# client = Client()
# url = reverse('API:_api_orgs')
# client.force_login(self.add_user)
# response = client.post(url, data={'device': 'device', 'organization': self.organization.id})
# assert response.status_code == 200
def test_organization_auth_change_user_anon_denied(self):
""" Check correct permission for change
Attempt to change as anon
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 401
def test_organization_auth_change_no_permission_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user without permissions
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_different_organization_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_permission_view_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with view permission
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_permission_add_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with add permission
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.add_user)
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 403
def test_organization_auth_change_has_permission(self):
""" Check correct permission for change
Make change with user who has change permission
"""
client = Client()
url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
client.force_login(self.change_user)
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 200
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_delete_user_anon_denied(self):
# """ Check correct permission for delete
# Attempt to delete item as anon user
# """
# client = Client()
# url = reverse('API:_api_orgs', kwargs={'pk': self.item.id})
# response = client.delete(url, data={'device': 'device'})
# assert (
# response.status_code == 302
# or
# response.status_code == 403
# )
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_delete_no_permission_denied(self):
# """ Check correct permission for delete
# Attempt to delete as user with no permissons
# """
# client = Client()
# url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
# client.force_login(self.no_permissions_user)
# response = client.delete(url, data={'device': 'device'})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_delete_different_organization_denied(self):
# """ Check correct permission for delete
# Attempt to delete as user from different organization
# """
# client = Client()
# url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
# client.force_login(self.different_organization_user)
# response = client.delete(url, data={'device': 'device'})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_delete_permission_view_denied(self):
# """ Check correct permission for delete
# Attempt to delete as user with veiw permission only
# """
# client = Client()
# url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
# client.force_login(self.view_user)
# response = client.delete(url, data={'device': 'device'})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_delete_permission_add_denied(self):
# """ Check correct permission for delete
# Attempt to delete as user with add permission only
# """
# client = Client()
# url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
# client.force_login(self.add_user)
# response = client.delete(url, data={'device': 'device'})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_delete_permission_change_denied(self):
# """ Check correct permission for delete
# Attempt to delete as user with change permission only
# """
# client = Client()
# url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
# client.force_login(self.change_user)
# response = client.delete(url, data={'device': 'device'})
# assert response.status_code == 403
# @pytest.mark.skip(reason="currently only able to add via admin interface")
# def test_organization_auth_delete_has_permission(self):
# """ Check correct permission for delete
# Delete item as user with delete permission
# """
# client = Client()
# url = reverse('API:_api_organization', kwargs={'pk': self.item.id})
# client.force_login(self.delete_user)
# response = client.delete(url, data={'device': 'device'})
# assert response.status_code == 302 and response.url == reverse('API:_api_orgs')

View File

@ -1,243 +0,0 @@
import pytest
import unittest
import requests
from django.test import TestCase, Client
from access.models import Organization
from core.models.history import History
from access.models import Team
# @pytest.mark.skip(reason="to be written")
# def test_history_auth_view():
# """ User requires Permission view_history """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_create():
# """ History row must be added to history table on create """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_update():
# """ History row must be added to history table on updatej """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_delete():
# """ History row must be added to history table on delete """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_create():
# """ History row must be added to history table on create
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_update():
# """ History row must be added to history table on update
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_delete():
# """ History row must be added to history table on delete
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_create():
# """ History row must be added to history table on create
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_update():
# """ History row must be added to history table on update
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_delete():
# """ History row must be added to history table on delete
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
class TeamHistory(TestCase):
model = Team
model_name = 'team'
@classmethod
def setUpTestData(self):
""" Setup Test """
organization = Organization.objects.create(name='test_org')
self.organization = organization
self.item_create = self.model.objects.create(
name = 'test_item_' + self.model_name,
organization = self.organization
)
self.history_create = History.objects.get(
action = History.Actions.ADD[0],
item_pk = self.item_create.pk,
item_class = self.model._meta.model_name,
)
self.item_change = self.item_create
self.item_change.name = 'test_item_' + self.model_name + '_changed'
self.item_change.save()
self.history_change = History.objects.get(
action = History.Actions.UPDATE[0],
item_pk = self.item_change.pk,
item_class = self.model._meta.model_name,
)
@pytest.mark.skip(reason="fails, fixme see #46")
# field type testing to be done as part of model testing
def test_history_entry_item_add_field_action(self):
""" Ensure action is "add" for item creation """
history = self.history_create.__dict__
assert history['action'] == int(History.Actions.ADD[0])
# assert type(history['action']) is int
@pytest.mark.skip(reason="to be written")
def test_history_entry_item_add_field_after(self):
""" Ensure after field contains correct value """
history = self.history_create.__dict__
assert history['after'] == str('{}')
# assert type(history['after']) is str
@pytest.mark.skip(reason="fails, fixme see #46")
def test_history_entry_item_add_field_before(self):
""" Ensure before field is an empty JSON string for create """
history = self.history_create.__dict__
assert history['before'] == str('{}')
# assert type(history['before']) is str
@pytest.mark.skip(reason="fails, fixme see #46")
def test_history_entry_item_add_field_item_pk(self):
""" Ensure history entry field item_pk is the created items pk """
history = self.history_create.__dict__
assert history['item_pk'] == self.item_create.pk
# assert type(history['item_pk']) is int
@pytest.mark.skip(reason="fails, fixme see #46")
def test_history_entry_item_add_field_item_class(self):
""" Ensure history entry field item_class is the model name """
history = self.history_create.__dict__
assert history['item_class'] == self.model._meta.model_name
# assert type(history['item_class']) is str
################################## Change ##################################
@pytest.mark.skip(reason="fails, fixme see #46")
# field type testing to be done as part of model testing
def test_history_entry_item_change_field_action(self):
""" Ensure action is "add" for item creation """
history = self.history_change.__dict__
assert history['action'] == int(History.Actions.UPDATE[0])
# assert type(history['action']) is int
@pytest.mark.skip(reason="fails, fixme see #46")
def test_history_entry_item_change_field_after(self):
""" Ensure after field contains correct value """
history = self.history_change.__dict__
assert history['after'] == str('{"name": "test_item_' + self.model_name + '_changed"}')
# assert type(history['after']) is str
@pytest.mark.skip(reason="to be written")
def test_history_entry_item_change_field_before(self):
""" Ensure before field is an empty JSON string for create """
history = self.history_change.__dict__
assert history['before'] == str('{}')
# assert type(history['before']) is str
@pytest.mark.skip(reason="fails, fixme see #46")
def test_history_entry_item_change_field_item_pk(self):
""" Ensure history entry field item_pk is the created items pk """
history = self.history_change.__dict__
assert history['item_pk'] == self.item_create.pk
# assert type(history['item_pk']) is int
@pytest.mark.skip(reason="fails, fixme see #46")
def test_history_entry_item_change_field_item_class(self):
""" Ensure history entry field item_class is the model name """
history = self.history_change.__dict__
assert history['item_class'] == self.model._meta.model_name
# assert type(history['item_class']) is str

View File

@ -1,510 +0,0 @@
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
class TeamPermissions(TestCase):
model = Team
model_name = 'team'
app_label = 'access'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a team
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.item = self.model.objects.create(
organization=organization,
name = 'teamone'
)
view_permissions = Permission.objects.get(
codename = 'view_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
def test_team_auth_view_user_anon_denied(self):
""" Check correct permission for view
Attempt to view as anon user
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
response = client.get(url)
assert response.status_code == 302 and response.url.startswith('/account/login')
def test_team_auth_view_no_permission_denied(self):
""" Check correct permission for view
Attempt to view with user missing permission
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.get(url)
assert response.status_code == 403
def test_team_auth_view_different_organizaiton_denied(self):
""" Check correct permission for view
Attempt to view with user from different organization
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.get(url)
assert response.status_code == 403
def test_team_auth_view_has_permission(self):
""" Check correct permission for view
Attempt to view as user with view permission
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.view_user)
response = client.get(url)
assert response.status_code == 200
def test_team_auth_add_user_anon_denied(self):
""" Check correct permission for add
Attempt to add as anon user
"""
client = Client()
url = reverse('Access:_team_add', kwargs={'pk': self.organization.id})
response = client.put(url, data={'team': 'team'})
assert response.status_code == 302 and response.url.startswith('/account/login')
def test_team_auth_add_no_permission_denied(self):
""" Check correct permission for add
Attempt to add as user with no permissions
"""
client = Client()
url = reverse('Access:_team_add', kwargs={'pk': self.organization.id})
client.force_login(self.no_permissions_user)
response = client.post(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_add_different_organization_denied(self):
""" Check correct permission for add
attempt to add as user from different organization
"""
client = Client()
url = reverse('Access:_team_add', kwargs={'pk': self.organization.id})
client.force_login(self.different_organization_user)
response = client.post(url, data={'name': 'team', 'organization': self.organization.id})
assert response.status_code == 403
def test_team_auth_add_permission_view_denied(self):
""" Check correct permission for add
Attempt to add a user with view permission
"""
client = Client()
url = reverse('Access:_team_add', kwargs={'pk': self.organization.id})
client.force_login(self.view_user)
response = client.post(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_add_has_permission(self):
""" Check correct permission for add
Attempt to add as user with no permission
"""
client = Client()
url = reverse('Access:_team_add', kwargs={'pk': self.organization.id})
client.force_login(self.add_user)
response = client.post(url, data={'team': 'team', 'organization': self.organization.id})
assert response.status_code == 200
def test_team_auth_change_user_anon_denied(self):
""" Check correct permission for change
Attempt to change as anon
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
response = client.patch(url, data={'team': 'team'})
assert response.status_code == 302 and response.url.startswith('/account/login')
def test_team_auth_change_no_permission_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user without permissions
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.post(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_different_organization_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.post(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_permission_view_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with view permission
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.view_user)
response = client.post(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_permission_add_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with add permission
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.add_user)
response = client.post(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_has_permission(self):
""" Check correct permission for change
Make change with user who has change permission
"""
client = Client()
url = reverse('Access:_team_view', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.change_user)
response = client.post(url, data={'team': 'team'})
assert response.status_code == 200
def test_team_auth_delete_user_anon_denied(self):
""" Check correct permission for delete
Attempt to delete item as anon user
"""
client = Client()
url = reverse('Access:_team_delete', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 302 and response.url.startswith('/account/login')
def test_team_auth_delete_no_permission_denied(self):
""" Check correct permission for delete
Attempt to delete as user with no permissons
"""
client = Client()
url = reverse('Access:_team_delete', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_different_organization_denied(self):
""" Check correct permission for delete
Attempt to delete as user from different organization
"""
client = Client()
url = reverse('Access:_team_delete', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_permission_view_denied(self):
""" Check correct permission for delete
Attempt to delete as user with veiw permission only
"""
client = Client()
url = reverse('Access:_team_delete', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.view_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_permission_add_denied(self):
""" Check correct permission for delete
Attempt to delete as user with add permission only
"""
client = Client()
url = reverse('Access:_team_delete', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.add_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_permission_change_denied(self):
""" Check correct permission for delete
Attempt to delete as user with change permission only
"""
client = Client()
url = reverse('Access:_team_delete', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.change_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_has_permission(self):
""" Check correct permission for delete
Delete item as user with delete permission
"""
client = Client()
url = reverse('Access:_team_delete', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.delete_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 302 and response.url == reverse('Access:_organization_view', kwargs={'pk': self.organization.id})

View File

@ -1,512 +0,0 @@
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client as nClient
from rest_framework.test import APIClient as Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
class TeamPermissionsAPI(TestCase):
model = Team
model_name = 'team'
app_label = 'access'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a team
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.item = self.model.objects.create(
organization=organization,
name = 'teamone'
)
view_permissions = Permission.objects.get(
codename = 'view_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
def test_team_auth_view_user_anon_denied(self):
""" Check correct permission for view
Attempt to view as anon user
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
response = client.get(url)
assert response.status_code == 401
def test_team_auth_view_no_permission_denied(self):
""" Check correct permission for view
Attempt to view with user missing permission
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.no_permissions_user)
response = client.get(url)
assert response.status_code == 403
def test_team_auth_view_different_organizaiton_denied(self):
""" Check correct permission for view
Attempt to view with user from different organization
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.different_organization_user)
response = client.get(url)
assert response.status_code == 403
def test_team_auth_view_has_permission(self):
""" Check correct permission for view
Attempt to view as user with view permission
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.view_user)
response = client.get(url)
assert response.status_code == 200
def test_team_auth_add_user_anon_denied(self):
""" Check correct permission for add
Attempt to add as anon user
"""
client = Client()
url = reverse('API:_api_organization_teams', kwargs={'organization_id': self.organization.id})
response = client.post(url, data={'team_name': 'team'})
assert response.status_code == 401
def test_team_auth_add_no_permission_denied(self):
""" Check correct permission for add
Attempt to add as user with no permissions
"""
client = Client()
url = reverse('API:_api_organization_teams', kwargs={'organization_id': self.organization.id})
client.force_login(self.no_permissions_user)
response = client.post(url, data={'team_name': 'team'})
assert response.status_code == 403
def test_team_auth_add_different_organization_denied(self):
""" Check correct permission for add
attempt to add as user from different organization
"""
client = Client()
url = reverse('API:_api_organization_teams', kwargs={'organization_id': self.organization.id})
client.force_login(self.different_organization_user)
response = client.post(url, data={'team_name': 'team'})
assert response.status_code == 403
def test_team_auth_add_permission_view_denied(self):
""" Check correct permission for add
Attempt to add a user with view permission
"""
client = Client()
url = reverse('API:_api_organization_teams', kwargs={'organization_id': self.organization.id})
client.force_login(self.view_user)
response = client.post(url, data={'team_name': 'team'})
assert response.status_code == 403
def test_team_auth_add_has_permission(self):
""" Check correct permission for add
Attempt to add as user with no permission
"""
client = Client()
url = reverse('API:_api_organization_teams', kwargs={'organization_id': self.organization.id})
client.force_login(self.add_user)
response = client.post(url, {'team_name': 'team_post'})
assert response.status_code == 201
def test_team_auth_change_user_anon_denied(self):
""" Check correct permission for change
Attempt to change as anon
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
response = client.patch(url, data={'team': 'team'})
assert response.status_code == 401
def test_team_auth_change_no_permission_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user without permissions
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.no_permissions_user)
response = client.patch(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_different_organization_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.different_organization_user)
response = client.patch(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_permission_view_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with view permission
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.view_user)
response = client.patch(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_permission_add_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with add permission
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.add_user)
response = client.patch(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_change_has_permission(self):
""" Check correct permission for change
Make change with user who has change permission
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.change_user)
response = client.patch(url, data={'id': self.item.id, 'team_name': 'team'})
assert response.status_code == 200
def test_team_auth_delete_user_anon_denied(self):
""" Check correct permission for delete
Attempt to delete item as anon user
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 401
def test_team_auth_delete_no_permission_denied(self):
""" Check correct permission for delete
Attempt to delete as user with no permissons
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.no_permissions_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_different_organization_denied(self):
""" Check correct permission for delete
Attempt to delete as user from different organization
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.different_organization_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_permission_view_denied(self):
""" Check correct permission for delete
Attempt to delete as user with veiw permission only
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.view_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_permission_add_denied(self):
""" Check correct permission for delete
Attempt to delete as user with add permission only
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.add_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_permission_change_denied(self):
""" Check correct permission for delete
Attempt to delete as user with change permission only
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.change_user)
response = client.delete(url, data={'team': 'team'})
assert response.status_code == 403
def test_team_auth_delete_has_permission(self):
""" Check correct permission for delete
Delete item as user with delete permission
"""
client = Client()
url = reverse('API:_api_team', kwargs={'organization_id': self.organization.id, 'group_ptr_id': self.item.id})
client.force_login(self.delete_user)
response = client.delete(url, data={'group_ptr_id': self.item.id}, content_type='application/json')
assert response.status_code == 204

View File

@ -1,243 +0,0 @@
import pytest
import unittest
import requests
from django.test import TestCase, Client
from access.models import Organization
from core.models.history import History
from access.models import TeamUsers
# @pytest.mark.skip(reason="to be written")
# def test_history_auth_view():
# """ User requires Permission view_history """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_create():
# """ History row must be added to history table on create """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_update():
# """ History row must be added to history table on updatej """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_delete():
# """ History row must be added to history table on delete """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_create():
# """ History row must be added to history table on create
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_update():
# """ History row must be added to history table on update
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_delete():
# """ History row must be added to history table on delete
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_create():
# """ History row must be added to history table on create
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_update():
# """ History row must be added to history table on update
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_delete():
# """ History row must be added to history table on delete
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
@pytest.mark.skip(reason="to do")
class TeamUsersHistory(TestCase):
model = TeamUsers
model_name = 'teamusers'
@classmethod
def setUpTestData(self):
""" Setup Test """
organization = Organization.objects.create(name='test_org')
self.organization = organization
self.item_create = self.model.objects.create(
name = 'test_item_' + self.model_name,
organization = self.organization
)
self.history_create = History.objects.get(
action = History.Actions.ADD[0],
item_pk = self.item_create.pk,
item_class = self.model._meta.model_name,
)
self.item_change = self.item_create
self.item_change.name = 'test_item_' + self.model_name + '_changed'
self.item_change.save()
self.history_change = History.objects.get(
action = History.Actions.UPDATE[0],
item_pk = self.item_change.pk,
item_class = self.model._meta.model_name,
)
@pytest.mark.skip(reason="to do")
# field type testing to be done as part of model testing
def test_history_entry_item_add_field_action(self):
""" Ensure action is "add" for item creation """
history = self.history_create.__dict__
assert history['action'] == int(History.Actions.ADD[0])
# assert type(history['action']) is int
@pytest.mark.skip(reason="to be written")
def test_history_entry_item_add_field_after(self):
""" Ensure after field contains correct value """
history = self.history_create.__dict__
assert history['after'] == str('{}')
# assert type(history['after']) is str
@pytest.mark.skip(reason="to do")
def test_history_entry_item_add_field_before(self):
""" Ensure before field is an empty JSON string for create """
history = self.history_create.__dict__
assert history['before'] == str('{}')
# assert type(history['before']) is str
@pytest.mark.skip(reason="to do")
def test_history_entry_item_add_field_item_pk(self):
""" Ensure history entry field item_pk is the created items pk """
history = self.history_create.__dict__
assert history['item_pk'] == self.item_create.pk
# assert type(history['item_pk']) is int
@pytest.mark.skip(reason="to do")
def test_history_entry_item_add_field_item_class(self):
""" Ensure history entry field item_class is the model name """
history = self.history_create.__dict__
assert history['item_class'] == self.model._meta.model_name
# assert type(history['item_class']) is str
################################## Change ##################################
@pytest.mark.skip(reason="to do")
# field type testing to be done as part of model testing
def test_history_entry_item_change_field_action(self):
""" Ensure action is "add" for item creation """
history = self.history_change.__dict__
assert history['action'] == int(History.Actions.UPDATE[0])
# assert type(history['action']) is int
@pytest.mark.skip(reason="to do")
def test_history_entry_item_change_field_after(self):
""" Ensure after field contains correct value """
history = self.history_change.__dict__
assert history['after'] == str('{"name": "test_item_' + self.model_name + '_changed"}')
# assert type(history['after']) is str
@pytest.mark.skip(reason="to be written")
def test_history_entry_item_change_field_before(self):
""" Ensure before field is an empty JSON string for create """
history = self.history_change.__dict__
assert history['before'] == str('{}')
# assert type(history['before']) is str
@pytest.mark.skip(reason="to do")
def test_history_entry_item_change_field_item_pk(self):
""" Ensure history entry field item_pk is the created items pk """
history = self.history_change.__dict__
assert history['item_pk'] == self.item_create.pk
# assert type(history['item_pk']) is int
@pytest.mark.skip(reason="to do")
def test_history_entry_item_change_field_item_class(self):
""" Ensure history entry field item_class is the model name """
history = self.history_change.__dict__
assert history['item_class'] == self.model._meta.model_name
# assert type(history['item_class']) is str

View File

@ -1,538 +0,0 @@
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
class TeamUserPermissions(TestCase):
model = TeamUsers
model_name = 'teamusers'
app_label = 'access'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a device
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.test_team = Team.objects.create(
team_name = 'test_team',
organization = organization,
)
self.team_user = User.objects.create_user(username="test_self.team_user", password="password")
self.item = self.model.objects.create(
team = self.test_team,
user = self.team_user
)
view_permissions = Permission.objects.get(
codename = 'view_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_view_user_anon_denied(self):
""" Check correct permission for view
Attempt to view as anon user
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
response = client.get(url)
assert response.status_code == 302 and response.url.startswith('/account/login')
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_view_no_permission_denied(self):
""" Check correct permission for view
Attempt to view with user missing permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.get(url)
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_view_different_organizaiton_denied(self):
""" Check correct permission for view
Attempt to view with user from different organization
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.get(url)
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_view_has_permission(self):
""" Check correct permission for view
Attempt to view as user with view permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.get(url)
assert response.status_code == 200
def test_team_user_auth_add_user_anon_denied(self):
""" Check correct permission for add
Attempt to add as anon user
"""
client = Client()
url = reverse('Access:_team_user_add', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
response = client.put(url, data={'device': 'device'})
assert response.status_code == 302 and response.url.startswith('/account/login')
# @pytest.mark.skip(reason="ToDO: figure out why fails")
def test_team_user_auth_add_no_permission_denied(self):
""" Check correct permission for add
Attempt to add as user with no permissions
"""
client = Client()
url = reverse('Access:_team_user_add', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
# @pytest.mark.skip(reason="ToDO: figure out why fails")
def test_team_user_auth_add_different_organization_denied(self):
""" Check correct permission for add
attempt to add as user from different organization
"""
client = Client()
url = reverse('Access:_team_user_add', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.post(url, data={'name': 'device', 'organization': self.organization.id})
assert response.status_code == 403
def test_team_user_auth_add_permission_view_denied(self):
""" Check correct permission for add
Attempt to add a user with view permission
"""
client = Client()
url = reverse('Access:_team_user_add', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.view_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
def test_team_user_auth_add_has_permission(self):
""" Check correct permission for add
Attempt to add as user with no permission
"""
client = Client()
url = reverse('Access:_team_user_add', kwargs={'organization_id': self.organization.id, 'pk': self.item.id})
client.force_login(self.add_user)
response = client.post(url, data={'device': 'device', 'organization': self.organization.id})
assert response.status_code == 200
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_user_anon_denied(self):
""" Check correct permission for change
Attempt to change as anon
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 302 and response.url.startswith('/account/login')
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_no_permission_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user without permissions
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_different_organization_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_permission_view_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with view permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_permission_add_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with add permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.add_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_has_permission(self):
""" Check correct permission for change
Make change with user who has change permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.change_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 200
def test_team_user_auth_delete_user_anon_denied(self):
""" Check correct permission for delete
Attempt to delete item as anon user
"""
client = Client()
url = reverse('Access:_team_user_delete', kwargs={'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id})
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 302 and response.url.startswith('/account/login')
def test_team_user_auth_delete_no_permission_denied(self):
""" Check correct permission for delete
Attempt to delete as user with no permissons
"""
client = Client()
url = reverse('Access:_team_user_delete', kwargs={'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
def test_team_user_auth_delete_different_organization_denied(self):
""" Check correct permission for delete
Attempt to delete as user from different organization
"""
client = Client()
url = reverse('Access:_team_user_delete', kwargs={'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
def test_team_user_auth_delete_permission_view_denied(self):
""" Check correct permission for delete
Attempt to delete as user with veiw permission only
"""
client = Client()
url = reverse('Access:_team_user_delete', kwargs={'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id})
client.force_login(self.view_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
def test_team_user_auth_delete_permission_add_denied(self):
""" Check correct permission for delete
Attempt to delete as user with add permission only
"""
client = Client()
url = reverse('Access:_team_user_delete', kwargs={'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id})
client.force_login(self.add_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
def test_team_user_auth_delete_permission_change_denied(self):
""" Check correct permission for delete
Attempt to delete as user with change permission only
"""
client = Client()
url = reverse('Access:_team_user_delete', kwargs={'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id})
client.force_login(self.change_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 403
def test_team_user_auth_delete_has_permission(self):
""" Check correct permission for delete
Delete item as user with delete permission
"""
client = Client()
url = reverse('Access:_team_user_delete',
kwargs={
'organization_id': self.organization.id,
'team_id': self.test_team.id,
'pk': self.item.id
}
)
client.force_login(self.delete_user)
response = client.delete(url, data={'device': 'device'})
assert response.status_code == 302 and response.url == reverse('Access:_team_view',
kwargs={
'organization_id': self.organization.id,
'pk': self.test_team.id
}
)

View File

@ -1,32 +0,0 @@
# from django.conf import settings
# from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
import requests
@pytest.mark.skip(reason="to be written")
def test_team_user_auth_view_api(user):
""" Check correct permission for view """
pass
@pytest.mark.skip(reason="to be written")
def test_team_user_auth_add_api(user):
""" Check correct permission for add """
pass
@pytest.mark.skip(reason="to be written")
def test_team_user_auth_change_api(user):
""" Check correct permission for change """
pass
@pytest.mark.skip(reason="to be written")
def test_team_user_auth_delete_api(user):
""" Check correct permission for delete """
pass

View File

View File

@ -0,0 +1,371 @@
import pytest
import unittest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import Client, TestCase
from rest_framework.relations import Hyperlink
from access.models import Organization, Team, TeamUsers, Permission
class OrganizationAPI(TestCase):
model = Organization
app_namespace = 'API'
url_name = '_api_organization'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a device
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.item = organization
self.url_view_kwargs = {'pk': self.item.id}
self.url_kwargs = {'pk': self.item.id}
view_permissions = Permission.objects.get(
codename = 'view_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.view_user)
response = client.get(url)
self.api_data = response.data
def test_api_field_exists_id(self):
""" Test for existance of API Field
id field must exist
"""
assert 'id' in self.api_data
def test_api_field_type_id(self):
""" Test for type for API Field
id field must be int
"""
assert type(self.api_data['id']) is int
def test_api_field_exists_name(self):
""" Test for existance of API Field
name field must exist
"""
assert 'name' in self.api_data
def test_api_field_type_name(self):
""" Test for type for API Field
name field must be str
"""
assert type(self.api_data['name']) is str
def test_api_field_exists_teams(self):
""" Test for existance of API Field
teams field must exist
"""
assert 'teams' in self.api_data
def test_api_field_type_teams(self):
""" Test for type for API Field
teams field must be list
"""
assert type(self.api_data['teams']) is list
def test_api_field_exists_url(self):
""" Test for existance of API Field
url field must exist
"""
assert 'url' in self.api_data
def test_api_field_type_url(self):
""" Test for type for API Field
url field must be str
"""
assert type(self.api_data['url']) is Hyperlink
def test_api_field_exists_teams_id(self):
""" Test for existance of API Field
teams.id field must exist
"""
assert 'id' in self.api_data['teams'][0]
def test_api_field_type_teams_id(self):
""" Test for type for API Field
teams.id field must be int
"""
assert type(self.api_data['teams'][0]['id']) is int
def test_api_field_exists_teams_team_name(self):
""" Test for existance of API Field
teams.team_name field must exist
"""
assert 'team_name' in self.api_data['teams'][0]
def test_api_field_type_teams_team_name(self):
""" Test for type for API Field
teams.team_name field must be string
"""
assert type(self.api_data['teams'][0]['team_name']) is str
def test_api_field_exists_teams_permissions(self):
""" Test for existance of API Field
teams.permissions field must exist
"""
assert 'permissions' in self.api_data['teams'][0]
def test_api_field_type_teams_permissions(self):
""" Test for type for API Field
teams.permissions field must be list
"""
assert type(self.api_data['teams'][0]['permissions']) is list
def test_api_field_exists_teams_permissions_url(self):
""" Test for existance of API Field
teams.permissions_url field must exist
"""
assert 'permissions_url' in self.api_data['teams'][0]
def test_api_field_type_teams_permissions_url(self):
""" Test for type for API Field
teams.permissions_url field must be url
"""
assert type(self.api_data['teams'][0]['permissions_url']) is str
def test_api_field_exists_teams_url(self):
""" Test for existance of API Field
teams.url field must exist
"""
assert 'url' in self.api_data['teams'][0]
def test_api_field_type_teams_url(self):
""" Test for type for API Field
teams.url field must be url
"""
assert type(self.api_data['teams'][0]['url']) is str
def test_api_field_exists_teams_permissions_id(self):
""" Test for existance of API Field
teams.permissions.id field must exist
"""
assert 'id' in self.api_data['teams'][0]['permissions'][0]
def test_api_field_type_teams_permissions_id(self):
""" Test for type for API Field
teams.permissions.id field must be int
"""
assert type(self.api_data['teams'][0]['permissions'][0]['id']) is int
def test_api_field_exists_teams_permissions_name(self):
""" Test for existance of API Field
teams.permissions.name field must exist
"""
assert 'name' in self.api_data['teams'][0]['permissions'][0]
def test_api_field_type_teams_permissions_name(self):
""" Test for type for API Field
teams.permissions.name field must be str
"""
assert type(self.api_data['teams'][0]['permissions'][0]['name']) is str
def test_api_field_exists_teams_permissions_codename(self):
""" Test for existance of API Field
teams.permissions.codename field must exist
"""
assert 'codename' in self.api_data['teams'][0]['permissions'][0]
def test_api_field_type_teams_permissions_codename(self):
""" Test for type for API Field
teams.permissions.codename field must be str
"""
assert type(self.api_data['teams'][0]['permissions'][0]['codename']) is str
def test_api_field_exists_teams_permissions_content_type(self):
""" Test for existance of API Field
teams.permissions.content_type field must exist
"""
assert 'content_type' in self.api_data['teams'][0]['permissions'][0]
def test_api_field_type_teams_permissions_content_type(self):
""" Test for type for API Field
teams.permissions.content_type field must be dict
"""
assert type(self.api_data['teams'][0]['permissions'][0]['content_type']) is dict
def test_api_field_exists_teams_permissions_content_type_id(self):
""" Test for existance of API Field
teams.permissions.content_type.id field must exist
"""
assert 'id' in self.api_data['teams'][0]['permissions'][0]['content_type']
def test_api_field_type_teams_permissions_content_type_id(self):
""" Test for type for API Field
teams.permissions.content_type.id field must be int
"""
assert type(self.api_data['teams'][0]['permissions'][0]['content_type']['id']) is int
def test_api_field_exists_teams_permissions_content_type_app_label(self):
""" Test for existance of API Field
teams.permissions.content_type.app_label field must exist
"""
assert 'app_label' in self.api_data['teams'][0]['permissions'][0]['content_type']
def test_api_field_type_teams_permissions_content_type_app_label(self):
""" Test for type for API Field
teams.permissions.content_type.app_label field must be str
"""
assert type(self.api_data['teams'][0]['permissions'][0]['content_type']['app_label']) is str
def test_api_field_exists_teams_permissions_content_type_model(self):
""" Test for existance of API Field
teams.permissions.content_type.model field must exist
"""
assert 'model' in self.api_data['teams'][0]['permissions'][0]['content_type']
def test_api_field_type_teams_permissions_content_type_model(self):
""" Test for type for API Field
teams.permissions.content_type.model field must be str
"""
assert type(self.api_data['teams'][0]['permissions'][0]['content_type']['model']) is str

View File

@ -0,0 +1,214 @@
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
from access.tests.abstract.model_permissions_organization_manager import OrganizationManagerModelPermissionChange, OrganizationManagerModelPermissionView
from app.tests.abstract.model_permissions import ModelPermissionsView, ModelPermissionsChange
class OrganizationPermissions(
TestCase,
ModelPermissionsView,
ModelPermissionsChange,
OrganizationManagerModelPermissionChange,
OrganizationManagerModelPermissionView,
):
model = Organization
app_namespace = 'Access'
url_name_view = '_organization_view'
# url_name_add = '_organization_add'
url_name_change = '_organization_view'
# url_name_delete = '_organization_delete'
# url_delete_response = reverse('ITAM:Operating Systems')
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a device
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(
name='test_different_organization'
)
self.different_organization = different_organization
# self.item = self.model.objects.create(
# organization=organization,
# name = 'deviceone'
# )
self.item = organization
self.url_view_kwargs = {'pk': self.item.id}
# self.url_add_kwargs = {'pk': self.item.id}
# self.add_data = {'operating_system': 'operating_system', 'organization': self.organization.id}
self.url_change_kwargs = {'pk': self.item.id}
self.change_data = {'operating_system': 'operating_system', 'organization': self.organization.id}
# self.url_delete_kwargs = {'pk': self.item.id}
# self.delete_data = {'operating_system': 'operating_system', 'organization': self.organization.id}
view_permissions = Permission.objects.get(
codename = 'view_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
self.user_is_organization_manager = User.objects.create_user(
username="test_org_manager",
password="password"
)
self.organization.manager = self.user_is_organization_manager
self.organization.save()
self.different_organization_is_manager = User.objects.create_user(
username="test_org_manager_different_org",
password="password"
)
self.different_organization.manager = self.different_organization_is_manager
self.different_organization.save()

View File

@ -0,0 +1,239 @@
import pytest
import unittest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import Client, TestCase
from access.models import Organization, Team, TeamUsers, Permission
from api.tests.abstract.api_permissions import APIPermissionChange, APIPermissionView
class OrganizationPermissionsAPI(TestCase, APIPermissionChange, APIPermissionView):
model = Organization
model_name = 'organization'
app_label = 'access'
app_namespace = 'API'
url_name = '_api_organization'
url_list = '_api_orgs'
change_data = {'name': 'device'}
# delete_data = {'device': 'device'}
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a device
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.item = organization
self.url_view_kwargs = {'pk': self.item.id}
self.url_kwargs = {'pk': self.item.id}
# self.add_data = {'name': 'device', 'organization': self.organization.id}
view_permissions = Permission.objects.get(
codename = 'view_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.super_user = User.objects.create_user(username="super_user", password="password", is_superuser=True)
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
def test_add_is_prohibited_anon_user(self):
""" Ensure Organization cant be created
Attempt to create organization as anon user
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_list)
# client.force_login(self.add_user)
response = client.post(url, data={'name': 'should not create'}, content_type='application/json')
assert response.status_code == 401
def test_add_is_prohibited_diff_org_user(self):
""" Ensure Organization cant be created
Attempt to create organization as user with different org permissions.
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_list)
client.force_login(self.different_organization_user)
response = client.post(url, data={'name': 'should not create'}, content_type='application/json')
assert response.status_code == 405
def test_add_is_prohibited_super_user(self):
""" Ensure Organization cant be created
Attempt to create organization as user who is super user
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_list)
client.force_login(self.super_user)
response = client.post(url, data={'name': 'should not create'}, content_type='application/json')
assert response.status_code == 405
def test_add_is_prohibited_user_same_org(self):
""" Ensure Organization cant be created
Attempt to create organization as user with permission
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_list)
client.force_login(self.add_user)
response = client.post(url, data={'name': 'should not create'}, content_type='application/json')
assert response.status_code == 405

View File

@ -12,87 +12,6 @@ from core.models.history import History
from access.models import Organization
# @pytest.mark.skip(reason="to be written")
# def test_history_auth_view():
# """ User requires Permission view_history """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_create():
# """ History row must be added to history table on create """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_update():
# """ History row must be added to history table on updatej """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_delete():
# """ History row must be added to history table on delete """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_create():
# """ History row must be added to history table on create
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_update():
# """ History row must be added to history table on update
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_operating_system_delete():
# """ History row must be added to history table on delete
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_create():
# """ History row must be added to history table on create
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_update():
# """ History row must be added to history table on update
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
# @pytest.mark.skip(reason="to be written")
# def test_history_device_software_delete():
# """ History row must be added to history table on delete
# Must also have populated parent_item_pk and parent_item_class columns
# """
# pass
class OrganizationHistory(TestCase):
@ -130,8 +49,24 @@ class OrganizationHistory(TestCase):
item_class = self.model._meta.model_name,
)
self.item_delete = self.model.objects.create(
name = 'test_item_delete_' + self.model_name,
)
self.item_delete.delete()
self.history_delete = History.objects.filter(
item_pk = self.item_delete.pk,
item_class = self.model._meta.model_name,
)
self.history_delete_children = History.objects.filter(
item_parent_pk = self.item_delete.pk,
item_parent_class = self.model._meta.model_name,
)
# field type testing to be done as part of model testing
def test_history_entry_item_add_field_action(self):
""" Ensure action is "add" for item creation """
@ -185,7 +120,6 @@ class OrganizationHistory(TestCase):
# field type testing to be done as part of model testing
def test_history_entry_item_change_field_action(self):
""" Ensure action is "add" for item creation """
@ -232,3 +166,22 @@ class OrganizationHistory(TestCase):
# assert type(history['item_class']) is str
################################## Delete ##################################
def test_device_history_entry_delete(self):
""" When an item is deleted, it's history entries must be removed """
assert self.history_delete.exists() is False
def test_device_history_entry_children_delete(self):
""" When an item is deleted, it's history entries must be removed """
assert self.history_delete_children.exists() is False

View File

@ -14,7 +14,7 @@ from access.models import Organization, Team, TeamUsers, Permission
from core.models.history import History
class DeviceHistoryPermissions(TestCase):
class OrganizationHistoryPermissions(TestCase):
item_model = Organization

View File

@ -0,0 +1,21 @@
import pytest
import unittest
import requests
from django.test import TestCase
from app.tests.abstract.models import ModelDisplay, ModelIndex
class OrganizationViews(
TestCase,
ModelDisplay,
ModelIndex
):
display_module = 'access.views.organization'
display_view = 'View'
index_module = display_module
index_view = 'IndexView'

View File

@ -0,0 +1,70 @@
import pytest
import unittest
from django.test import TestCase, Client
from access.models import Organization, Team, TeamUsers, Permission
from app.tests.abstract.models import TenancyModel
class TeamModel(
TestCase,
TenancyModel
):
model = Team
@classmethod
def setUpTestData(self):
""" Setup Test
"""
self.parent_item = Organization.objects.create(name='test_org')
different_organization = Organization.objects.create(name='test_different_organization')
self.item = self.model.objects.create(
organization=self.parent_item,
name = 'teamone'
)
def test_model_has_property_parent_object(self):
""" Check if model contains 'parent_object'
This is a required property for all models that have a parent
"""
assert hasattr(self.model, 'parent_object')
def test_model_property_parent_object_returns_object(self):
""" Check if model contains 'parent_object'
This is a required property for all models that have a parent
"""
assert self.item.parent_object is self.parent_item
@pytest.mark.skip(reason="to be written")
def test_function_save_attributes():
""" Ensure save Attributes function match django default
the save method is overridden. the function attributes must match default django method
"""
pass
@pytest.mark.skip(reason="uses Django group manager")
def test_attribute_is_type_objects(self):
pass
@pytest.mark.skip(reason="uses Django group manager")
def test_model_class_tenancy_manager_function_get_queryset_called(self):
pass

View File

@ -0,0 +1,294 @@
import pytest
import unittest
import requests
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import Client, TestCase
from rest_framework.relations import Hyperlink
from access.models import Organization, Team, TeamUsers, Permission
# from api.tests.abstract.api_permissions import APIPermissions
class TeamAPI(TestCase):
model = Team
app_namespace = 'API'
url_name = '_api_team'
# url_list = '_api_organization_teams'
# change_data = {'name': 'device'}
# delete_data = {'device': 'device'}
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a team
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.item = self.model.objects.create(
organization=organization,
team_name = 'teamone'
)
self.url_kwargs = {'organization_id': self.organization.id}
self.url_view_kwargs = {'organization_id': self.organization.id, 'group_ptr_id': self.item.id}
self.add_data = {'team_name': 'team_post'}
view_permissions = Permission.objects.get(
codename = 'view_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
# view_team = Team.objects.create(
# team_name = 'view_team',
# organization = organization,
# )
self.item.permissions.set([view_permissions])
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = self.item,
user = self.view_user
)
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.view_user)
response = client.get(url)
self.api_data = response.data
def test_api_field_exists_id(self):
""" Test for existance of API Field
id field must exist
"""
assert 'id' in self.api_data
def test_api_field_type_id(self):
""" Test for type for API Field
id field must be int
"""
assert type(self.api_data['id']) is int
def test_api_field_exists_team_name(self):
""" Test for existance of API Field
team_name field must exist
"""
assert 'team_name' in self.api_data
def test_api_field_type_name(self):
""" Test for type for API Field
team_name field must be str
"""
assert type(self.api_data['team_name']) is str
def test_api_field_exists_url(self):
""" Test for existance of API Field
url field must exist
"""
assert 'url' in self.api_data
def test_api_field_type_url(self):
""" Test for type for API Field
url field must be str
"""
assert type(self.api_data['url']) is str
def test_api_field_exists_permissions(self):
""" Test for existance of API Field
permissions field must exist
"""
assert 'permissions' in self.api_data
def test_api_field_type_permissions(self):
""" Test for type for API Field
url field must be list
"""
assert type(self.api_data['permissions']) is list
def test_api_field_exists_permissions_id(self):
""" Test for existance of API Field
permissions.id field must exist
"""
assert 'id' in self.api_data['permissions'][0]
def test_api_field_type_permissions_id(self):
""" Test for type for API Field
permissions.id field must be int
"""
assert type(self.api_data['permissions'][0]['id']) is int
def test_api_field_exists_permissions_name(self):
""" Test for existance of API Field
permissions.name field must exist
"""
assert 'name' in self.api_data['permissions'][0]
def test_api_field_type_permissions_name(self):
""" Test for type for API Field
permissions.name field must be str
"""
assert type(self.api_data['permissions'][0]['name']) is str
def test_api_field_exists_permissions_codename(self):
""" Test for existance of API Field
permissions.codename field must exist
"""
assert 'codename' in self.api_data['permissions'][0]
def test_api_field_type_permissions_codename(self):
""" Test for type for API Field
permissions.codename field must be str
"""
assert type(self.api_data['permissions'][0]['codename']) is str
def test_api_field_exists_permissions_content_type(self):
""" Test for existance of API Field
permissions.content_type field must exist
"""
assert 'content_type' in self.api_data['permissions'][0]
def test_api_field_type_permissions_content_type(self):
""" Test for type for API Field
permissions.content_type field must be dict
"""
assert type(self.api_data['permissions'][0]['content_type']) is dict
def test_api_field_exists_permissions_content_type_id(self):
""" Test for existance of API Field
permissions.content_type.id field must exist
"""
assert 'id' in self.api_data['permissions'][0]['content_type']
def test_api_field_type_permissions_content_type_id(self):
""" Test for type for API Field
permissions.content_type.id field must be int
"""
assert type(self.api_data['permissions'][0]['content_type']['id']) is int
def test_api_field_exists_permissions_content_type_app_label(self):
""" Test for existance of API Field
permissions.content_type.app_label field must exist
"""
assert 'app_label' in self.api_data['permissions'][0]['content_type']
def test_api_field_type_permissions_content_type_app_label(self):
""" Test for type for API Field
permissions.content_type.app_label field must be str
"""
assert type(self.api_data['permissions'][0]['content_type']['app_label']) is str
def test_api_field_exists_permissions_content_type_model(self):
""" Test for existance of API Field
permissions.content_type.model field must exist
"""
assert 'model' in self.api_data['permissions'][0]['content_type']
def test_api_field_type_permissions_content_type_model(self):
""" Test for type for API Field
permissions.content_type.model field must be str
"""
assert type(self.api_data['permissions'][0]['content_type']['model']) is str

View File

@ -0,0 +1,79 @@
import pytest
import unittest
import requests
from django.test import TestCase, Client
from access.models import Organization
from core.models.history import History
from core.tests.abstract.history_entry import HistoryEntry
from core.tests.abstract.history_entry_child_model import HistoryEntryChildItem
from access.models import Team
from django.contrib.auth.models import Group
class TeamHistory(TestCase, HistoryEntry, HistoryEntryChildItem):
model = Team
@classmethod
def setUpTestData(self):
""" Setup Test """
organization = Organization.objects.create(name='test_org')
self.organization = organization
self.item_parent = organization
self.item_create = self.model.objects.create(
team_name = 'test_item_' + self.model._meta.model_name,
organization = self.organization
)
self.history_create = History.objects.get(
action = History.Actions.ADD[0],
item_pk = self.item_create.pk,
item_class = self.model._meta.model_name,
)
self.item_change = self.item_create
self.item_change.team_name = 'test_item_' + self.model._meta.model_name + '_changed'
self.item_change.save()
self.field_after_expected_value = '{"name": "test_org_' + self.item_change.team_name + '", "team_name": "' + self.item_change.team_name + '"}'
self.history_change = History.objects.get(
action = History.Actions.UPDATE[0],
item_pk = self.item_change.pk,
item_class = self.model._meta.model_name,
)
debug = Group.objects.all()
self.item_delete = self.model.objects.create(
team_name = 'test_item_delete_' + self.model._meta.model_name,
organization = self.organization
)
self.deleted_pk = self.item_delete.pk
self.item_delete.delete()
self.history_delete = History.objects.get(
action = History.Actions.DELETE[0],
item_pk = self.deleted_pk,
item_class = self.model._meta.model_name,
)
self.history_delete_children = History.objects.filter(
item_parent_pk = self.deleted_pk,
item_parent_class = self.item_parent._meta.model_name,
)

View File

@ -0,0 +1,210 @@
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
from access.tests.abstract.model_permissions_organization_manager import OrganizationManagerModelPermissions
from app.tests.abstract.model_permissions import ModelPermissions
class TeamPermissions(
TestCase,
ModelPermissions,
OrganizationManagerModelPermissions,
):
model = Team
app_namespace = 'Access'
url_name_view = '_team_view'
url_name_add = '_team_add'
url_name_change = '_team_view'
url_name_delete = '_team_delete'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a team
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.different_organization = different_organization
self.item = self.model.objects.create(
organization=organization,
name = 'teamone'
)
self.url_view_kwargs = {'organization_id': self.organization.id, 'pk': self.item.id}
self.url_add_kwargs = {'pk': self.organization.id}
self.add_data = {'team': 'team'}
self.url_change_kwargs = {'organization_id': self.organization.id, 'pk': self.item.id}
self.change_data = {'team': 'team'}
self.url_delete_kwargs = {'organization_id': self.organization.id, 'pk': self.item.id}
self.delete_data = {'team': 'team'}
self.url_delete_response = reverse('Access:_organization_view', kwargs={'pk': self.organization.id})
view_permissions = Permission.objects.get(
codename = 'view_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
self.user_is_organization_manager = User.objects.create_user(
username="test_org_manager",
password="password"
)
self.organization.manager = self.user_is_organization_manager
self.organization.save()
self.different_organization_is_manager = User.objects.create_user(
username="test_org_manager_different_org",
password="password"
)
self.different_organization.manager = self.different_organization_is_manager
self.different_organization.save()

View File

@ -0,0 +1,175 @@
import pytest
import unittest
import requests
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from access.models import Organization, Team, TeamUsers, Permission
from api.tests.abstract.api_permissions import APIPermissions
class TeamPermissionsAPI(TestCase, APIPermissions):
model = Team
app_namespace = 'API'
url_name = '_api_team'
url_list = '_api_organization_teams'
change_data = {'name': 'device'}
delete_data = {'device': 'device'}
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a team
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.item = self.model.objects.create(
organization=organization,
name = 'teamone'
)
self.url_kwargs = {'organization_id': self.organization.id}
self.url_view_kwargs = {'organization_id': self.organization.id, 'group_ptr_id': self.item.id}
self.add_data = {'team_name': 'team_post'}
view_permissions = Permission.objects.get(
codename = 'view_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)

View File

@ -0,0 +1,29 @@
import pytest
import unittest
import requests
from django.test import TestCase
from app.tests.abstract.models import ModelAdd, ModelDelete, ModelDisplay
class TeamViews(
TestCase,
ModelAdd,
ModelDelete,
ModelDisplay,
):
add_module = 'access.views.team'
add_view = 'Add'
# change_module = add_module
# change_view = 'Change'
delete_module = add_module
delete_view = 'Delete'
display_module = add_module
display_view = 'View'

View File

@ -0,0 +1,56 @@
import pytest
import unittest
from django.test import TestCase, Client
from django.contrib.auth.models import User
from access.models import Organization, Team, TeamUsers, Permission
class TeamUsersModel(TestCase):
model = TeamUsers
@classmethod
def setUpTestData(self):
""" Setup Test
"""
organization = Organization.objects.create(name='test_org')
different_organization = Organization.objects.create(name='test_different_organization')
self.parent_item = Team.objects.create(
team_name = 'test_team',
organization = organization,
)
team_user = User.objects.create_user(username="test_self.team_user", password="password")
self.item = self.model.objects.create(
team = self.parent_item,
user = team_user
)
def test_model_has_property_parent_object(self):
""" Check if model contains 'parent_object'
This is a required property for all models that have a parent
"""
assert hasattr(self.model, 'parent_object')
def test_model_property_parent_object_returns_object(self):
""" Check if model contains 'parent_object'
This is a required property for all models that have a parent
"""
assert self.item.parent_object == self.parent_item

View File

@ -0,0 +1,92 @@
import pytest
import unittest
import requests
from django.contrib.auth.models import User
from django.test import TestCase, Client
from access.models import Organization
from core.models.history import History
from core.tests.abstract.history_entry import HistoryEntry
from core.tests.abstract.history_entry_child_model import HistoryEntryChildItem
from access.models import Team, TeamUsers
class TeamUsersHistory(TestCase, HistoryEntry, HistoryEntryChildItem):
model = TeamUsers
model_name = 'teamusers'
@classmethod
def setUpTestData(self):
""" Setup Test """
organization = Organization.objects.create(name='test_org')
self.organization = organization
self.item_parent = Team.objects.create(
team_name = 'test_item_' + self.model._meta.model_name,
organization = self.organization
)
self.user = User.objects.create(
username = 'test_item_' + self.model._meta.model_name,
password = 'a random password'
)
self.item_create = self.model.objects.create(
user = self.user,
team = self.item_parent
)
self.history_create = History.objects.get(
action = History.Actions.ADD[0],
item_pk = self.item_create.pk,
item_class = self.model._meta.model_name,
)
self.item_change = self.item_create
self.item_change.manager = True
self.item_change.save()
self.field_after_expected_value = '{"manager": true}'
self.history_change = History.objects.get(
action = History.Actions.UPDATE[0],
item_pk = self.item_change.pk,
item_class = self.model._meta.model_name,
)
self.user_delete = User.objects.create(
username = 'test_item_delete' + self.model._meta.model_name,
password = 'a random password'
)
self.item_delete = self.model.objects.create(
user = self.user_delete,
team = self.item_parent
)
self.deleted_pk = self.item_delete.pk
self.item_delete.delete()
self.history_delete = History.objects.get(
action = History.Actions.DELETE[0],
item_pk = self.deleted_pk,
item_class = self.model._meta.model_name,
)
self.history_delete_children = History.objects.filter(
item_parent_pk = self.deleted_pk,
item_parent_class = self.item_parent._meta.model_name,
)

View File

@ -0,0 +1,325 @@
# from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
import requests
from access.models import Organization, Team, TeamUsers, Permission
from access.tests.abstract.model_permissions_organization_manager import OrganizationManagerModelPermissionAdd, OrganizationManagerModelPermissionDelete
from app.tests.abstract.model_permissions import ModelPermissionsAdd, ModelPermissionsChange, ModelPermissionsDelete
class TeamUserPermissions(
TestCase,
ModelPermissionsAdd,
ModelPermissionsDelete,
OrganizationManagerModelPermissionAdd,
OrganizationManagerModelPermissionDelete
):
model = TeamUsers
app_namespace = 'Access'
url_name_view = '_team_user_view'
url_name_add = '_team_user_add'
url_name_change = '_team_user_view'
url_name_delete = '_team_user_delete'
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user and item
. create an organization that is different to item
2. Create a device
3. create teams with each permission: view, add, change, delete
4. create a user per team
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
different_organization = Organization.objects.create(name='test_different_organization')
self.different_organization = different_organization
self.test_team = Team.objects.create(
team_name = 'test_team',
organization = organization,
)
self.team_user = User.objects.create_user(username="test_self.team_user", password="password")
self.item = self.model.objects.create(
team = self.test_team,
user = self.team_user
)
self.url_view_kwargs = {'pk': self.item.id}
self.url_add_kwargs = {'organization_id': self.organization.id, 'pk': self.item.id}
self.add_data = {'operating_system': 'operating_system', 'organization': self.organization.id}
self.url_change_kwargs = {'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id}
self.change_data = {'operating_system': 'operating_system', 'organization': self.organization.id}
self.url_delete_kwargs = {'organization_id': self.organization.id, 'team_id': self.item.team.id, 'pk': self.item.id}
self.delete_data = {'operating_system': 'operating_system', 'organization': self.organization.id}
self.url_delete_response = reverse('Access:_team_view',
kwargs={
'organization_id': self.organization.id,
'pk': self.test_team.id
}
)
view_permissions = Permission.objects.get(
codename = 'view_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
view_team = Team.objects.create(
team_name = 'view_team',
organization = organization,
)
view_team.permissions.set([view_permissions])
add_permissions = Permission.objects.get(
codename = 'add_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
change_permissions = Permission.objects.get(
codename = 'change_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
change_team = Team.objects.create(
team_name = 'change_team',
organization = organization,
)
change_team.permissions.set([change_permissions])
delete_permissions = Permission.objects.get(
codename = 'delete_' + self.model._meta.model_name,
content_type = ContentType.objects.get(
app_label = self.model._meta.app_label,
model = self.model._meta.model_name,
)
)
delete_team = Team.objects.create(
team_name = 'delete_team',
organization = organization,
)
delete_team.permissions.set([delete_permissions])
self.no_permissions_user = User.objects.create_user(username="test_no_permissions", password="password")
self.view_user = User.objects.create_user(username="test_user_view", password="password")
teamuser = TeamUsers.objects.create(
team = view_team,
user = self.view_user
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
self.change_user = User.objects.create_user(username="test_user_change", password="password")
teamuser = TeamUsers.objects.create(
team = change_team,
user = self.change_user
)
self.delete_user = User.objects.create_user(username="test_user_delete", password="password")
teamuser = TeamUsers.objects.create(
team = delete_team,
user = self.delete_user
)
self.different_organization_user = User.objects.create_user(username="test_different_organization_user", password="password")
different_organization_team = Team.objects.create(
team_name = 'different_organization_team',
organization = different_organization,
)
different_organization_team.permissions.set([
view_permissions,
add_permissions,
change_permissions,
delete_permissions,
])
TeamUsers.objects.create(
team = different_organization_team,
user = self.different_organization_user
)
self.user_is_organization_manager = User.objects.create_user(
username="test_org_manager",
password="password"
)
self.organization.manager = self.user_is_organization_manager
self.organization.save()
self.different_organization_is_manager = User.objects.create_user(
username="test_org_manager_different_org",
password="password"
)
self.different_organization.manager = self.different_organization_is_manager
self.different_organization.save()
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_user_anon_denied(self):
""" Check correct permission for change
Attempt to change as anon
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
response = client.patch(url, data={'device': 'device'})
assert response.status_code == 302 and response.url.startswith('/account/login')
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_no_permission_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user without permissions
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.no_permissions_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_different_organization_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.different_organization_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_permission_view_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with view permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.view_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_permission_add_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with add permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.add_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 403
@pytest.mark.skip(reason="feature does not exist")
def test_team_user_auth_change_has_permission(self):
""" Check correct permission for change
Make change with user who has change permission
"""
client = Client()
url = reverse('Access:_team_user_view', kwargs={'pk': self.item.id})
client.force_login(self.change_user)
response = client.post(url, data={'device': 'device'})
assert response.status_code == 200

View File

@ -0,0 +1,30 @@
import pytest
import unittest
import requests
from django.test import TestCase
from app.tests.abstract.models import AddView, DeleteView
class TeamUserViews(
TestCase,
AddView,
DeleteView
):
add_module = 'access.views.user'
add_view = 'Add'
# change_module = add_module
# change_view = 'GroupView'
delete_module = add_module
delete_view = 'Delete'
# display_module = add_module
# display_view = 'GroupView'
# index_module = add_module
# index_view = 'GroupIndexView'

View File

@ -0,0 +1,93 @@
import pytest
import unittest
from django.test import TestCase
from access.models import TenancyObject, TenancyManager
from core.mixin.history_save import SaveHistory
from unittest.mock import patch
class TenancyManagerTests(TestCase):
item = TenancyManager
def test_has_attribute_get_queryset(self):
""" Field organization exists """
assert hasattr(self.item, 'get_queryset')
def test_is_function_get_queryset(self):
""" Attribute 'get_organization' is a function """
assert callable(self.item.get_queryset)
class TenancyObjectTests(TestCase):
item = TenancyObject
def test_class_inherits_save_history(self):
""" Confirm class inheritence
TenancyObject must inherit SaveHistory
"""
assert issubclass(TenancyObject, SaveHistory)
def test_has_attribute_organization(self):
""" Field organization exists """
assert hasattr(self.item, 'organization')
def test_has_attribute_is_global(self):
""" Field organization exists """
assert hasattr(self.item, 'is_global')
def test_has_attribute_model_notes(self):
""" Field organization exists """
assert hasattr(self.item, 'model_notes')
def test_has_attribute_get_organization(self):
""" Function 'get_organization' Exists """
assert hasattr(self.item, 'get_organization')
def test_is_function_get_organization(self):
""" Attribute 'get_organization' is a function """
assert callable(self.item.get_organization)
@pytest.mark.skip(reason="figure out how to test abstract class")
def test_has_attribute_objects(self):
""" Attribute Check
attribute `objects` must be set to `access.models.TenancyManager()`
"""
assert 'objects' in self.item
@pytest.mark.skip(reason="figure out how to test abstract class")
def test_attribute_not_none_objects(self):
""" Attribute Check
attribute `objects` must be set to `access.models.TenancyManager()`
"""
assert self.item.objects is not None

View File

@ -1,13 +1,19 @@
from django.contrib.auth import decorators as auth_decorator
from django.db.models import Q
from django.utils.decorators import method_decorator
from django.views import generic
from access.mixin import *
from access.models import *
from access.forms.organization import OrganizationForm
from core.views.common import ChangeView, IndexView
class IndexView(OrganizationPermission, generic.ListView):
class IndexView(IndexView):
model = Organization
permission_required = [
'access.view_organization'
]
@ -15,6 +21,14 @@ class IndexView(OrganizationPermission, generic.ListView):
context_object_name = "organization_list"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['content_title'] = 'Organizations'
return context
def get_queryset(self):
if self.request.user.is_superuser:
@ -23,18 +37,35 @@ class IndexView(OrganizationPermission, generic.ListView):
else:
return Organization.objects.filter(pk__in=self.user_organizations())
return Organization.objects.filter(
Q(pk__in=self.user_organizations())
|
Q(manager=self.request.user.id)
)
class View(OrganizationPermission, generic.UpdateView):
class View(ChangeView):
context_object_name = "organization"
form_class = OrganizationForm
model = Organization
permission_required = [
'access.view_organization',
'access.change_organization',
]
template_name = "access/organization.html.j2"
fields = ["name", 'id']
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
if not self.permission_check(request, [ 'access.view_organization' ]):
raise PermissionDenied('You are not part of this organization')
return super().get(request, *args, **kwargs)
def get_success_url(self, **kwargs):
@ -48,19 +79,28 @@ class View(OrganizationPermission, generic.UpdateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['organization'] = Organization.objects.get(pk=self.kwargs['pk'])
context['model_docs_path'] = self.model._meta.app_label + '/' + self.model._meta.model_name + '/'
context['teams'] = Team.objects.filter(organization=self.kwargs['pk'])
context['model_pk'] = self.kwargs['pk']
context['model_name'] = self.model._meta.verbose_name.replace(' ', '')
context['content_title'] = 'Organization - ' + context[self.context_object_name].name
return context
@method_decorator(auth_decorator.permission_required("access.change_organization", raise_exception=True))
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
if not self.permission_check(request, [ 'access.change_organization' ]):
raise PermissionDenied('You are not part of this organization')
return super().post(request, *args, **kwargs)

View File

@ -2,32 +2,49 @@ from django.contrib.auth import decorators as auth_decorator
from django.contrib.auth.models import Permission
from django.utils.decorators import method_decorator
from django.urls import reverse
from django.views import generic
from access.forms.team import TeamForm, TeamFormAdd
from access.models import Team, TeamUsers, Organization
from access.mixin import *
from core.views.common import AddView, ChangeView, DeleteView
class View(OrganizationPermission, generic.UpdateView):
class View(ChangeView):
context_object_name = "team"
form_class = TeamForm
model = Team
permission_required = [
'access.view_team',
'access.change_team',
]
template_name = 'access/team.html.j2'
fields = [
"name",
'id',
'organization',
'permissions'
]
def get(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
if not self.permission_check(request, [ 'access.view_team' ]):
raise PermissionDenied('You are not part of this organization')
return super().get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['model_docs_path'] = self.model._meta.app_label + '/' + self.model._meta.model_name + '/'
organization = Organization.objects.get(pk=self.kwargs['organization_id'])
context['organization'] = organization
@ -37,7 +54,6 @@ class View(OrganizationPermission, generic.UpdateView):
teamusers = TeamUsers.objects.filter(team=self.kwargs['pk'])
context['teamusers'] = teamusers
context['permissions'] = Permission.objects.filter()
context['model_pk'] = self.kwargs['pk']
context['model_name'] = self.model._meta.verbose_name.replace(' ', '')
@ -48,22 +64,33 @@ class View(OrganizationPermission, generic.UpdateView):
return reverse('Access:_team_view', args=(self.kwargs['organization_id'], self.kwargs['pk'],))
@method_decorator(auth_decorator.permission_required("access.change_team", raise_exception=True))
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return self.handle_no_permission()
if not self.permission_check(request, [ 'access.change_team' ]):
raise PermissionDenied('You are not part of this organization')
return super().post(request, *args, **kwargs)
class Add(OrganizationPermission, generic.CreateView):
class Add(AddView):
form_class = TeamFormAdd
model = Team
parent_model = Organization
permission_required = [
'access.add_team',
]
template_name = 'form.html.j2'
fields = [
'team_name',
]
def form_valid(self, form):
form.instance.organization = Organization.objects.get(pk=self.kwargs['pk'])
@ -77,8 +104,6 @@ class Add(OrganizationPermission, generic.CreateView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['model_pk'] = self.kwargs['pk']
context['model_name'] = self.model._meta.verbose_name.replace(' ', '')
context['content_title'] = 'Add Team'
@ -86,7 +111,7 @@ class Add(OrganizationPermission, generic.CreateView):
class Delete(OrganizationPermission, generic.DeleteView):
class Delete(DeleteView):
model = Team
permission_required = [
'access.delete_team'

View File

@ -1,24 +1,27 @@
from django.contrib.auth import decorators as auth_decorator
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import generic
from access.mixin import OrganizationPermission
from access.forms.team_users import TeamUsersForm
from access.models import Team, TeamUsers
from core.views.common import AddView, DeleteView
class Add(OrganizationPermission, generic.CreateView):
class Add(AddView):
context_object_name = "teamuser"
form_class = TeamUsersForm
model = TeamUsers
parent_model = Team
permission_required = [
'access.view_team',
'access.add_teamusers'
]
template_name = 'form.html.j2'
fields = [
'user',
'manager'
]
def form_valid(self, form):
@ -46,7 +49,7 @@ class Add(OrganizationPermission, generic.CreateView):
return context
class Delete(OrganizationPermission, generic.DeleteView):
class Delete(DeleteView):
model = TeamUsers
permission_required = [
'access.delete_teamusers'

79
app/api/auth.py Normal file
View File

@ -0,0 +1,79 @@
import datetime
from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication, get_authorization_header
from api.models.tokens import AuthToken
class TokenAuthentication(BaseAuthentication):
""" API Token Authentication
Provides the ability to use the API by using a token to authenticate.
"""
def authenticate_header(self, request):
return 'Token'
def authenticate(self, request):
""" Authentication the API session using the supplied token
Args:
request (object): API Request Object
Raises:
exceptions.AuthenticationFailed: 'Token header invalid' - Authorization Header Value is not in format `Token <auth-token>`
exceptions.AuthenticationFailed: 'Token header invalid. Possibly incorrectly formatted' - Authentication header value has >1 space
exceptions.AuthenticationFailed: 'Invalid token header. Token string should not contain invalid characters.' - Authorization header contains non-unicode chars
Returns:
None (None): User not authenticated
tuple(user,token): User authenticated
"""
auth = get_authorization_header(request).split()
if not auth:
return None
if len(auth) == 1:
raise exceptions.AuthenticationFailed('Token header invalid')
elif len(auth) > 2:
raise exceptions.AuthenticationFailed('Token header invalid. Possibly incorrectly formatted')
elif len(auth) == 2:
try:
decoded_token: str = auth[1].decode("utf-8")
for token in AuthToken.objects.filter():
provided_token: str = token.token_hash(decoded_token)
if token.token == provided_token:
if datetime.datetime.strptime(str(token.expires),'%Y-%m-%d %H:%M:%S%z') > datetime.datetime.now(datetime.timezone.utc):
user = token.user
return (user, provided_token)
else:
expired_token = AuthToken.objects.get(id=token.id)
expired_token.delete()
except UnicodeError:
raise exceptions.AuthenticationFailed('Invalid token header. Token string should not contain invalid characters.')
return None

View File

@ -0,0 +1,49 @@
import datetime
from django import forms
from api.models.tokens import AuthToken
from app import settings
from core.forms.common import CommonModelForm
class AuthTokenForm(CommonModelForm):
prefix = 'user_token'
class Meta:
fields = [
'note',
'expires',
]
model = AuthToken
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['expires'].widget = forms.widgets.DateTimeInput(attrs={'type': 'datetime-local', 'format': "%Y-%m-%dT%H:%M"})
self.fields['expires'].input_formats = settings.DATETIME_FORMAT
self.fields['expires'].format="%Y-%m-%dT%H:%M"
self.fields['expires'].initial= datetime.datetime.now() + datetime.timedelta(days=90)
if self.prefix + '-gen_token' not in self.data:
generated_token = self.instance.generate()
else:
generated_token = self.data[self.prefix + '-gen_token']
self.fields['gen_token'] = forms.CharField(
label="Generated Token",
initial=generated_token,
empty_value= generated_token,
required=False,
help_text = 'Ensure you save this token somewhere as you will never be able to obtain it again',
)
self.fields['gen_token'].widget.attrs['readonly'] = True

View File

@ -1,4 +1,4 @@
# Generated by Django 5.0.6 on 2024-05-24 23:50
# Generated by Django 5.0.7 on 2024-07-12 03:54
import access.fields
import django.db.models.deletion
@ -9,24 +9,23 @@ from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('access', '0002_alter_team_organization'),
('settings', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='UserSettings',
name='AuthToken',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, unique=True)),
('note', models.CharField(blank=True, default=None, max_length=50, null=True)),
('token', models.CharField(db_index=True, max_length=64, unique=True, verbose_name='Auth Token')),
('expires', models.DateTimeField(verbose_name='Expiry Date')),
('created', access.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False)),
('modified', access.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False)),
('default_organization', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='access.organization')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]

View File

View File

76
app/api/models/tokens.py Normal file
View File

@ -0,0 +1,76 @@
import hashlib
import random
import string
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from access.fields import *
from access.models import TenancyObject
class AuthToken(models.Model):
id = models.AutoField(
primary_key=True,
unique=True,
blank=False
)
note = models.CharField(
blank = True,
max_length = 50,
default = None,
null= True,
)
token = models.CharField(
verbose_name = 'Auth Token',
db_index=True,
max_length = 64,
null = False,
blank = False,
unique = True,
)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
expires = models.DateTimeField(
verbose_name = 'Expiry Date',
null = False,
blank = False
)
created = AutoCreatedField()
modified = AutoLastModifiedField()
def generate(self) -> str:
return str(hashlib.sha256(str(self.randomword()).encode('utf-8')).hexdigest())
def token_hash(self, token:str) -> str:
salt = settings.SECRET_KEY
return str(hashlib.sha256(str(token + salt).encode('utf-8')).hexdigest())
def randomword(self) -> str:
return ''.join(random.choice(string.ascii_letters) for i in range(120))
def __str__(self):
return self.token

View File

View File

@ -14,9 +14,8 @@ class TeamSerializerBase(serializers.ModelSerializer):
class Meta:
model = Team
fields = (
"id",
"team_name",
'organization',
'team_name',
'permissions',
'url',
)
@ -29,9 +28,18 @@ class TeamSerializerBase(serializers.ModelSerializer):
class TeamPermissionSerializer(serializers.ModelSerializer):
class Meta:
model = Permission
depth = 1
fields = '__all__'
class TeamSerializer(TeamSerializerBase):
permissions = serializers.SerializerMethodField('get_url')
permissions_url = serializers.SerializerMethodField('get_url')
def get_url(self, obj):
@ -63,16 +71,18 @@ class TeamSerializer(TeamSerializerBase):
class Meta:
model = Team
depth = 1
depth = 2
fields = (
"id",
"team_name",
'organization',
'permissions',
'permissions_url',
'url',
)
read_only_fields = [
'permissions',
'id',
'organization',
'permissions_url',
'url'
]
@ -111,7 +121,7 @@ class OrganizationSerializer(serializers.ModelSerializer):
return request.build_absolute_uri(reverse('API:_api_organization_teams', args=[obj.id]))
teams = TeamSerializerBase(source='team_set', many=True, read_only=False)
teams = TeamSerializer(source='team_set', many=True, read_only=False)
view_name="API:_api_organization"

View File

@ -0,0 +1,86 @@
from rest_framework import serializers
from rest_framework.reverse import reverse
from config_management.models.groups import ConfigGroups
class ParentGroupSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField('get_url')
class Meta:
model = ConfigGroups
fields = [
'id',
'name',
'url',
]
read_only_fields = [
'id',
'name',
'url',
]
def get_url(self, obj):
request = self.context.get('request')
return request.build_absolute_uri(reverse("API:_api_config_group", args=[obj.pk]))
class ConfigGroupsSerializerBase(serializers.ModelSerializer):
parent = ParentGroupSerializer(read_only=True)
url = serializers.SerializerMethodField('get_url')
class Meta:
model = ConfigGroups
fields = [
'id',
'parent',
'name',
'config',
'url',
]
read_only_fields = [
'id',
'name',
'config',
'url',
]
def get_url(self, obj):
request = self.context.get('request')
return request.build_absolute_uri(reverse("API:_api_config_group", args=[obj.pk]))
class ConfigGroupsSerializer(ConfigGroupsSerializerBase):
class Meta:
model = ConfigGroups
depth = 1
fields = [
'id',
'parent',
'name',
'config',
'url',
]
read_only_fields = [
'id',
'parent',
'name',
'config',
'url',
]

View File

@ -0,0 +1,168 @@
from django.core.exceptions import ValidationError
from django.utils.html import escape
class Inventory:
""" Inventory Object
Pass in an Inventory dict that a device has provided and sanitize ready for use.
Raises:
ValidationError: Malformed inventory data.
"""
class Details:
_name: str
_serial_number: str
_uuid: str
def __init__(self, details: dict):
self._name = escape(details['name'])
self._serial_number = escape(details['serial_number'])
self._uuid = escape(details['uuid'])
@property
def name(self) -> str:
return str(self._name)
@property
def serial_number(self) -> str:
return str(self._serial_number)
@property
def uuid(self) -> str:
return str(self._uuid)
class OperatingSystem:
_name: str
_version_major: str
_version: str
def __init__(self, operating_system: dict):
self._name = escape(operating_system['name'])
self._version_major = escape(operating_system['version_major'])
self._version = escape(operating_system['version'])
@property
def name(self) -> str:
return str(self._name)
@property
def version_major(self) -> str:
return str(self._version_major)
@property
def version(self) -> str:
return str(self._version)
class Software:
_name: str
_category: str
_version: str
def __init__(self, software: dict):
self._name = escape(software['name'])
self._category = escape(software['category'])
self._version = escape(software['version'])
@property
def name(self) -> str:
return str(self._name)
@property
def category(self) -> str:
return str(self._category)
@property
def version(self) -> str:
return str(self._version)
_details: Details = None
_operating_system: OperatingSystem = None
_software: list[Software] = []
def __init__(self, inventory: dict):
if (
type(inventory['details']) is dict and
type(inventory['os']) is dict and
type(inventory['software']) is list
):
self._details = self.Details(inventory['details'])
self._operating_system = self.OperatingSystem(inventory['os'])
for software in inventory['software']:
self._software += [ self.Software(software) ]
else:
raise ValidationError('Inventory File is invalid')
@property
def details(self) -> Details:
return self._details
@property
def operating_system(self) -> OperatingSystem:
return self._operating_system
@property
def software(self) -> list[Software]:
return list(self._software)

View File

@ -1,9 +1,38 @@
from django.urls import reverse
from itam.models.device import Device
from rest_framework import serializers
from api.serializers.config import ParentGroupSerializer
from config_management.models.groups import ConfigGroupHosts
from itam.models.device import Device
class DeviceConfigGroupsSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='group.name', read_only=True)
url = serializers.HyperlinkedIdentityField(
view_name="API:_api_config_group", format="html"
)
class Meta:
model = ConfigGroupHosts
fields = [
'id',
'name',
'url',
]
read_only_fields = [
'id',
'name',
'url',
]
class DeviceSerializer(serializers.ModelSerializer):
@ -13,7 +42,9 @@ class DeviceSerializer(serializers.ModelSerializer):
)
config = serializers.SerializerMethodField('get_device_config')
groups = DeviceConfigGroupsSerializer(source='configgrouphosts_set', many=True, read_only=True)
def get_device_config(self, device):
request = self.context.get('request')
@ -22,11 +53,29 @@ class DeviceSerializer(serializers.ModelSerializer):
class Meta:
model = Device
fields = '__all__'
read_only_fields = [
'inventorydate',
depth = 1
fields = [
'id',
'is_global',
'slug',
'name',
'config',
'serial_number',
'uuid',
'inventorydate',
'created',
'modified',
'groups',
'organization',
'url',
]
read_only_fields = [
'id',
'config',
'inventorydate',
'created',
'modified',
'groups',
'url',
]

View File

@ -0,0 +1,73 @@
from django.urls import reverse
from itam.models.device import Device
from rest_framework import serializers
class InventorySerializer(serializers.Serializer):
""" Serializer for Inventory Upload """
class DetailsSerializer(serializers.Serializer):
name = serializers.CharField(
help_text = 'Host name',
required = True
)
serial_number = serializers.CharField(
help_text = 'Devices serial number',
required = True
)
uuid = serializers.CharField(
help_text = 'Device system UUID',
required = True
)
class OperatingSystemSerializer(serializers.Serializer):
name = serializers.CharField(
help_text='Name of the operating system installed on the device',
required = True,
)
version_major = serializers.IntegerField(
help_text='Major semver version number of the OS version',
required = True,
)
version = serializers.CharField(
help_text='semver version number of the OS',
required = True
)
class SoftwareSerializer(serializers.Serializer):
name = serializers.CharField(
help_text='Name of the software',
required = True
)
category = serializers.CharField(
help_text='Category of the software',
default = None,
required = False
)
version = serializers.CharField(
default = None,
help_text='semver version number of the software',
required = False
)
details = DetailsSerializer()
os = OperatingSystemSerializer()
software = SoftwareSerializer(many = True)

446
app/api/tasks.py Normal file
View File

@ -0,0 +1,446 @@
import json
import re
from django.utils import timezone
from celery import shared_task, current_task
from celery.utils.log import get_task_logger
from celery import states
from access.models import Organization
from api.serializers.inventory import Inventory
from itam.models.device import Device, DeviceType, DeviceOperatingSystem, DeviceSoftware
from itam.models.operating_system import OperatingSystem, OperatingSystemVersion
from itam.models.software import Software, SoftwareCategory, SoftwareVersion
from settings.models.app_settings import AppSettings
logger = get_task_logger(__name__)
@shared_task(bind=True)
def process_inventory(self, data, organization: int):
device = None
device_operating_system = None
operating_system = None
operating_system_version = None
try:
logger.info('Begin Processing Inventory')
data = json.loads(data)
data = Inventory(data)
organization = Organization.objects.get(id=organization)
app_settings = AppSettings.objects.get(owner_organization = None)
device_serial_number = None
device_uuid = None
if data.details.serial_number and str(data.details.serial_number).lower() != 'na':
device_serial_number = str(data.details.serial_number)
if data.details.uuid and str(data.details.uuid).lower() != 'na':
device_uuid = str(data.details.uuid)
if device_serial_number: # Search for device by serial number.
device = Device.objects.filter(
serial_number__iexact=device_serial_number
)
if device.exists():
device = Device.objects.get(
serial_number__iexact=device_serial_number
)
else:
device = None
if device_uuid and not device: # Search for device by UUID.
device = Device.objects.filter(
uuid__iexact=device_uuid
)
if device.exists():
device = Device.objects.get(
uuid__iexact=device_uuid
)
else:
device = None
if not device: # Search for device by Name.
device = Device.objects.filter(
name__iexact=str(data.details.name).lower()
)
if device.exists():
device = Device.objects.get(
name__iexact=str(data.details.name).lower()
)
else:
device = None
if not device: # Create the device
device = Device.objects.create(
name = data.details.name,
device_type = None,
serial_number = device_serial_number,
uuid = device_uuid,
organization = organization,
)
if device:
logger.info(f"Device: {device.name}, Serial: {device.serial_number}, UUID: {device.uuid}")
device_edited = False
if not device.uuid and device_uuid:
device.uuid = device_uuid
device_edited = True
if not device.serial_number and device_serial_number:
device.serial_number = data.details.serial_number
device_edited = True
if str(device.name).lower() != str(data.details.name).lower(): # Update device Name
device.name = data.details.name
device_edited = True
if device_edited:
device.save()
operating_system = OperatingSystem.objects.filter(
name=data.operating_system.name,
is_global = True
)
if operating_system.exists():
operating_system = OperatingSystem.objects.get(
name=data.operating_system.name,
is_global = True
)
else:
operating_system = None
if not operating_system:
operating_system = OperatingSystem.objects.filter(
name=data.operating_system.name,
organization = organization
)
if operating_system.exists():
operating_system = OperatingSystem.objects.get(
name=data.operating_system.name,
organization = organization
)
else:
operating_system = None
if not operating_system:
operating_system = OperatingSystem.objects.create(
name = data.operating_system.name,
organization = organization,
is_global = True
)
operating_system_version = OperatingSystemVersion.objects.filter(
name=data.operating_system.version_major,
operating_system=operating_system
)
if operating_system_version.exists():
operating_system_version = OperatingSystemVersion.objects.get(
name=data.operating_system.version_major,
operating_system=operating_system
)
else:
operating_system_version = None
if not operating_system_version:
operating_system_version = OperatingSystemVersion.objects.create(
organization = organization,
is_global = True,
name = data.operating_system.version_major,
operating_system = operating_system,
)
device_operating_system = DeviceOperatingSystem.objects.filter(
device=device,
)
if device_operating_system.exists():
device_operating_system = DeviceOperatingSystem.objects.get(
device=device,
)
else:
device_operating_system = None
if not device_operating_system:
device_operating_system = DeviceOperatingSystem.objects.create(
organization = organization,
device=device,
version = data.operating_system.version,
operating_system_version = operating_system_version,
installdate = timezone.now()
)
if not device_operating_system.installdate: # Only update install date if empty
device_operating_system.installdate = timezone.now()
device_operating_system.save()
if device_operating_system.operating_system_version != operating_system_version:
device_operating_system.operating_system_version = operating_system_version
device_operating_system.save()
if device_operating_system.version != data.operating_system.version:
device_operating_system.version = data.operating_system.version
device_operating_system.save()
if app_settings.software_is_global:
software_organization = app_settings.global_organization
else:
software_organization = device.organization
if app_settings.software_categories_is_global:
software_category_organization = app_settings.global_organization
else:
software_category_organization = device.organization
inventoried_software: list = []
for inventory in list(data.software):
software = None
software_category = None
software_version = None
device_software = None
software_category = SoftwareCategory.objects.filter( name = inventory.category )
if software_category.exists():
software_category = SoftwareCategory.objects.get(
name = inventory.category
)
else: # Create Software Category
software_category = SoftwareCategory.objects.create(
organization = software_category_organization,
is_global = True,
name = inventory.category,
)
if software_category.name == inventory.category:
if Software.objects.filter( name = inventory.name ).exists():
software = Software.objects.get(
name = inventory.name
)
if not software.category:
software.category = software_category
software.save()
else: # Create Software
software = Software.objects.create(
organization = software_organization,
is_global = True,
name = inventory.name,
category = software_category,
)
if software.name == inventory.name:
pattern = r"^(\d+:)?(?P<semver>\d+\.\d+(\.\d+)?)"
semver = re.search(pattern, str(inventory.version), re.DOTALL)
if semver:
semver = semver['semver']
else:
semver = inventory.version
if SoftwareVersion.objects.filter( name = semver, software = software ).exists():
software_version = SoftwareVersion.objects.get(
name = semver,
software = software,
)
else: # Create Software Category
software_version = SoftwareVersion.objects.create(
organization = organization,
is_global = True,
name = semver,
software = software,
)
if software_version.name == semver:
if DeviceSoftware.objects.filter( software = software, device=device ).exists():
device_software = DeviceSoftware.objects.get(
device = device,
software = software
)
logger.debug(f"Select Existing Device Software: {device_software.software.name}")
else: # Create Software
device_software = DeviceSoftware.objects.create(
organization = organization,
is_global = True,
installedversion = software_version,
software = software,
device = device,
action=None
)
logger.debug(f"Create Device Software: {device_software.software.name}")
if device_software: # Update the Inventoried software
inventoried_software += [ device_software.id ]
if not device_software.installed: # Only update install date if blank
device_software.installed = timezone.now()
device_software.save()
logger.debug(f"Update Device Software (installed): {device_software.software.name}")
if device_software.installedversion.name != software_version.name:
device_software.installedversion = software_version
device_software.save()
logger.debug(f"Update Device Software (installedversion): {device_software.software.name}")
for not_installed in DeviceSoftware.objects.filter( device=device ):
if not_installed.id not in inventoried_software:
not_installed.delete()
logger.debug(f"Remove Device Software: {not_installed.software.name}")
if device and operating_system and operating_system_version and device_operating_system:
device.inventorydate = timezone.now()
device.save()
logger.info('Finish Processing Inventory')
return str('finished...')
except Exception as e:
logger.critical('Exception')
raise Exception(e)
return str(f'Exception Occured: {e}')

View File

View File

View File

@ -0,0 +1,470 @@
import pytest
import unittest
from django.shortcuts import reverse
from django.test import TestCase, Client
class APIPermissionView:
model: object
""" Item Model to test """
app_namespace: str = None
""" URL namespace """
url_name: str
""" URL name of the view to test """
url_view_kwargs: dict = None
""" URL kwargs of the item page """
def test_view_user_anon_denied(self):
""" Check correct permission for view
Attempt to view as anon user
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
response = client.get(url)
assert response.status_code == 401
def test_view_no_permission_denied(self):
""" Check correct permission for view
Attempt to view with user missing permission
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.no_permissions_user)
response = client.get(url)
assert response.status_code == 403
def test_view_different_organizaiton_denied(self):
""" Check correct permission for view
Attempt to view with user from different organization
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.different_organization_user)
response = client.get(url)
assert response.status_code == 403
def test_view_has_permission(self):
""" Check correct permission for view
Attempt to view as user with view permission
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.view_user)
response = client.get(url)
assert response.status_code == 200
class APIPermissionAdd:
model: object
""" Item Model to test """
app_namespace: str = None
""" URL namespace """
url_list: str
""" URL view name of the item list page """
url_kwargs: dict = None
""" URL view kwargs for the item list page """
add_data: dict = None
def test_add_user_anon_denied(self):
""" Check correct permission for add
Attempt to add as anon user
"""
client = Client()
if self.url_kwargs:
url = reverse(self.app_namespace + ':' + self.url_list, kwargs = self.url_kwargs)
else:
url = reverse(self.app_namespace + ':' + self.url_list)
response = client.put(url, data=self.add_data)
assert response.status_code == 401
# @pytest.mark.skip(reason="ToDO: figure out why fails")
def test_add_no_permission_denied(self):
""" Check correct permission for add
Attempt to add as user with no permissions
"""
client = Client()
if self.url_kwargs:
url = reverse(self.app_namespace + ':' + self.url_list, kwargs = self.url_kwargs)
else:
url = reverse(self.app_namespace + ':' + self.url_list)
client.force_login(self.no_permissions_user)
response = client.post(url, data=self.add_data)
assert response.status_code == 403
# @pytest.mark.skip(reason="ToDO: figure out why fails")
def test_add_different_organization_denied(self):
""" Check correct permission for add
attempt to add as user from different organization
"""
client = Client()
if self.url_kwargs:
url = reverse(self.app_namespace + ':' + self.url_list, kwargs = self.url_kwargs)
else:
url = reverse(self.app_namespace + ':' + self.url_list)
client.force_login(self.different_organization_user)
response = client.post(url, data=self.add_data)
assert response.status_code == 403
def test_add_permission_view_denied(self):
""" Check correct permission for add
Attempt to add a user with view permission
"""
client = Client()
if self.url_kwargs:
url = reverse(self.app_namespace + ':' + self.url_list, kwargs = self.url_kwargs)
else:
url = reverse(self.app_namespace + ':' + self.url_list)
client.force_login(self.view_user)
response = client.post(url, data=self.add_data)
assert response.status_code == 403
def test_add_has_permission(self):
""" Check correct permission for add
Attempt to add as user with no permission
"""
client = Client()
if self.url_kwargs:
url = reverse(self.app_namespace + ':' + self.url_list, kwargs = self.url_kwargs)
else:
url = reverse(self.app_namespace + ':' + self.url_list)
client.force_login(self.add_user)
response = client.post(url, data=self.add_data)
assert response.status_code == 201
class APIPermissionChange:
model: object
""" Item Model to test """
app_namespace: str = None
""" URL namespace """
url_name: str
""" URL name of the view to test """
url_view_kwargs: dict = None
""" URL kwargs of the item page """
change_data: dict = None
def test_change_user_anon_denied(self):
""" Check correct permission for change
Attempt to change as anon
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
response = client.patch(url, data=self.change_data, content_type='application/json')
assert response.status_code == 401
def test_change_no_permission_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user without permissions
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.no_permissions_user)
response = client.patch(url, data=self.change_data, content_type='application/json')
assert response.status_code == 403
def test_change_different_organization_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user from different organization
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.different_organization_user)
response = client.patch(url, data=self.change_data, content_type='application/json')
assert response.status_code == 403
def test_change_permission_view_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with view permission
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.view_user)
response = client.patch(url, data=self.change_data, content_type='application/json')
assert response.status_code == 403
def test_change_permission_add_denied(self):
""" Ensure permission view cant make change
Attempt to make change as user with add permission
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.add_user)
response = client.patch(url, data=self.change_data, content_type='application/json')
assert response.status_code == 403
def test_change_has_permission(self):
""" Check correct permission for change
Make change with user who has change permission
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.change_user)
response = client.patch(url, data=self.change_data, content_type='application/json')
assert response.status_code == 200
class APIPermissionDelete:
model: object
""" Item Model to test """
app_namespace: str = None
""" URL namespace """
url_name: str
""" URL name of the view to test """
url_view_kwargs: dict = None
""" URL kwargs of the item page """
delete_data: dict = None
def test_delete_user_anon_denied(self):
""" Check correct permission for delete
Attempt to delete item as anon user
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 401
def test_delete_no_permission_denied(self):
""" Check correct permission for delete
Attempt to delete as user with no permissons
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.no_permissions_user)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 403
def test_delete_different_organization_denied(self):
""" Check correct permission for delete
Attempt to delete as user from different organization
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.different_organization_user)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 403
def test_delete_permission_view_denied(self):
""" Check correct permission for delete
Attempt to delete as user with veiw permission only
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.view_user)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 403
def test_delete_permission_add_denied(self):
""" Check correct permission for delete
Attempt to delete as user with add permission only
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.add_user)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 403
def test_delete_permission_change_denied(self):
""" Check correct permission for delete
Attempt to delete as user with change permission only
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.change_user)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 403
def test_delete_has_permission(self):
""" Check correct permission for delete
Delete item as user with delete permission
"""
client = Client()
url = reverse(self.app_namespace + ':' + self.url_name, kwargs=self.url_view_kwargs)
client.force_login(self.delete_user)
response = client.delete(url, data=self.delete_data)
assert response.status_code == 204
class APIPermissions(
APIPermissionAdd,
APIPermissionChange,
APIPermissionDelete,
APIPermissionView
):
""" Abstract class containing all API Permission test cases """
model: object
""" Item Model to test """

View File

@ -1,151 +0,0 @@
from django.shortcuts import reverse
from django.test import TestCase, Client
import pytest
import unittest
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_added():
""" Device is created """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_operating_system_added():
""" Operating System is created """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_operating_system_version_added():
""" Operating System version is created """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_has_operating_system_added():
""" Operating System version linked to device """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_operating_system_version_is_semver():
""" Operating System version is full semver
Operating system versions name is the major version number of semver.
The device version is to be full semver
"""
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_no_version_cleaned():
""" Check softare cleaned up
As part of the inventory upload the software versions of software found on the device is set to null
and before the processing is completed, the version=null software is supposed to be cleaned up.
"""
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_category_added():
""" Software category exists """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_added():
""" Test software exists """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_category_linked_to_software():
""" Software category linked to software """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_version_added():
""" Test software version exists """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_version_returns_semver():
""" Software Version from inventory returns semver if within version string """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_version_returns_original_version():
""" Software Version from inventory returns inventoried version if no semver found """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_version_linked_to_software():
""" Test software version linked to software it belongs too """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_has_software_version():
""" Inventoried software is linked to device and it's the corret one"""
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_software_has_installed_date():
""" Inventoried software version has install date """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_software_blank_installed_date_is_updated():
""" A blank installed date of software is updated if the software was already attached to the device """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_valid_status_created():
""" Successful inventory upload returns 201 """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_invalid_status_bad_request():
""" Incorrectly formated inventory upload returns 400 """
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_exeception_status_sever_error():
""" if the method throws an exception 500 must be returned.
idea to test: add a random key to the report that is not documented
and perform some action against it that will cause a python exception.
"""
pass

View File

View File

@ -0,0 +1,989 @@
import datetime
import json
import pytest
import unittest
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
from django.test.utils import override_settings
from unittest.mock import patch
from access.models import Organization, Team, TeamUsers, Permission
from api.views.mixin import OrganizationPermissionAPI
from api.serializers.inventory import Inventory
from api.tasks import process_inventory
from itam.models.device import Device, DeviceOperatingSystem, DeviceSoftware
from itam.models.operating_system import OperatingSystem, OperatingSystemVersion
from itam.models.software import Software, SoftwareCategory, SoftwareVersion
from settings.models.user_settings import UserSettings
class InventoryAPI(TestCase):
model = Device
model_name = 'device'
app_label = 'itam'
inventory = {
"details": {
"name": "device_name",
"serial_number": "a serial number",
"uuid": "string"
},
"os": {
"name": "os_name",
"version_major": "12",
"version": "12.1"
},
"software": [
{
"name": "software_name",
"category": "category_name",
"version": "1.2.3"
},
{
"name": "software_name_not_semver",
"category": "category_name",
"version": "2024.4"
},
{
"name": "software_name_semver_contained",
"category": "category_name",
"version": "1.2.3-rc1"
},
]
}
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user
2. Create a team for user with correct permissions
3. add user to the teeam
4. upload the inventory
5. conduct queries for tests
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
self.add_user = User.objects.create_user(username="test_user_add", password="password")
add_user_settings = UserSettings.objects.get(user=self.add_user)
add_user_settings.default_organization = organization
add_user_settings.save()
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
# upload the inventory
process_inventory(json.dumps(self.inventory), organization.id)
self.device = Device.objects.get(name=self.inventory['details']['name'])
self.operating_system = OperatingSystem.objects.get(name=self.inventory['os']['name'])
self.operating_system_version = OperatingSystemVersion.objects.get(name=self.inventory['os']['version_major'])
self.device_operating_system = DeviceOperatingSystem.objects.get(version=self.inventory['os']['version'])
self.software = Software.objects.get(name=self.inventory['software'][0]['name'])
self.software_category = SoftwareCategory.objects.get(name=self.inventory['software'][0]['category'])
self.software_version = SoftwareVersion.objects.get(
name = self.inventory['software'][0]['version'],
software = self.software,
)
self.software_not_semver = Software.objects.get(name=self.inventory['software'][1]['name'])
self.software_version_not_semver = SoftwareVersion.objects.get(
name = self.inventory['software'][1]['version'],
software = self.software_not_semver
)
self.software_is_semver = Software.objects.get(name=self.inventory['software'][2]['name'])
self.software_version_is_semver = SoftwareVersion.objects.get(
software = self.software_is_semver
)
self.device_software = DeviceSoftware.objects.get(device=self.device,software=self.software)
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
@patch.object(OrganizationPermissionAPI, 'permission_check')
def test_inventory_function_called_permission_check(self, permission_check):
""" Inventory Upload checks permissions
Function 'permission_check' is the function that checks permissions
As the non-established way of authentication an API permission is being done
confimation that the permissions are still checked is required.
"""
client = Client()
url = reverse('API:_api_device_inventory')
client.force_login(self.add_user)
response = client.post(url, data=self.inventory, content_type='application/json')
assert permission_check.called
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
@patch.object(Inventory, '__init__')
def test_inventory_serializer_inventory_called(self, serializer):
""" Inventory Upload checks permissions
Function 'permission_check' is the function that checks permissions
As the non-established way of authentication an API permission is being done
confimation that the permissions are still checked is required.
"""
client = Client()
url = reverse('API:_api_device_inventory')
client.force_login(self.add_user)
response = client.post(url, data=self.inventory, content_type='application/json')
assert serializer.called
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
@patch.object(Inventory.Details, '__init__')
def test_inventory_serializer_inventory_details_called(self, serializer):
""" Inventory Upload uses Inventory serializer
Details Serializer is called for inventory details dict.
"""
client = Client()
url = reverse('API:_api_device_inventory')
client.force_login(self.add_user)
response = client.post(url, data=self.inventory, content_type='application/json')
assert serializer.called
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
@patch.object(Inventory.OperatingSystem, '__init__')
def test_inventory_serializer_inventory_operating_system_called(self, serializer):
""" Inventory Upload uses Inventory serializer
Operating System Serializer is called for inventory Operating system dict.
"""
client = Client()
url = reverse('API:_api_device_inventory')
client.force_login(self.add_user)
response = client.post(url, data=self.inventory, content_type='application/json')
assert serializer.called
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
@patch.object(Inventory.Software, '__init__')
def test_inventory_serializer_inventory_software_called(self, serializer):
""" Inventory Upload uses Inventory serializer
Software Serializer is called for inventory software list.
"""
client = Client()
url = reverse('API:_api_device_inventory')
client.force_login(self.add_user)
response = client.post(url, data=self.inventory, content_type='application/json')
assert serializer.called
def test_api_inventory_device_added(self):
""" Device is created """
assert self.device.name == self.inventory['details']['name']
def test_api_inventory_device_uuid_match(self):
""" Device uuid match """
assert self.device.uuid == self.inventory['details']['uuid']
def test_api_inventory_device_serial_number_match(self):
""" Device SN match """
assert self.device.serial_number == self.inventory['details']['serial_number']
def test_api_inventory_operating_system_added(self):
""" Operating System is created """
assert self.operating_system.name == self.inventory['os']['name']
def test_api_inventory_operating_system_version_added(self):
""" Operating System version is created """
assert self.operating_system_version.name == self.inventory['os']['version_major']
def test_api_inventory_device_has_operating_system_added(self):
""" Operating System version linked to device """
assert self.device_operating_system.version == self.inventory['os']['version']
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_operating_system_version_is_semver(self):
""" Operating System version is full semver
Operating system versions name is the major version number of semver.
The device version is to be full semver
"""
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_no_version_cleaned(self):
""" Check softare cleaned up
As part of the inventory upload the software versions of software found on the device is set to null
and before the processing is completed, the version=null software is supposed to be cleaned up.
"""
pass
def test_api_inventory_software_category_added(self):
""" Software category exists """
assert self.software_category.name == self.inventory['software'][0]['category']
def test_api_inventory_software_added(self):
""" Test software exists """
assert self.software.name == self.inventory['software'][0]['name']
def test_api_inventory_software_category_linked_to_software(self):
""" Software category linked to software """
assert self.software.category == self.software_category
def test_api_inventory_software_version_added(self):
""" Test software version exists """
assert self.software_version.name == self.inventory['software'][0]['version']
def test_api_inventory_software_version_returns_semver(self):
""" Software Version from inventory returns semver if within version string """
assert self.software_version_is_semver.name == str(self.inventory['software'][2]['version']).split('-')[0]
def test_api_inventory_software_version_returns_original_version(self):
""" Software Version from inventory returns inventoried version if no semver found """
assert self.software_version_not_semver.name == self.inventory['software'][1]['version']
def test_api_inventory_software_version_linked_to_software(self):
""" Test software version linked to software it belongs too """
assert self.software_version.software == self.software
def test_api_inventory_device_has_software_version(self):
""" Inventoried software is linked to device and it's the corret one"""
assert self.software_version.name == self.inventory['software'][0]['version']
def test_api_inventory_device_software_has_installed_date(self):
""" Inventoried software version has install date """
assert self.device_software.installed is not None
def test_api_inventory_device_software_installed_date_type(self):
""" Inventoried software version has install date """
assert type(self.device_software.installed) is datetime.datetime
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_software_blank_installed_date_is_updated(self):
""" A blank installed date of software is updated if the software was already attached to the device """
pass
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
def test_api_inventory_valid_status_ok_existing_device(self):
""" Successful inventory upload returns 200 for existing device"""
client = Client()
url = reverse('API:_api_device_inventory')
client.force_login(self.add_user)
response = client.post(url, data=self.inventory, content_type='application/json')
assert response.status_code == 200
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
def test_api_inventory_invalid_status_bad_request(self):
""" Incorrectly formated inventory upload returns 400 """
client = Client()
url = reverse('API:_api_device_inventory')
mod_inventory = self.inventory.copy()
mod_inventory.update({
'details': {
'name': 'test_api_inventory_invalid_status_bad_request'
},
'software': {
'not_within_a': 'list'
}
})
client.force_login(self.add_user)
response = client.post(url, data=mod_inventory, content_type='application/json')
assert response.status_code == 400
@pytest.mark.skip(reason="to be written")
def test_api_inventory_exeception_status_sever_error(self):
""" if the method throws an exception 500 must be returned.
idea to test: add a random key to the report that is not documented
and perform some action against it that will cause a python exception.
"""
pass
class InventoryAPIDifferentNameSerialNumberMatch(TestCase):
""" Test inventory upload with different name
should match by serial number
"""
model = Device
model_name = 'device'
app_label = 'itam'
inventory = {
"details": {
"name": "device_name",
"serial_number": "serial_number_123",
"uuid": "string"
},
"os": {
"name": "os_name",
"version_major": "12",
"version": "12.1"
},
"software": [
{
"name": "software_name",
"category": "category_name",
"version": "1.2.3"
},
{
"name": "software_name_not_semver",
"category": "category_name",
"version": "2024.4"
},
{
"name": "software_name_semver_contained",
"category": "category_name",
"version": "1.2.3-rc1"
},
]
}
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user
2. Create a team for user with correct permissions
3. add user to the teeam
4. upload the inventory
5. conduct queries for tests
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
Device.objects.create(
name='random device name',
serial_number='serial_number_123'
)
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
self.add_user = User.objects.create_user(username="test_user_add", password="password")
add_user_settings = UserSettings.objects.get(user=self.add_user)
add_user_settings.default_organization = organization
add_user_settings.save()
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
# upload the inventory
process_inventory(json.dumps(self.inventory), organization.id)
self.device = Device.objects.get(name=self.inventory['details']['name'])
self.operating_system = OperatingSystem.objects.get(name=self.inventory['os']['name'])
self.operating_system_version = OperatingSystemVersion.objects.get(name=self.inventory['os']['version_major'])
self.device_operating_system = DeviceOperatingSystem.objects.get(version=self.inventory['os']['version'])
self.software = Software.objects.get(name=self.inventory['software'][0]['name'])
self.software_category = SoftwareCategory.objects.get(name=self.inventory['software'][0]['category'])
self.software_version = SoftwareVersion.objects.get(
name = self.inventory['software'][0]['version'],
software = self.software,
)
self.software_not_semver = Software.objects.get(name=self.inventory['software'][1]['name'])
self.software_version_not_semver = SoftwareVersion.objects.get(
name = self.inventory['software'][1]['version'],
software = self.software_not_semver
)
self.software_is_semver = Software.objects.get(name=self.inventory['software'][2]['name'])
self.software_version_is_semver = SoftwareVersion.objects.get(
software = self.software_is_semver
)
self.device_software = DeviceSoftware.objects.get(device=self.device,software=self.software)
def test_api_inventory_device_added(self):
""" Device is created """
assert self.device.name == self.inventory['details']['name']
def test_api_inventory_device_uuid_match(self):
""" Device uuid match """
assert self.device.uuid == self.inventory['details']['uuid']
def test_api_inventory_device_serial_number_match(self):
""" Device SN match """
assert self.device.serial_number == self.inventory['details']['serial_number']
def test_api_inventory_operating_system_added(self):
""" Operating System is created """
assert self.operating_system.name == self.inventory['os']['name']
def test_api_inventory_operating_system_version_added(self):
""" Operating System version is created """
assert self.operating_system_version.name == self.inventory['os']['version_major']
def test_api_inventory_device_has_operating_system_added(self):
""" Operating System version linked to device """
assert self.device_operating_system.version == self.inventory['os']['version']
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_operating_system_version_is_semver(self):
""" Operating System version is full semver
Operating system versions name is the major version number of semver.
The device version is to be full semver
"""
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_no_version_cleaned(self):
""" Check softare cleaned up
As part of the inventory upload the software versions of software found on the device is set to null
and before the processing is completed, the version=null software is supposed to be cleaned up.
"""
pass
def test_api_inventory_software_category_added(self):
""" Software category exists """
assert self.software_category.name == self.inventory['software'][0]['category']
def test_api_inventory_software_added(self):
""" Test software exists """
assert self.software.name == self.inventory['software'][0]['name']
def test_api_inventory_software_category_linked_to_software(self):
""" Software category linked to software """
assert self.software.category == self.software_category
def test_api_inventory_software_version_added(self):
""" Test software version exists """
assert self.software_version.name == self.inventory['software'][0]['version']
def test_api_inventory_software_version_returns_semver(self):
""" Software Version from inventory returns semver if within version string """
assert self.software_version_is_semver.name == str(self.inventory['software'][2]['version']).split('-')[0]
def test_api_inventory_software_version_returns_original_version(self):
""" Software Version from inventory returns inventoried version if no semver found """
assert self.software_version_not_semver.name == self.inventory['software'][1]['version']
def test_api_inventory_software_version_linked_to_software(self):
""" Test software version linked to software it belongs too """
assert self.software_version.software == self.software
def test_api_inventory_device_has_software_version(self):
""" Inventoried software is linked to device and it's the corret one"""
assert self.software_version.name == self.inventory['software'][0]['version']
def test_api_inventory_device_software_has_installed_date(self):
""" Inventoried software version has install date """
assert self.device_software.installed is not None
def test_api_inventory_device_software_installed_date_type(self):
""" Inventoried software version has install date """
assert type(self.device_software.installed) is datetime.datetime
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_software_blank_installed_date_is_updated(self):
""" A blank installed date of software is updated if the software was already attached to the device """
pass
class InventoryAPIDifferentNameUUIDMatch(TestCase):
""" Test inventory upload with different name
should match by uuid
"""
model = Device
model_name = 'device'
app_label = 'itam'
inventory = {
"details": {
"name": "device_name",
"serial_number": "serial_number_123",
"uuid": "123-456-789"
},
"os": {
"name": "os_name",
"version_major": "12",
"version": "12.1"
},
"software": [
{
"name": "software_name",
"category": "category_name",
"version": "1.2.3"
},
{
"name": "software_name_not_semver",
"category": "category_name",
"version": "2024.4"
},
{
"name": "software_name_semver_contained",
"category": "category_name",
"version": "1.2.3-rc1"
},
]
}
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user
2. Create a team for user with correct permissions
3. add user to the teeam
4. upload the inventory
5. conduct queries for tests
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
Device.objects.create(
name='random device name',
uuid='123-456-789'
)
add_permissions = Permission.objects.get(
codename = 'add_' + self.model_name,
content_type = ContentType.objects.get(
app_label = self.app_label,
model = self.model_name,
)
)
add_team = Team.objects.create(
team_name = 'add_team',
organization = organization,
)
add_team.permissions.set([add_permissions])
self.add_user = User.objects.create_user(username="test_user_add", password="password")
add_user_settings = UserSettings.objects.get(user=self.add_user)
add_user_settings.default_organization = organization
add_user_settings.save()
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
)
# upload the inventory
process_inventory(json.dumps(self.inventory), organization.id)
self.device = Device.objects.get(name=self.inventory['details']['name'])
self.operating_system = OperatingSystem.objects.get(name=self.inventory['os']['name'])
self.operating_system_version = OperatingSystemVersion.objects.get(name=self.inventory['os']['version_major'])
self.device_operating_system = DeviceOperatingSystem.objects.get(version=self.inventory['os']['version'])
self.software = Software.objects.get(name=self.inventory['software'][0]['name'])
self.software_category = SoftwareCategory.objects.get(name=self.inventory['software'][0]['category'])
self.software_version = SoftwareVersion.objects.get(
name = self.inventory['software'][0]['version'],
software = self.software,
)
self.software_not_semver = Software.objects.get(name=self.inventory['software'][1]['name'])
self.software_version_not_semver = SoftwareVersion.objects.get(
name = self.inventory['software'][1]['version'],
software = self.software_not_semver
)
self.software_is_semver = Software.objects.get(name=self.inventory['software'][2]['name'])
self.software_version_is_semver = SoftwareVersion.objects.get(
software = self.software_is_semver
)
self.device_software = DeviceSoftware.objects.get(device=self.device,software=self.software)
def test_api_inventory_device_added(self):
""" Device is created """
assert self.device.name == self.inventory['details']['name']
def test_api_inventory_device_uuid_match(self):
""" Device uuid match """
assert self.device.uuid == self.inventory['details']['uuid']
def test_api_inventory_device_serial_number_match(self):
""" Device SN match """
assert self.device.serial_number == self.inventory['details']['serial_number']
def test_api_inventory_operating_system_added(self):
""" Operating System is created """
assert self.operating_system.name == self.inventory['os']['name']
def test_api_inventory_operating_system_version_added(self):
""" Operating System version is created """
assert self.operating_system_version.name == self.inventory['os']['version_major']
def test_api_inventory_device_has_operating_system_added(self):
""" Operating System version linked to device """
assert self.device_operating_system.version == self.inventory['os']['version']
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_operating_system_version_is_semver(self):
""" Operating System version is full semver
Operating system versions name is the major version number of semver.
The device version is to be full semver
"""
pass
@pytest.mark.skip(reason="to be written")
def test_api_inventory_software_no_version_cleaned(self):
""" Check softare cleaned up
As part of the inventory upload the software versions of software found on the device is set to null
and before the processing is completed, the version=null software is supposed to be cleaned up.
"""
pass
def test_api_inventory_software_category_added(self):
""" Software category exists """
assert self.software_category.name == self.inventory['software'][0]['category']
def test_api_inventory_software_added(self):
""" Test software exists """
assert self.software.name == self.inventory['software'][0]['name']
def test_api_inventory_software_category_linked_to_software(self):
""" Software category linked to software """
assert self.software.category == self.software_category
def test_api_inventory_software_version_added(self):
""" Test software version exists """
assert self.software_version.name == self.inventory['software'][0]['version']
def test_api_inventory_software_version_returns_semver(self):
""" Software Version from inventory returns semver if within version string """
assert self.software_version_is_semver.name == str(self.inventory['software'][2]['version']).split('-')[0]
def test_api_inventory_software_version_returns_original_version(self):
""" Software Version from inventory returns inventoried version if no semver found """
assert self.software_version_not_semver.name == self.inventory['software'][1]['version']
def test_api_inventory_software_version_linked_to_software(self):
""" Test software version linked to software it belongs too """
assert self.software_version.software == self.software
def test_api_inventory_device_has_software_version(self):
""" Inventoried software is linked to device and it's the corret one"""
assert self.software_version.name == self.inventory['software'][0]['version']
def test_api_inventory_device_software_has_installed_date(self):
""" Inventoried software version has install date """
assert self.device_software.installed is not None
def test_api_inventory_device_software_installed_date_type(self):
""" Inventoried software version has install date """
assert type(self.device_software.installed) is datetime.datetime
@pytest.mark.skip(reason="to be written")
def test_api_inventory_device_software_blank_installed_date_is_updated(self):
""" A blank installed date of software is updated if the software was already attached to the device """
pass

View File

@ -1,17 +1,22 @@
# from django.conf import settings
import celery
import pytest
import unittest
import requests
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import reverse
from django.test import TestCase, Client
from django.test.utils import override_settings
import pytest
import unittest
import requests
from unittest.mock import patch
from access.models import Organization, Team, TeamUsers, Permission
from itam.models.device import Device
from settings.models.user_settings import UserSettings
class InventoryPermissionsAPI(TestCase):
@ -140,6 +145,13 @@ class InventoryPermissionsAPI(TestCase):
)
self.add_user = User.objects.create_user(username="test_user_add", password="password")
add_user_settings = UserSettings.objects.get(user=self.add_user)
add_user_settings.default_organization = organization
add_user_settings.save()
teamuser = TeamUsers.objects.create(
team = add_team,
user = self.add_user
@ -180,7 +192,8 @@ class InventoryPermissionsAPI(TestCase):
@pytest.mark.skip(reason="test to be written")
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
def test_device_auth_add_user_anon_denied(self):
""" Check correct permission for add
@ -191,12 +204,13 @@ class InventoryPermissionsAPI(TestCase):
url = reverse('API:_api_device_inventory')
response = client.put(url, data=self.inventory)
response = client.put(url, data=self.inventory, content_type='application/json')
assert response.status_code == 401
@pytest.mark.skip(reason="test to be written")
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
def test_device_auth_add_no_permission_denied(self):
""" Check correct permission for add
@ -208,12 +222,13 @@ class InventoryPermissionsAPI(TestCase):
client.force_login(self.no_permissions_user)
response = client.post(url, data=self.inventory)
response = client.post(url, data=self.inventory, content_type='application/json')
assert response.status_code == 403
@pytest.mark.skip(reason="test to be written")
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
def test_device_auth_add_different_organization_denied(self):
""" Check correct permission for add
@ -225,12 +240,13 @@ class InventoryPermissionsAPI(TestCase):
client.force_login(self.different_organization_user)
response = client.post(url, data=self.inventory)
response = client.post(url, data=self.inventory, content_type='application/json')
assert response.status_code == 403
@pytest.mark.skip(reason="test to be written")
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
def test_device_auth_add_permission_view_denied(self):
""" Check correct permission for add
@ -242,12 +258,13 @@ class InventoryPermissionsAPI(TestCase):
client.force_login(self.view_user)
response = client.post(url, data=self.inventory)
response = client.post(url, data=self.inventory, content_type='application/json')
assert response.status_code == 403
@pytest.mark.skip(reason="test to be written")
@override_settings(CELERY_TASK_ALWAYS_EAGER=True,
CELERY_TASK_EAGER_PROPOGATES=True)
def test_device_auth_add_has_permission(self):
""" Check correct permission for add
@ -259,8 +276,8 @@ class InventoryPermissionsAPI(TestCase):
client.force_login(self.add_user)
response = client.post(url, data=self.inventory)
response = client.post(url, data=self.inventory, content_type='application/json')
assert response.status_code == 201
assert response.status_code == 200

View File

@ -0,0 +1,326 @@
import hashlib
import json
import pytest
import requests
import unittest
from datetime import datetime, timedelta
from django.contrib.auth.models import AnonymousUser, User
from django.shortcuts import reverse
from django.test import TestCase, Client
from access.models import Organization, Team, TeamUsers, Permission
from api.models.tokens import AuthToken
from settings.models.user_settings import UserSettings
class APIAuthToken(TestCase):
@classmethod
def setUpTestData(self):
"""Setup Test
1. Create an organization for user
3. create user
4. create user settings
5. create API key (valid)
6. generate an API key that does not exist
5. create API key (expired)
"""
organization = Organization.objects.create(name='test_org')
self.organization = organization
self.add_user = User.objects.create_user(username="test_user_add", password="password")
add_user_settings = UserSettings.objects.get(user=self.add_user)
add_user_settings.default_organization = organization
add_user_settings.save()
expires = datetime.utcnow() + timedelta(days = 10)
expires = expires.strftime('%Y-%m-%d %H:%M:%S%z')
token = AuthToken.objects.create(
user = self.add_user,
expires=expires
)
self.api_token_valid = token.generate()
self.hashed_token = token.token_hash(self.api_token_valid)
token.token = self.hashed_token
token.save()
self.api_token_does_not_exist = hashlib.sha256(str('a random string').encode('utf-8')).hexdigest()
expires = datetime.utcnow() + timedelta(days = -10)
expires = expires.strftime('%Y-%m-%d %H:%M:%S%z')
self.api_token_expired = token.generate()
self.hashed_token_expired = token.token_hash(self.api_token_expired)
token = AuthToken.objects.create(
user = self.add_user,
expires=expires,
token = self.hashed_token_expired
)
def test_token_create_own(self):
""" Check correct permission for add
User can only create token for self.
"""
client = Client()
client.force_login(self.add_user)
url = reverse('_user_auth_token_add', kwargs={'user_id': self.add_user.id})
response = client.post(url, kwargs={'user_id': self.add_user.id})
assert response.status_code == 200
def test_token_create_other_user(self):
""" Check correct permission for add
User can not create token for another user.
"""
client = Client()
client.force_login(self.add_user)
url = reverse('_user_auth_token_add', kwargs={'user_id': 999})
response = client.post(url, kwargs={'user_id': 999})
assert response.status_code == 403
def test_token_delete_own(self):
""" Check correct permission for delete
User can only delete token for self.
"""
client = Client()
client.force_login(self.add_user)
url = reverse('_user_auth_token_delete', kwargs={'user_id': self.add_user.id, 'pk': 1})
response = client.post(url, kwargs={'user_id': self.add_user.id, 'pk': 1})
assert response.status_code == 302 and response.url == '/account/settings/1'
def test_token_delete_other_user(self):
""" Check correct permission for delete
User can not delete another users token.
"""
client = Client()
client.force_login(self.add_user)
url = reverse('_user_auth_token_delete', kwargs={'user_id': 999, 'pk': 1})
response = client.post(url, data={'id': 1}, kwargs={'user_id': 999, 'pk': 1})
assert response.status_code == 403
def test_auth_invalid_token(self):
""" Check token authentication
Invalid token does not allow login
"""
client = Client()
url = reverse('home') + 'api/'
response = client.get(
url,
content_type='application/json',
headers = {
'Accept': 'application/json',
'Authorization': 'Token ' + self.api_token_does_not_exist,
}
)
assert response.status_code == 401
def test_auth_no_token(self):
""" Check token authentication
providing no token does not allow login
"""
client = Client()
url = reverse('home') + 'api/'
response = client.get(
url,
content_type='application/json',
headers = {
'Accept': 'application/json'
}
)
assert response.status_code == 401
def test_auth_expired_token(self):
""" Check token authentication
expired token does not allow login
"""
client = Client()
url = reverse('home') + 'api/'
response = client.get(
url,
content_type='application/json',
headers = {
'Accept': 'application/json',
'Authorization': 'Token ' + self.api_token_expired,
}
)
assert response.status_code == 401
def test_auth_valid_token(self):
""" Check token authentication
Valid token allows login
"""
client = Client()
url = reverse('home') + 'api/'
response = client.get(
url,
content_type='application/json',
headers = {
'Accept': 'application/json',
'Authorization': 'Token ' + self.api_token_valid,
}
)
assert response.status_code == 200
def test_feat_expired_token_is_removed(self):
""" token feature confirmation
expired token is deleted
"""
client = Client()
url = reverse('home') + 'api/'
response = client.get(
url,
content_type='application/json',
headers = {
'Accept': 'application/json',
'Authorization': 'Token ' + self.api_token_expired,
}
)
db_query = AuthToken.objects.filter(
token = self.hashed_token_expired
)
assert not db_query.exists()
def test_token_not_saved_to_db(self):
""" confirm generated token not saved to the database """
db_query = AuthToken.objects.filter(
token = self.api_token_valid
)
assert not db_query.exists()
def test_header_format_invalid_token(self):
""" token header format check
header missing 'Token' prefix reports invalid
"""
client = Client()
url = reverse('home') + 'api/'
response = client.get(
url,
content_type='application/json',
headers = {
'Accept': 'application/json',
'Authorization': '' + self.api_token_valid,
}
)
content: dict = json.loads(response.content.decode('utf-8'))
assert response.status_code == 401 and content['detail'] == 'Token header invalid'
def test_header_format_invalid_token_spaces(self):
""" token header format check
auth header with extra spaces reports invalid
"""
client = Client()
url = reverse('home') + 'api/'
response = client.get(
url,
content_type='application/json',
headers = {
'Accept': 'application/json',
'Authorization': 'Token A space ' + self.api_token_valid,
}
)
content: dict = json.loads(response.content.decode('utf-8'))
assert response.status_code == 401 and content['detail'] == 'Token header invalid. Possibly incorrectly formatted'

View File

@ -3,7 +3,7 @@ from django.urls import path
from rest_framework.routers import DefaultRouter
from rest_framework.urlpatterns import format_suffix_patterns
from .views import access, index
from .views import access, config, index
from .views.itam import software, config as itam_config
from .views.itam.device import DeviceViewSet
@ -24,6 +24,9 @@ router.register('software', software.SoftwareViewSet, basename='software')
urlpatterns = [
path("config/<slug:slug>/", itam_config.View.as_view(), name="_api_device_config"),
path("configuration/", config.ConfigGroupsList.as_view(), name='_api_config_groups'),
path("configuration/<int:pk>", config.ConfigGroupsDetail.as_view(), name='_api_config_group'),
path("device/inventory", inventory.Collect.as_view(), name="_api_device_inventory"),
path("organization/", access.OrganizationList.as_view(), name='_api_orgs'),

View File

@ -1,5 +1,7 @@
from django.contrib.auth.models import Permission
from drf_spectacular.utils import extend_schema, extend_schema_view, OpenApiResponse
from rest_framework import generics, routers, serializers, views
from rest_framework.permissions import DjangoObjectPermissions
from rest_framework.response import Response
@ -7,12 +9,17 @@ from rest_framework.response import Response
from access.mixin import OrganizationMixin
from access.models import Organization, Team
from api.serializers.access import OrganizationSerializer, OrganizationListSerializer, TeamSerializer
from api.serializers.access import OrganizationSerializer, OrganizationListSerializer, TeamSerializer, TeamPermissionSerializer
from api.views.mixin import OrganizationPermissionAPI
class OrganizationList(generics.ListCreateAPIView):
@extend_schema_view(
get=extend_schema(
summary = "Fetch Organizations",
description="Returns a list of organizations."
),
)
class OrganizationList(generics.ListAPIView):
permission_classes = [
OrganizationPermissionAPI
@ -28,7 +35,18 @@ class OrganizationList(generics.ListCreateAPIView):
class OrganizationDetail(generics.RetrieveUpdateDestroyAPIView):
@extend_schema_view(
get=extend_schema(
summary = "Get An Organization",
),
patch=extend_schema(
summary = "Update an organization",
),
put=extend_schema(
summary = "Update an organization",
),
)
class OrganizationDetail(generics.RetrieveUpdateAPIView):
permission_classes = [
OrganizationPermissionAPI
@ -44,6 +62,20 @@ class OrganizationDetail(generics.RetrieveUpdateDestroyAPIView):
@extend_schema_view(
post=extend_schema(
summary = "Create a Team",
description = """Create a team within the defined organization.""",
tags = ['team',],
request = TeamSerializer,
responses = {
200: OpenApiResponse(description='Team has been updated with the supplied permissions'),
401: OpenApiResponse(description='User Not logged in'),
403: OpenApiResponse(description='User is missing permission or in different organization'),
}
),
create=extend_schema(exclude=True),
)
class TeamList(generics.ListCreateAPIView):
permission_classes = [
@ -66,6 +98,45 @@ class TeamList(generics.ListCreateAPIView):
@extend_schema_view(
get=extend_schema(
summary = "Fetch a Team",
description = """Fetch a team within the defined organization.
""",
methods=["GET"],
tags = ['team',],
request = TeamSerializer,
responses = {
200: OpenApiResponse(description='Team has been updated with the supplied permissions'),
401: OpenApiResponse(description='User Not logged in'),
403: OpenApiResponse(description='User is missing permission or in different organization'),
}
),
patch=extend_schema(
summary = "Update a Team",
description = """Update a team within the defined organization.
""",
methods=["Patch"],
tags = ['team',],
request = TeamSerializer,
responses = {
200: OpenApiResponse(description='Team has been updated with the supplied permissions'),
401: OpenApiResponse(description='User Not logged in'),
403: OpenApiResponse(description='User is missing permission or in different organization'),
}
),
put = extend_schema(
summary = "Amend a team",
tags = ['team',],
),
delete=extend_schema(
summary = "Delete a Team",
tags = ['team',],
),
post = extend_schema(
exclude = True,
)
)
class TeamDetail(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [
@ -79,12 +150,66 @@ class TeamDetail(generics.RetrieveUpdateDestroyAPIView):
class TeamPermissionDetail(routers.APIRootView):
@extend_schema_view(
get=extend_schema(
summary = "Fetch a teams permissions",
tags = ['team',],
),
post=extend_schema(
summary = "Replace team Permissions",
description = """Replace the teams permissions with the permissions supplied.
# temp disabled until permission checker updated
# permission_classes = [
# OrganizationPermissionAPI
# ]
Teams Permissions will be replaced with the permissions supplied. **ALL** existing permissions will be
removed.
permissions are required to be in format `<module name>_<permission>_<table name>`
""",
methods=["POST"],
tags = ['team',],
request = TeamPermissionSerializer,
responses = {
200: OpenApiResponse(description='Team has been updated with the supplied permissions'),
401: OpenApiResponse(description='User Not logged in'),
403: OpenApiResponse(description='User is missing permission or in different organization'),
}
),
delete=extend_schema(
summary = "Delete permissions",
tags = ['team',],
),
patch = extend_schema(
summary = "Amend team Permissions",
description = """Amend the teams permissions with the permissions supplied.
Teams permissions will include the existing permissions along with the ones supplied.
permissions are required to be in format `<module name>_<permission>_<table name>`
""",
methods=["PATCH"],
parameters = None,
tags = ['team',],
request = TeamPermissionSerializer,
responses = {
200: OpenApiResponse(description='Team has been updated with the supplied permissions'),
401: OpenApiResponse(description='User Not logged in'),
403: OpenApiResponse(description='User is missing permission or in different organization'),
}
),
put = extend_schema(
summary = "Amend team Permissions",
tags = ['team',],
)
)
class TeamPermissionDetail(views.APIView):
permission_classes = [
OrganizationPermissionAPI
]
queryset = Team.objects.all()
serializer_class = TeamPermissionSerializer
def get(self, request, *args, **kwargs):

54
app/api/views/config.py Normal file
View File

@ -0,0 +1,54 @@
from drf_spectacular.utils import extend_schema, extend_schema_view
from rest_framework import generics
from api.serializers.config import ConfigGroupsSerializer
from api.views.mixin import OrganizationPermissionAPI
from config_management.models.groups import ConfigGroups
@extend_schema_view(
get=extend_schema(
summary = "Fetch Config groups",
description="Returns a list of Config Groups."
),
)
class ConfigGroupsList(generics.ListAPIView):
permission_classes = [
OrganizationPermissionAPI
]
queryset = ConfigGroups.objects.all()
lookup_field = 'pk'
serializer_class = ConfigGroupsSerializer
def get_view_name(self):
return "Config Groups"
@extend_schema_view(
get=extend_schema(
summary = "Get A Config Group",
# responses = {}
),
)
class ConfigGroupsDetail(generics.RetrieveAPIView):
permission_classes = [
OrganizationPermissionAPI
]
queryset = ConfigGroups.objects.all()
lookup_field = 'pk'
serializer_class = ConfigGroupsSerializer
def get_view_name(self):
return "Config Group"

View File

@ -27,6 +27,7 @@ class Index(viewsets.ViewSet):
{
# "teams": reverse("_api_teams", request=request),
"devices": reverse("API:device-list", request=request),
"config_groups": reverse("API:_api_config_groups", request=request),
"organizations": reverse("API:_api_orgs", request=request),
"software": reverse("API:software-list", request=request),
}

View File

@ -1,27 +1,25 @@
# from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin
import json
import re
from django.http import JsonResponse
from django.utils import timezone
from django.core.exceptions import ValidationError, PermissionDenied
from drf_spectacular.utils import extend_schema, OpenApiResponse
from rest_framework import generics, views
from rest_framework.response import Response
from access.mixin import OrganizationMixin
from access.models import Organization
from api.views.mixin import OrganizationPermissionAPI
from api.serializers.itam.inventory import InventorySerializer
from api.serializers.inventory import Inventory
from core.http.common import Http
from itam.models.device import Device, DeviceType, DeviceOperatingSystem, DeviceSoftware
from itam.models.operating_system import OperatingSystem, OperatingSystemVersion
from itam.models.software import Software, SoftwareCategory, SoftwareVersion
from itam.models.device import Device
from settings.models.app_settings import AppSettings
from settings.models.user_settings import UserSettings
from api.tasks import process_inventory
class InventoryPermissions(OrganizationPermissionAPI):
@ -30,271 +28,94 @@ class InventoryPermissions(OrganizationPermissionAPI):
data = view.request.data
self.obj = Device.objects.get(slug=str(data['details']['name']).lower())
self.obj = Device.objects.get(slug=str(data.details.name).lower())
return super().permission_check(request, view, obj=None)
class Collect(OrganizationMixin, views.APIView):
permission_classes = [
InventoryPermissions
]
class Collect(OrganizationPermissionAPI, views.APIView):
queryset = Device.objects.all()
@extend_schema(
summary = "Upload a device's inventory",
description = """After inventorying a device, it's inventory file, `.json` is uploaded to this endpoint.
If the device does not exist, it will be created. If the device does exist the existing
device will be updated with the information within the inventory.
matching for an existing device is by slug which is the hostname converted to lower case
letters. This conversion is automagic.
**NOTE:** _for device creation, the API user must have user setting 'Default Organization'. Without
this setting populated, no device will be created and the endpoint will return HTTP/403_
## Permissions
- `itam.add_device` Required to upload inventory
""",
methods=["POST"],
parameters = None,
tags = ['device', 'inventory',],
request = InventorySerializer,
responses = {
200: OpenApiResponse(description='Inventory upload successful'),
401: OpenApiResponse(description='User Not logged in'),
403: OpenApiResponse(description='User is missing permission or in different organization'),
500: OpenApiResponse(description='Exception occured. View server logs for the Stack Trace'),
}
)
def post(self, request, *args, **kwargs):
data = json.loads(request.body)
status = Http.Status.BAD_REQUEST
device = None
device_operating_system = None
operating_system = None
operating_system_version = None
status = Http.Status.OK
response_data = 'OK'
try:
default_organization = UserSettings.objects.get(user=request.user).default_organization
data = json.loads(request.body)
data = Inventory(data)
app_settings = AppSettings.objects.get(owner_organization = None)
device = None
if Device.objects.filter(name=data['details']['name']).exists():
device = Device.objects.get(name=data['details']['name'])
else: # Create the device
self.default_organization = UserSettings.objects.get(user=request.user).default_organization
device = Device.objects.create(
name = data['details']['name'],
device_type = None,
serial_number = data['details']['serial_number'],
uuid = data['details']['uuid'],
organization = default_organization,
)
if Device.objects.filter(slug=str(data.details.name).lower()).exists():
status = Http.Status.CREATED
self.obj = Device.objects.get(slug=str(data.details.name).lower())
device = self.obj
if OperatingSystem.objects.filter( slug=data['os']['name'] ).exists():
operating_system = OperatingSystem.objects.get( slug=data['os']['name'] )
if not self.permission_check(request=request, view=self, obj=device):
else: # Create Operating System
raise Http404
operating_system = OperatingSystem.objects.create(
name = data['os']['name'],
organization = default_organization,
is_global = True
)
task = process_inventory.delay(request.body, self.default_organization.id)
response_data: dict = {"task_id": f"{task.id}"}
if OperatingSystemVersion.objects.filter( name=data['os']['version_major'], operating_system=operating_system ).exists():
except PermissionDenied as e:
operating_system_version = OperatingSystemVersion.objects.get(
organization = default_organization,
is_global = True,
name = data['os']['version_major'],
operating_system = operating_system
)
status = Http.Status.FORBIDDEN
response_data = ''
else: # Create Operating System Version
operating_system_version = OperatingSystemVersion.objects.create(
organization = default_organization,
is_global = True,
name = data['os']['version_major'],
operating_system = operating_system,
)
if DeviceOperatingSystem.objects.filter( version=data['os']['version'], device=device, operating_system_version=operating_system_version ).exists():
device_operating_system = DeviceOperatingSystem.objects.get(
device=device,
version = data['os']['version'],
operating_system_version = operating_system_version,
)
if not device_operating_system.installdate: # Only update install date if empty
device_operating_system.installdate = timezone.now()
device_operating_system.save()
else: # Create Operating System Version
device_operating_system = DeviceOperatingSystem.objects.create(
organization = default_organization,
device=device,
version = data['os']['version'],
operating_system_version = operating_system_version,
installdate = timezone.now()
)
if app_settings.software_is_global:
software_organization = app_settings.global_organization
else:
software_organization = device.organization
if app_settings.software_categories_is_global:
software_category_organization = app_settings.global_organization
else:
software_category_organization = device.organization
for inventory in list(data['software']):
software = None
software_category = None
software_version = None
device_software = None
if SoftwareCategory.objects.filter( name = inventory['category'] ).exists():
software_category = SoftwareCategory.objects.get(
name = inventory['category']
)
else: # Create Software Category
software_category = SoftwareCategory.objects.create(
organization = software_category_organization,
is_global = True,
name = inventory['category'],
)
if Software.objects.filter( name = inventory['name'] ).exists():
software = Software.objects.get(
name = inventory['name']
)
if not software.category:
software.category = software_category
software.save()
else: # Create Software
software = Software.objects.create(
organization = software_organization,
is_global = True,
name = inventory['name'],
category = software_category,
)
pattern = r"^(\d+:)?(?P<semver>\d+\.\d+(\.\d+)?)"
semver = re.search(pattern, str(inventory['version']), re.DOTALL)
if semver:
semver = semver['semver']
else:
semver = inventory['version']
if SoftwareVersion.objects.filter( name = semver, software = software ).exists():
software_version = SoftwareVersion.objects.get(
name = semver,
software = software,
)
else: # Create Software Category
software_version = SoftwareVersion.objects.create(
organization = default_organization,
is_global = True,
name = semver,
software = software,
)
if DeviceSoftware.objects.filter( software = software, device=device ).exists():
device_software = DeviceSoftware.objects.get(
device = device,
software = software
)
else: # Create Software
device_software = DeviceSoftware.objects.create(
organization = default_organization,
is_global = True,
installedversion = software_version,
software = software,
device = device,
action=None
)
if device_software: # Update the Inventoried software
clear_installed_software = DeviceSoftware.objects.filter(
device = device,
software = software
)
# Clear installed version of all installed software
# any found later with no version to be removed
clear_installed_software.update(installedversion=None)
if not device_software.installed: # Only update install date if blank
device_software.installed = timezone.now()
device_software.save()
device_software.installedversion = software_version
device_software.save()
if device and operating_system and operating_system_version and device_operating_system:
# Remove software no longer installed
DeviceSoftware.objects.filter(
device = device,
software = software,
).delete()
device.inventorydate = timezone.now()
device.save()
status = Http.Status.OK
except ValidationError as e:
status = Http.Status.BAD_REQUEST
response_data = e.message
except Exception as e:
print(f'An error occured{e}')
status = Http.Status.SERVER_ERROR
response_data = 'Unknown Server Error occured'
return Response(data='OK',status=status)
return Response(data=response_data,status=status)

View File

@ -3,6 +3,8 @@ from django.shortcuts import get_object_or_404
from rest_framework import generics, viewsets
from access.mixin import OrganizationMixin
from api.serializers.itam.software import SoftwareSerializer
from api.views.mixin import OrganizationPermissionAPI
@ -10,7 +12,7 @@ from itam.models.software import Software
class SoftwareViewSet(viewsets.ModelViewSet):
class SoftwareViewSet(OrganizationMixin, viewsets.ModelViewSet):
permission_classes = [
OrganizationPermissionAPI

View File

@ -1,6 +1,7 @@
from django.core.exceptions import PermissionDenied
from django.forms import ValidationError
from rest_framework import exceptions
from rest_framework.permissions import DjangoObjectPermissions
from access.mixin import OrganizationMixin
@ -28,12 +29,16 @@ class OrganizationPermissionAPI(DjangoObjectPermissions, OrganizationMixin):
self.request = request
method = self.request._request.method.lower()
if method.upper() not in view.allowed_methods:
view.http_method_not_allowed(request._request)
if hasattr(view, 'queryset'):
if view.queryset.model._meta:
self.obj = view.queryset.model
method = self.request._request.method.lower()
object_organization = None
if method == 'get':
@ -50,7 +55,6 @@ class OrganizationPermissionAPI(DjangoObjectPermissions, OrganizationMixin):
raise ValidationError('you must provide an organization')
object_organization = int(request.data['organization'])
elif method == 'patch':
action = 'change'
@ -126,12 +130,17 @@ class OrganizationPermissionAPI(DjangoObjectPermissions, OrganizationMixin):
return True
if hasattr(self, 'default_organization'):
object_organization = self.default_organization
if object_organization is None:
if method == 'post' and hasattr(self, 'default_organization'):
raise Exception("unable to determine object organization")
if self.default_organization:
object_organization = self.default_organization.id
if not self.has_organization_permission(object_organization) and not request.user.is_superuser:
return False
raise PermissionDenied('You are not part of this organization')
return True

View File

@ -0,0 +1,3 @@
from .celery import worker as celery_app
__all__ = ('celery_app',)

18
app/app/celery.py Normal file
View File

@ -0,0 +1,18 @@
import os
from django.conf import settings
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
worker = Celery('app')
worker.config_from_object(f'django.conf:settings', namespace='CELERY')
worker.autodiscover_tasks()
@worker.task(bind=True, ignore_result=True)
def debug_task(self):
print(f'Request: {self!r}')

View File

@ -5,6 +5,8 @@ from app.urls import urlpatterns
from django.conf import settings
from django.urls import URLPattern, URLResolver
from access.models import Organization
from settings.models.user_settings import UserSettings
@ -21,6 +23,34 @@ def request(request):
return request.get_full_path()
def social_backends(request):
""" Fetch Backend Names
Required for use on the login page to dynamically build the social auth URLS
Returns:
list(str): backend name
"""
from importlib import import_module
social_backends = []
if hasattr(settings, 'SSO_BACKENDS'):
for backend in settings.SSO_BACKENDS:
paths = str(backend).split('.')
module = import_module(paths[0] + '.' + paths[1] + '.' + paths[2])
backend_class = getattr(module, paths[3])
backend = backend_class.name
social_backends += [ str(backend) ]
return social_backends
def user_settings(context) -> int:
""" Provides the settings ID for the current user.
@ -44,6 +74,23 @@ def user_settings(context) -> int:
return None
def user_default_organization(context) -> int:
""" Provides the users default organization.
Returns:
int: Users Default Organization
"""
if context.user.is_authenticated:
settings = UserSettings.objects.filter(user=context.user)
if settings[0].default_organization:
return settings[0].default_organization.id
return None
def nav_items(context) -> list(dict()):
""" Fetch All Project URLs
@ -60,7 +107,7 @@ def nav_items(context) -> list(dict()):
is_active: {bool} if this link is the active URL
Returns:
_type_: _description_
list: Items user has view access to
"""
dnav = []
@ -74,6 +121,7 @@ def nav_items(context) -> list(dict()):
'admin',
'djdt', # Debug application
'api',
'social',
]
nav_items = []
@ -113,11 +161,45 @@ def nav_items(context) -> list(dict()):
name = str(pattern.name)
nav_items = nav_items + [ {
'name': name,
'url': url,
'is_active': is_active
} ]
if hasattr(pattern.callback.view_class, 'permission_required'):
permissions_required = pattern.callback.view_class.permission_required
user_has_perm = False
if type(permissions_required) is list:
user_has_perm = context.user.has_perms(permissions_required)
else:
user_has_perm = context.user.has_perm(permissions_required)
if hasattr(pattern.callback.view_class, 'model'):
if pattern.callback.view_class.model is Organization and context.user.is_authenticated:
organizations = Organization.objects.filter(manager = context.user)
if len(organizations) > 0:
user_has_perm = True
if str(nav_group.app_name).lower() == 'settings':
user_has_perm = True
if context.user.is_superuser:
user_has_perm = True
if user_has_perm:
nav_items = nav_items + [ {
'name': name,
'url': url,
'is_active': is_active
} ]
if len(nav_items) > 0:
@ -136,5 +218,7 @@ def common(context):
return {
'build_details': build_details(context),
'nav_items': nav_items(context),
'social_backends': social_backends(context),
'user_settings': user_settings(context),
'user_default_organization': user_default_organization(context)
}

View File

@ -0,0 +1,33 @@
def merge_software(software: list, new_software: list) -> list:
""" Merge two lists of software actions
Args:
software (list(dict)): Original list to merge over
new_software (list(dict)): new list to use to merge over
Returns:
list(dict): merged list of software actions
"""
merge_software = []
merge: dict = {}
for original in software:
merge.update({
original['name']: original
})
for new in new_software:
merge.update({
new['name']: new
})
for key, value in merge.items():
merge_software = merge_software + [ value ]
return merge_software

View File

@ -11,6 +11,7 @@ https://docs.djangoproject.com/en/5.0/ref/settings/
"""
import os
import sys
from pathlib import Path
from split_settings.tools import optional, include
@ -23,20 +24,80 @@ SETTINGS_DIR = '/etc/itsm' # Primary Settings Directory
BUILD_REPO = os.getenv('CI_PROJECT_URL')
BUILD_SHA = os.getenv('CI_COMMIT_SHA')
BUILD_VERSION = os.getenv('CI_COMMIT_TAG')
DOCS_ROOT = 'https://nofusscomputing.com/projects/centurion_erp/user/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-b*41-$afq0yl)1e#qpz^-nbt-opvjwb#avv++b9rfdxa@b55sk'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Celery settings
CELERY_ACCEPT_CONTENT = ['json']
CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True # broker_connection_retry_on_startup
CELERY_BROKER_URL = 'amqp://guest:guest@172.16.10.102:30712/itsm'
# https://docs.celeryq.dev/en/stable/userguide/configuration.html#broker-use-ssl
# import ssl
# broker_use_ssl = {
# 'keyfile': '/var/ssl/private/worker-key.pem',
# 'certfile': '/var/ssl/amqp-server-cert.pem',
# 'ca_certs': '/var/ssl/myca.pem',
# 'cert_reqs': ssl.CERT_REQUIRED
# }
CELERY_BROKER_POOL_LIMIT = 3 # broker_pool_limit
CELERY_CACHE_BACKEND = 'django-cache'
CELERY_ENABLE_UTC = True
CELERY_RESULT_BACKEND = 'django-db'
CELERY_RESULT_EXTENDED = True
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
CELERY_TASK_DEFAULT_EXCHANGE = 'ITSM' # task_default_exchange
CELERY_TASK_DEFAULT_PRIORITY = 10 # 1-10=LOW-HIGH task_default_priority
# CELERY_TASK_DEFAULT_QUEUE = 'background'
CELERY_TASK_TIME_LIMIT = 3600 # task_time_limit
CELERY_TASK_TRACK_STARTED = True # task_track_started
# dont set concurrency for docer as it defaults to CPU count
CELERY_WORKER_CONCURRENCY = 2 # worker_concurrency - Default: Number of CPU cores
CELERY_WORKER_DEDUPLICATE_SUCCESSFUL_TASKS = True # worker_deduplicate_successful_tasks
CELERY_WORKER_MAX_TASKS_PER_CHILD = 1 # worker_max_tasks_per_child
# CELERY_WORKER_MAX_MEMORY_PER_CHILD = 10000 # 10000=10mb worker_max_memory_per_child - Default: No limit. Type: int (kilobytes)
# CELERY_TASK_SEND_SENT_EVENT = True
CELERY_WORKER_SEND_TASK_EVENTS = True # worker_send_task_events
# django setting.
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'my_cache_table',
}
}
#
# Defaults
#
ALLOWED_HOSTS = [ '*' ] # Site host to serve
DEBUG = False # SECURITY WARNING: don't run with debug turned on in production!
SITE_URL = 'http://127.0.0.1' # domain with HTTP method for the sites URL
SECRET_KEY = None # You need to generate this
SESSION_COOKIE_AGE = 1209600 # Age the session cookie should live for in seconds.
SSO_ENABLED = False # Enable SSO
SSO_LOGIN_ONLY_BACKEND = None # Use specified SSO backend as the ONLY method to login. (builting login form will not be used)
TRUSTED_ORIGINS = [] # list of trusted domains for CSRF
ALLOWED_HOSTS = [ '*' ]
# Application definition
# CSRF_COOKIE_SECURE = True
# SECURE_HSTS_SECONDS = # ToDo: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-SECURE_HSTS_SECONDS
# SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # ToDo: https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header
# SECURE_SSL_REDIRECT = True
# SECURE_SSL_HOST = # ToDo: https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-host
# SESSION_COOKIE_SECURE = True
# USE_X_FORWARDED_HOST = True # ToDo: https://docs.djangoproject.com/en/dev/ref/settings/#use-x-forwarded-host
INSTALLED_APPS = [
'django.contrib.admin',
@ -47,8 +108,8 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
'rest_framework',
'rest_framework_json_api',
'rest_framework.authtoken',
'social_django',
'django_celery_results',
'core.apps.CoreConfig',
'access.apps.AccessConfig',
'itam.apps.ItamConfig',
@ -100,7 +161,7 @@ WSGI_APPLICATION = 'app.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'NAME': str(BASE_DIR / 'db.sqlite3'),
}
}
@ -156,7 +217,7 @@ STATICFILES_DIRS = [
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
SITE_TITLE = "Site Title"
SITE_TITLE = "Centurion ERP"
API_ENABLED = True
@ -174,7 +235,7 @@ if API_ENABLED:
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'api.auth.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PAGINATION_CLASS':
@ -209,23 +270,77 @@ if API_ENABLED:
}
SPECTACULAR_SETTINGS = {
'TITLE': 'Your Project API',
'DESCRIPTION': 'Your project description',
'TITLE': 'ITSM API',
'DESCRIPTION': """This UI is intended to serve as the API documentation.
## Authentication
Access to the API is restricted and requires authentication. Available authentication methods are:
- Session
- Token
Session authentication is made available after logging into the application via the login interface.
Token authentication is via an API token that a user will generate within their
[settings panel](https://nofusscomputing.com/projects/django-template/user/user_settings/#api-tokens).
## Examples
curl:
- Simple API Request: `curl -X GET <url>/api/ -H 'Authorization: Token <token>'`
- Post an Inventory File:
``` bash
curl --header "Content-Type: application/json" \\
--header "Authorization: Token <token>" \\
--request POST \\
--data @<path to inventory file>/<file name>.json \\
<url>/api/device/inventory
```
""",
'VERSION': '1.0.0',
'SERVE_INCLUDE_SCHEMA': False,
'SWAGGER_UI_DIST': 'SIDECAR',
'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
'REDOC_DIST': 'SIDECAR',
'PREPROCESSING_HOOKS': [
'drf_spectacular.hooks.preprocess_exclude_path_format'
],
}
DATETIME_FORMAT = 'j N Y H:i:s'
#
# Settings for unit tests
#
RUNNING_TESTS = 'test' in str(sys.argv)
if RUNNING_TESTS:
SECRET_KEY = 'django-insecure-tests_are_being_run'
#
# Load user settings files
#
if os.path.isdir(SETTINGS_DIR):
settings_files = os.path.join(SETTINGS_DIR, '*.py')
include(optional(settings_files))
#
# Settings to reset to prevent user from over-riding
#
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
CSRF_TRUSTED_ORIGINS = [
SITE_URL,
*TRUSTED_ORIGINS
]
if DEBUG:
INSTALLED_APPS += [
@ -245,3 +360,25 @@ if DEBUG:
'information.apps.InformationConfig',
'project_management.apps.ProjectManagementConfig',
]
if SSO_ENABLED:
if SSO_LOGIN_ONLY_BACKEND:
LOGIN_URL = f'/sso/login/{SSO_LOGIN_ONLY_BACKEND}/'
AUTHENTICATION_BACKENDS += (
*SSO_BACKENDS,
)
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'social_core.pipeline.user.get_username',
'social_core.pipeline.social_auth.associate_by_email',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)

View File

Some files were not shown because too many files have changed in this diff Show More