Renaming Registration model to Task

Change-Id: I83801c7bf40360d36d4e6ddcd17238cf39792c58
This commit is contained in:
adriant 2015-08-12 16:58:40 +12:00 committed by Dale Smith
parent 8a7c4d6a89
commit af54cdf650
17 changed files with 317 additions and 317 deletions

View File

@ -14,20 +14,20 @@ The base use case is three stages:
* Recieve Request
* Validate request data against action serializers.
* If valid, setup Registration to represent the request, and the Actions specified for that ActionView.
* The service runs the pre_approve function on all actions which should do any self validation to mark the actions themselves as valid or invalid, and populating the nodes in the Registration based on that.
* If valid, setup Task to represent the request, and the Actions specified for that ActionView.
* The service runs the pre_approve function on all actions which should do any self validation to mark the actions themselves as valid or invalid, and populating the nodes in the Task based on that.
* Admin Approval
* An admin looks at the Registration and its notes.
* An admin looks at the Task and its notes.
* If they decide it is safe to approve, they do so.
* If there are any invalid actions approval will do nothing until the action data is updated and initial validation is rerun.
* The service runs the post_approve function on all actions.
* If any of the actions require a Token to be issued and emailed for additional data such as a user password, then that will occur.
* If no Token is required, the Registration will run submit actions, and be marked as complete.
* If no Token is required, the Task will run submit actions, and be marked as complete.
* Token Submit
* User submits the Token data.
* The service runs the submit function on all actions, passing along the Token data, normally a password.
* The action will then complete with the given final data.
* Registration is marked as complete.
* Task is marked as complete.
There are cases and ActionViews that auto-approve, and thus automatically do the middle step right after the first. There are also others which do not need a Token and thus run the submit step as part of the second, or even all three at once. The exact number of 'steps' and the time between them depends on the definition of the ActionView.
@ -35,7 +35,7 @@ Actions themselves can also effectively do anything within the scope of those th
The points that are modular, or will be made more modular in future, are the ActionViews and the actions tied to them. Adding new actions is easy, and attaching them to existing ActionViews is as well. Adding new ActionViews is also fairly easy, but will be made more modular in future (see Future Plans).
Creation and management of Registrations, Tokens, and Notifications is not modular and is the framework around the defined Actions and ActionViews that handles how they are executed. This helps keep the way Actions are executed consistent and simpler to maintain, but does also allow Actions to run almost any logic within those consistent steps.
Creation and management of Tasks, Tokens, and Notifications is not modular and is the framework around the defined Actions and ActionViews that handles how they are executed. This helps keep the way Actions are executed consistent and simpler to maintain, but does also allow Actions to run almost any logic within those consistent steps.
#### Default Action Endpoints:
@ -44,7 +44,7 @@ Creation and management of Registrations, Tokens, and Notifications is not modul
* ../project - POST
* unauthenticated endpoint
* for signup of new users/projects.
* registration requires manual approval, sends a uri+token for password setup after the project is created and setup.
* task requires manual approval, sends a uri+token for password setup after the project is created and setup.
* create project
* add admin user to project
* setup basic networking if needed
@ -66,20 +66,20 @@ Creation and management of Registrations, Tokens, and Notifications is not modul
#### Admin Endpoints:
* ../registration - GET
* A json containing all registrations.
* ../task - GET
* A json containing all tasks.
* This will be updated to take parameters to refine the list.
* ../registration/<uuid> - GET
* Get details for a specific registration.
* ../registration/<uuid> - PUT
* Update a registration and retrigger pre_approve.
* ../registration/<uuid> - POST
* approve a registration
* ../task/<uuid> - GET
* Get details for a specific task.
* ../task/<uuid> - PUT
* Update a task and retrigger pre_approve.
* ../task/<uuid> - POST
* approve a task
* ../token - GET
* A json containing all tokens.
* This will be updated to take parameters to refine the list.
* ../token - POST
* Reissue tokens for a given registration.
* Reissue tokens for a given task.
* ../token - DELETE
* Delete all expired tokens.
* ../token/<uuid> - GET
@ -109,25 +109,25 @@ If that was the case, the system should ideally also have been modular enough to
#### What is an Action?
Actions are a generic database model which knows what 'type' of action it is. On pulling the actions related to a Registration from the database we wrap it into the appropriate class type which handlings all the logic associated with that action type.
Actions are a generic database model which knows what 'type' of action it is. On pulling the actions related to a Task from the database we wrap it into the appropriate class type which handlings all the logic associated with that action type.
An Action is both a simple database representation of itself, and a more complex in memory class that handles all the logic around it.
Each action class has the functions "pre_approve", "post_approve", and "submit". These relate to stages of the approval process, and any python code can be executed in those functions, some of which should ideally be validation that the data passed makes sense.
Multiple actions can be chained together under one Registration and will execute in the defined order. Actions can pass information along via an in memory cache/field on the registration object, but that is only safe for the same stage of execution. Actions can also store data back to the database if their logic requires some info passed along to a later step of execution.
Multiple actions can be chained together under one Task and will execute in the defined order. Actions can pass information along via an in memory cache/field on the task object, but that is only safe for the same stage of execution. Actions can also store data back to the database if their logic requires some info passed along to a later step of execution.
See 'base.models' for a good idea of Actions.
#### What is a Registration?
#### What is a Task?
A registration is a top level model representation of the request. It wraps the request metadata, and based on the ActionView, will have actions associated with it.
A task is a top level model representation of the request. It wraps the request metadata, and based on the ActionView, will have actions associated with it.
See 'api_v1.models'.
#### What is a Token?
A token is a unique identifier linking to a registration, so that anyone submitting the token will submit to the actions related to the registration.
A token is a unique identifier linking to a task, so that anyone submitting the token will submit to the actions related to the task.
See 'api_v1.models'.
@ -135,9 +135,9 @@ See 'api_v1.models'.
ActionViews are classes which extend the base ActionView class and use it's imbuilt functions to process actions. They also have actions associated with them and the inbuilt functions from the base class are there to process and validate those against data coming in.
The ActionView will process incoming data and build it into a Registration, and the related Action classes.
The ActionView will process incoming data and build it into a Task, and the related Action classes.
They are very simple to define as the inbuilt functions handle all the real logic, but defining which functions of those are called changes the view to create a registration that either requires approval or auto-approves.
They are very simple to define as the inbuilt functions handle all the real logic, but defining which functions of those are called changes the view to create a task that either requires approval or auto-approves.
The base ActionView class has three functions:
@ -146,10 +146,10 @@ The base ActionView class has three functions:
* process_actions
* needs to be called in the ActionView definition
* A function to run the processing and validation of request data for actions.
* Builds and returns the registration object, or the validation errors.
* Builds and returns the task object, or the validation errors.
* approve
* Takes a registration and approves it, running post_approve actions and issuing a token if needed.
* Used only if no admin approval is needed for Registrations create by this ActionView.
* Takes a task and approves it, running post_approve actions and issuing a token if needed.
* Used only if no admin approval is needed for Tasks create by this ActionView.
See 'api_v1.views' and look at the ActionView class to get a better idea.
@ -188,7 +188,7 @@ This section is a work in progress, although eventually there should be a puppet
* Finish and clean up the client/shell tools
* Nicer handling of token emails and email templates
* Tests for username isn't email vs username is email
* Basic admin panel in horizon, and example public forms for registration and token submission.
* Basic admin panel in horizon, and example public forms for task and token submission.
## Future Plans:

View File

@ -73,7 +73,7 @@ ACTIONVIEW_SETTINGS:
template: token.txt
html_template: token.txt
completed:
subject: Registration completed
subject: Task completed
reply: no-reply@example.com
template: completed.txt
html_template: completed.txt
@ -88,7 +88,7 @@ ACTIONVIEW_SETTINGS:
template: token.txt
html_template: token.txt
completed:
subject: Registration completed
subject: Task completed
reply: no-reply@example.com
template: completed.txt
html_template: completed.txt
@ -100,14 +100,14 @@ ACTIONVIEW_SETTINGS:
template: token.txt
html_template: token.txt
completed:
subject: Registration completed
subject: Task completed
reply: no-reply@example.com
template: completed.txt
html_template: completed.txt
EditUser:
emails:
completed:
subject: Registration completed
subject: Task completed
reply: no-reply@example.com
template: completed.txt
html_template: completed.txt

View File

@ -4,12 +4,12 @@ from setuptools import setup, find_packages
setup(
name='stacktask',
version='0.1.0a7',
description='A user registration service for openstack.',
version='0.1.0a8',
description='A user task service for openstack.',
long_description=(
'A registration service to sit alongside keystone and ' +
'A task service to sit alongside keystone and ' +
'add some missing functionality.'),
url='https://github.com/catalyst/openstack-registration',
url='https://github.com/catalyst/stack-task',
author='Adrian Turjak',
author_email='adriant@catalyst.net.nz',
license='Apache 2.0',
@ -20,7 +20,7 @@ setup(
'Programming Language :: Python :: 2.7',
],
keywords='openstack registration keystone users tasks workflow',
keywords='openstack keystone users tasks registration workflow',
packages=find_packages(),
package_data={'stacktask': ['api/v*/templates/*.txt']},

View File

@ -23,7 +23,7 @@ class Migration(migrations.Migration):
],
),
migrations.CreateModel(
name='Registration',
name='Task',
fields=[
('uuid', models.CharField(default=stacktask.api.models.hex_uuid, max_length=200, serialize=False, primary_key=True)),
('reg_ip', models.GenericIPAddressField()),
@ -43,12 +43,12 @@ class Migration(migrations.Migration):
('token', models.CharField(max_length=200, serialize=False, primary_key=True)),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('expires', models.DateTimeField()),
('registration', models.ForeignKey(to='api.Registration')),
('task', models.ForeignKey(to='api.Task')),
],
),
migrations.AddField(
model_name='notification',
name='registration',
field=models.ForeignKey(to='api.Registration'),
name='task',
field=models.ForeignKey(to='api.Task'),
),
]

View File

@ -22,10 +22,10 @@ def hex_uuid():
return uuid4().hex
class Registration(models.Model):
class Task(models.Model):
"""
Wrapper object for the request and related actions.
Stores the state registration and a log for the
Stores the state of the Task and a log for the
action.
"""
uuid = models.CharField(max_length=200, default=hex_uuid,
@ -49,7 +49,7 @@ class Registration(models.Model):
completed_on = models.DateTimeField(null=True)
def __init__(self, *args, **kwargs):
super(Registration, self).__init__(*args, **kwargs)
super(Task, self).__init__(*args, **kwargs)
# in memory dict to be used for passing data between actions:
self.cache = {}
@ -87,28 +87,28 @@ class Registration(models.Model):
class Token(models.Model):
"""
UUID token object bound to a registration.
UUID token object bound to a task.
"""
registration = models.ForeignKey(Registration)
task = models.ForeignKey(Task)
token = models.CharField(max_length=200, primary_key=True)
created = models.DateTimeField(default=timezone.now)
expires = models.DateTimeField()
def to_dict(self):
return {
"registration": self.registration.uuid,
"task": self.task.uuid,
"token": self.token, "expires": self.expires
}
class Notification(models.Model):
"""
Notification linked to a registration with some notes.
Notification linked to a task with some notes.
"""
notes = JSONField(default={})
registration = models.ForeignKey(Registration)
task = models.ForeignKey(Task)
created = models.DateTimeField(default=timezone.now)
acknowledged = models.BooleanField(default=False)
@ -116,7 +116,7 @@ class Notification(models.Model):
return {
"pk": self.pk,
"notes": self.notes,
"registration": self.registration.uuid,
"task": self.task.uuid,
"acknowledged": self.acknowledged,
"created": self.created
}

View File

@ -1,6 +1,6 @@
Hello,
Your registration has been completed.
Your task has been completed.
The actions you had requested are:
{% for action in actions %}

View File

@ -1,13 +1,13 @@
Hello,
Your registration is in our system and now waiting approval.
Your task is in our system and now waiting approval.
The actions you had requested are:
{% for action in actions %}
- {{ action }}
{% endfor %}
Once someone has approved your registration you will be emailed an update.
Once someone has approved your task you will be emailed an update.
Thank you for using our service.

View File

@ -1,6 +1,6 @@
Hello,
Your registrations with our service is almost done.
Your task with our service is almost done.
The action you have requested is:
{% for action in actions %}

View File

@ -14,7 +14,7 @@
from rest_framework import status
from rest_framework.test import APITestCase
from stacktask.api.models import Registration, Token
from stacktask.api.models import Task, Token
import mock
from django.utils import timezone
from datetime import timedelta
@ -129,7 +129,7 @@ class FakeManager(object):
class APITests(APITestCase):
"""Tests to ensure the approval/token workflow does
what is expected. These test don't check final
results for actions, simply that the registrations,
results for actions, simply that the tasks,
action, and tokens are created/updated.
These tests also focus on authentication status
@ -139,7 +139,7 @@ class APITests(APITestCase):
def test_new_user(self):
"""
Ensure the new user workflow goes as expected.
Create registration, create token, submit token.
Create task, create token, submit token.
"""
project = mock.Mock()
project.id = 'test_project_id'
@ -263,7 +263,7 @@ class APITests(APITestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data,
{'notes': 'Registration completed successfully.'})
{'notes': 'Task completed successfully.'})
@mock.patch('stacktask.base.models.IdentityManager', FakeManager)
def test_add_user_existing_with_role(self):
@ -299,7 +299,7 @@ class APITests(APITestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data,
{'notes': 'Registration completed successfully.'})
{'notes': 'Task completed successfully.'})
@mock.patch('stacktask.base.models.IdentityManager', FakeManager)
@mock.patch('stacktask.tenant_setup.models.IdentityManager', FakeManager)
@ -323,8 +323,8 @@ class APITests(APITestCase):
'user_id': "test_user_id",
'authenticated': True
}
new_registration = Registration.objects.all()[0]
url = "/v1/registration/" + new_registration.uuid
new_task = Task.objects.all()[0]
url = "/v1/task/" + new_task.uuid
response = self.client.post(url, {'approved': True}, format='json',
headers=headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
@ -372,8 +372,8 @@ class APITests(APITestCase):
'user_id': "test_user_id",
'authenticated': True
}
new_registration = Registration.objects.all()[0]
url = "/v1/registration/" + new_registration.uuid
new_task = Task.objects.all()[0]
url = "/v1/task/" + new_task.uuid
response = self.client.post(url, {'approved': True}, format='json',
headers=headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@ -416,21 +416,21 @@ class APITests(APITestCase):
'user_id': "test_user_id",
'authenticated': True
}
new_registration = Registration.objects.all()[0]
url = "/v1/registration/" + new_registration.uuid
new_task = Task.objects.all()[0]
url = "/v1/task/" + new_task.uuid
response = self.client.post(url, {'approved': True}, format='json',
headers=headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data,
{'notes': 'Registration completed successfully.'}
{'notes': 'Task completed successfully.'}
)
@mock.patch('stacktask.base.models.IdentityManager', FakeManager)
def test_reset_user(self):
"""
Ensure the reset user workflow goes as expected.
Create registration + create token, submit token.
Create task + create token, submit token.
"""
user = mock.Mock()
@ -488,7 +488,7 @@ class APITests(APITestCase):
self.assertEqual(
response.data, {'errors': ['This token does not exist.']})
def test_no_registration_get(self):
def test_no_task_get(self):
"""
Should be a 404.
"""
@ -500,13 +500,13 @@ class APITests(APITestCase):
'user_id': "test_user_id",
'authenticated': True
}
url = "/v1/registration/e8b3f57f5da64bf3a6bf4f9bbd3a40b5"
url = "/v1/task/e8b3f57f5da64bf3a6bf4f9bbd3a40b5"
response = self.client.get(url, format='json', headers=headers)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(
response.data, {'errors': ['No registration with this id.']})
response.data, {'errors': ['No task with this id.']})
def test_no_registration_post(self):
def test_no_task_post(self):
"""
Should be a 404.
"""
@ -518,11 +518,11 @@ class APITests(APITestCase):
'user_id': "test_user_id",
'authenticated': True
}
url = "/v1/registration/e8b3f57f5da64bf3a6bf4f9bbd3a40b5"
url = "/v1/task/e8b3f57f5da64bf3a6bf4f9bbd3a40b5"
response = self.client.post(url, format='json', headers=headers)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(
response.data, {'errors': ['No registration with this id.']})
response.data, {'errors': ['No task with this id.']})
@mock.patch('stacktask.base.models.IdentityManager', FakeManager)
def test_token_expired_post(self):
@ -585,9 +585,9 @@ class APITests(APITestCase):
@mock.patch('stacktask.base.models.IdentityManager', FakeManager)
@mock.patch('stacktask.tenant_setup.models.IdentityManager', FakeManager)
def test_registration_complete(self):
def test_task_complete(self):
"""
Can't approve a completed registration.
Can't approve a completed task.
"""
setup_temp_cache({}, {})
@ -604,22 +604,22 @@ class APITests(APITestCase):
'user_id': "test_user_id",
'authenticated': True
}
new_registration = Registration.objects.all()[0]
new_registration.completed = True
new_registration.save()
url = "/v1/registration/" + new_registration.uuid
new_task = Task.objects.all()[0]
new_task.completed = True
new_task.save()
url = "/v1/task/" + new_task.uuid
response = self.client.post(url, {'approved': True}, format='json',
headers=headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data,
{'errors': ['This registration has already been completed.']})
{'errors': ['This task has already been completed.']})
@mock.patch('stacktask.base.models.IdentityManager', FakeManager)
@mock.patch('stacktask.tenant_setup.models.IdentityManager', FakeManager)
def test_registration_update(self):
def test_task_update(self):
"""
Creates a invalid registration.
Creates a invalid task.
Updates it and attempts to reapprove.
"""
@ -645,8 +645,8 @@ class APITests(APITestCase):
'authenticated': True
}
new_registration = Registration.objects.all()[0]
url = "/v1/registration/" + new_registration.uuid
new_task = Task.objects.all()[0]
url = "/v1/task/" + new_task.uuid
response = self.client.post(url, {'approved': True}, format='json',
headers=headers)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@ -657,7 +657,7 @@ class APITests(APITestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data,
{'notes': ['Registration successfully updated.']})
{'notes': ['Task successfully updated.']})
response = self.client.post(url, {'approved': True}, format='json',
headers=headers)
@ -680,7 +680,7 @@ class APITests(APITestCase):
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
new_registration = Registration.objects.all()[0]
new_task = Task.objects.all()[0]
headers = {
'project_name': "test_project",
@ -695,8 +695,8 @@ class APITests(APITestCase):
response = self.client.get(url, headers=headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data[0]['registration'],
new_registration.uuid)
response.data[0]['task'],
new_task.uuid)
@mock.patch('stacktask.base.models.IdentityManager', FakeManager)
@mock.patch('stacktask.tenant_setup.models.IdentityManager', FakeManager)
@ -711,7 +711,7 @@ class APITests(APITestCase):
response = self.client.post(url, data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
new_registration = Registration.objects.all()[0]
new_task = Task.objects.all()[0]
headers = {
'project_name': "test_project",
@ -726,8 +726,8 @@ class APITests(APITestCase):
response = self.client.get(url, headers=headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.data[0]['registration'],
new_registration.uuid)
response.data[0]['task'],
new_task.uuid)
url = "/v1/notification/%s/" % response.data[0]['pk']
data = {'acknowledged': True}
@ -853,7 +853,7 @@ class APITests(APITestCase):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, {'notes': ['created token']})
registration = Registration.objects.all()[0]
task = Task.objects.all()[0]
new_token = Token.objects.all()[0]
uuid = new_token.token
@ -867,7 +867,7 @@ class APITests(APITestCase):
'authenticated': True
}
url = "/v1/token/"
data = {"registration": registration.uuid}
data = {"task": task.uuid}
response = self.client.post(url, data, format='json',
headers=headers)
self.assertEqual(response.status_code, status.HTTP_200_OK)

View File

@ -18,8 +18,8 @@ from stacktask.api.v1 import views
urlpatterns = patterns(
'',
url(r'^registration/(?P<uuid>\w+)', views.RegistrationDetail.as_view()),
url(r'^registration', views.RegistrationList.as_view()),
url(r'^task/(?P<uuid>\w+)', views.TaskDetail.as_view()),
url(r'^task', views.TaskList.as_view()),
url(r'^token/(?P<id>\w+)', views.TokenDetail.as_view()),
url(r'^token', views.TokenList.as_view()),
url(r'^notification/(?P<pk>\w+)', views.NotificationDetail.as_view()),

View File

@ -16,7 +16,7 @@ from decorator import decorator
from rest_framework.views import APIView
from rest_framework.response import Response
from stacktask.base.user_store import IdentityManager
from stacktask.api.models import Registration, Token, Notification
from stacktask.api.models import Task, Token, Notification
from django.utils import timezone
from datetime import timedelta
from uuid import uuid4
@ -67,14 +67,14 @@ def admin(func, *args, **kwargs):
return Response({'errors': ["Must be admin."]}, 403)
def create_token(registration):
def create_token(task):
# expire needs to be made configurable.
expire = timezone.now() + timedelta(hours=24)
# is this a good way to create tokens?
uuid = uuid4().hex
token = Token.objects.create(
registration=registration,
task=task,
token=uuid,
expires=expire
)
@ -82,14 +82,14 @@ def create_token(registration):
return token
def send_email(registration, email_conf, token=None):
def send_email(task, email_conf, token=None):
if email_conf:
template = loader.get_template(email_conf['template'])
html_template = loader.get_template(email_conf['html_template'])
emails = set()
actions = []
for action in registration.actions:
for action in task.actions:
act = action.get_action()
email = act.get_email()
if email:
@ -100,18 +100,18 @@ def send_email(registration, email_conf, token=None):
notes = {
'notes':
(("Error: Unable to send token, More than one email for" +
" registration: %s") % registration.uuid)
" task: %s") % task.uuid)
}
create_notification(registration, notes)
create_notification(task, notes)
return
# TODO(adriant): raise some error?
# and surround calls to this function with try/except
if token:
context = {'registration': registration, 'actions': actions,
context = {'task': task, 'actions': actions,
'token': token.token}
else:
context = {'registration': registration, 'actions': actions}
context = {'task': task, 'actions': actions}
try:
message = template.render(Context(context))
@ -122,17 +122,17 @@ def send_email(registration, email_conf, token=None):
except SMTPException as e:
notes = {
'notes':
("Error: '%s' while emailing token for registration: %s" %
(e, registration.uuid))
("Error: '%s' while emailing token for task: %s" %
(e, task.uuid))
}
create_notification(registration, notes)
create_notification(task, notes)
# TODO(adriant): raise some error?
# and surround calls to this function with try/except
def create_notification(registration, notes):
def create_notification(task, notes):
notification = Notification.objects.create(
registration=registration,
task=task,
notes=notes
)
notification.save()
@ -217,36 +217,36 @@ class NotificationDetail(APIViewWithLogger):
status=400)
class RegistrationList(APIViewWithLogger):
class TaskList(APIViewWithLogger):
@admin
def get(self, request, format=None):
"""
A list of dict representations of Registration objects
A list of dict representations of Task objects
and their related actions.
"""
registrations = Registration.objects.all()
tasks = Task.objects.all()
reg_list = []
for registration in registrations:
reg_list.append(registration.to_dict())
for task in tasks:
reg_list.append(task.to_dict())
return Response(reg_list, status=200)
class RegistrationDetail(APIViewWithLogger):
class TaskDetail(APIViewWithLogger):
@admin
def get(self, request, uuid, format=None):
"""
Dict representation of a Registration object
Dict representation of a Task object
and its related actions.
"""
try:
registration = Registration.objects.get(uuid=uuid)
except Registration.DoesNotExist:
task = Task.objects.get(uuid=uuid)
except Task.DoesNotExist:
return Response(
{'errors': ['No registration with this id.']},
{'errors': ['No task with this id.']},
status=404)
return Response(registration.to_dict())
return Response(task.to_dict())
@admin
def put(self, request, uuid, format=None):
@ -255,22 +255,22 @@ class RegistrationDetail(APIViewWithLogger):
of the pre_approve step.
"""
try:
registration = Registration.objects.get(uuid=uuid)
except Registration.DoesNotExist:
task = Task.objects.get(uuid=uuid)
except Task.DoesNotExist:
return Response(
{'errors': ['No registration with this id.']},
{'errors': ['No task with this id.']},
status=404)
if registration.completed:
if task.completed:
return Response(
{'errors':
['This registration has already been completed.']},
['This task has already been completed.']},
status=400)
act_list = []
valid = True
for action in registration.actions:
for action in task.actions:
action_serializer = settings.ACTION_CLASSES[action.action_name][1]
if action_serializer is not None:
@ -300,11 +300,11 @@ class RegistrationDetail(APIViewWithLogger):
except Exception as e:
notes = {
'errors':
[("Error: '%s' while updating registration. " +
"See registration itself for details.") % e],
'registration': registration.uuid
[("Error: '%s' while updating task. " +
"See task itself for details.") % e],
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -320,7 +320,7 @@ class RegistrationDetail(APIViewWithLogger):
return Response(response_dict, status=500)
return Response(
{'notes': ["Registration successfully updated."]},
{'notes': ["Task successfully updated."]},
status=200)
else:
errors = {}
@ -332,23 +332,23 @@ class RegistrationDetail(APIViewWithLogger):
@admin
def post(self, request, uuid, format=None):
"""
Will approve the Registration specified,
Will approve the Task specified,
followed by running the post_approve actions
and if valid will setup and create a related token.
"""
try:
registration = Registration.objects.get(uuid=uuid)
except Registration.DoesNotExist:
task = Task.objects.get(uuid=uuid)
except Task.DoesNotExist:
return Response(
{'errors': ['No registration with this id.']},
{'errors': ['No task with this id.']},
status=404)
if request.data.get('approved', False) is True:
if registration.completed:
if task.completed:
return Response(
{'errors':
['This registration has already been completed.']},
['This task has already been completed.']},
status=400)
need_token = False
@ -356,7 +356,7 @@ class RegistrationDetail(APIViewWithLogger):
actions = []
for action in registration.actions:
for action in task.actions:
act_model = action.get_action()
actions.append(act_model)
try:
@ -364,11 +364,11 @@ class RegistrationDetail(APIViewWithLogger):
except Exception as e:
notes = {
'errors':
[("Error: '%s' while approving registration. " +
"See registration itself for details.") % e],
'registration': registration.uuid
[("Error: '%s' while approving task. " +
"See task itself for details.") % e],
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -384,30 +384,30 @@ class RegistrationDetail(APIViewWithLogger):
need_token = True
if valid:
registration.approved = True
registration.approved_on = timezone.now()
registration.save()
task.approved = True
task.approved_on = timezone.now()
task.save()
if need_token:
token = create_token(registration)
token = create_token(task)
try:
class_conf = settings.ACTIONVIEW_SETTINGS[
registration.action_view]
task.action_view]
# will throw a key error if the token template has not
# been specified
email_conf = class_conf['emails']['token']
send_email(registration, email_conf, token)
send_email(task, email_conf, token)
return Response({'notes': ['created token']},
status=200)
except KeyError as e:
notes = {
'errors':
[("Error: '%s' while sending " +
"token. See registration " +
"token. See task " +
"itself for details.") % e],
'registration': registration.uuid
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -429,11 +429,11 @@ class RegistrationDetail(APIViewWithLogger):
notes = {
'errors':
[("Error: '%s' while submitting " +
"registration. See registration " +
"task. See task " +
"itself for details.") % e],
'registration': registration.uuid
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -443,19 +443,19 @@ class RegistrationDetail(APIViewWithLogger):
return Response(notes, status=500)
registration.completed = True
registration.completed_on = timezone.now()
registration.save()
task.completed = True
task.completed_on = timezone.now()
task.save()
# Sending confirmation email:
class_conf = settings.ACTIONVIEW_SETTINGS.get(
registration.action_view, {})
task.action_view, {})
email_conf = class_conf.get(
'emails', {}).get('completed', None)
send_email(registration, email_conf)
send_email(task, email_conf)
return Response(
{'notes': "Registration completed successfully."},
{'notes': "Task completed successfully."},
status=200)
return Response({'errors': ['actions invalid']}, status=400)
else:
@ -482,47 +482,47 @@ class TokenList(APIViewWithLogger):
@admin
def post(self, request, format=None):
"""
Reissue a token for an approved registration.
Reissue a token for an approved task.
Clears other tokens for it.
"""
uuid = request.data.get('registration', None)
uuid = request.data.get('task', None)
if uuid is None:
return Response(
{'registration': ["This field is required.", ]},
{'task': ["This field is required.", ]},
status=400)
try:
registration = Registration.objects.get(uuid=uuid)
except Registration.DoesNotExist:
task = Task.objects.get(uuid=uuid)
except Task.DoesNotExist:
return Response(
{'errors': ['No registration with this id.']},
{'errors': ['No task with this id.']},
status=404)
if not registration.approved:
if not task.approved:
return Response(
{'errors': ['This registration has not been approved.']},
{'errors': ['This task has not been approved.']},
status=400)
for token in registration.tokens:
for token in task.tokens:
token.delete()
token = create_token(registration)
token = create_token(task)
try:
class_conf = settings.ACTIONVIEW_SETTINGS[
registration.action_view]
task.action_view]
# will throw a key error if the token template has not
# been specified
email_conf = class_conf['emails']['token']
send_email(registration, email_conf, token)
send_email(task, email_conf, token)
except KeyError as e:
notes = {
'errors':
[("Error: '%s' while sending " +
"token. See registration " +
"token. See task " +
"itself for details.") % e],
'registration': registration.uuid
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -563,10 +563,10 @@ class TokenDetail(APIViewWithLogger):
return Response(
{'errors': ['This token does not exist.']}, status=404)
if token.registration.completed:
if token.task.completed:
return Response(
{'errors':
['This registration has already been completed.']},
['This task has already been completed.']},
status=400)
if token.expires < timezone.now():
@ -577,7 +577,7 @@ class TokenDetail(APIViewWithLogger):
required_fields = []
actions = []
for action in token.registration.actions:
for action in token.task.actions:
action = action.get_action()
actions.append(action)
for field in action.token_fields:
@ -599,10 +599,10 @@ class TokenDetail(APIViewWithLogger):
return Response(
{'errors': ['This token does not exist.']}, status=404)
if token.registration.completed:
if token.task.completed:
return Response(
{'errors':
['This registration has already been completed.']},
['This task has already been completed.']},
status=400)
if token.expires < timezone.now():
@ -613,7 +613,7 @@ class TokenDetail(APIViewWithLogger):
required_fields = set()
actions = []
for action in token.registration.actions:
for action in token.task.actions:
action = action.get_action()
actions.append(action)
for field in action.token_fields:
@ -637,11 +637,11 @@ class TokenDetail(APIViewWithLogger):
except Exception as e:
notes = {
'errors':
[("Error: '%s' while submitting registration. " +
"See registration itself for details.") % e],
'registration': token.registration.uuid
[("Error: '%s' while submitting task. " +
"See task itself for details.") % e],
'task': token.task.uuid
}
create_notification(token.registration, notes)
create_notification(token.task, notes)
import traceback
trace = traceback.format_exc()
@ -656,17 +656,17 @@ class TokenDetail(APIViewWithLogger):
}
return Response(response_dict, status=500)
token.registration.completed = True
token.registration.completed_on = timezone.now()
token.registration.save()
token.task.completed = True
token.task.completed_on = timezone.now()
token.task.save()
token.delete()
# Sending confirmation email:
class_conf = settings.ACTIONVIEW_SETTINGS.get(
token.registration.action_view, {})
token.task.action_view, {})
email_conf = class_conf.get(
'emails', {}).get('completed', None)
send_email(token.registration, email_conf)
send_email(token.task, email_conf)
return Response(
{'notes': "Token submitted successfully."},
@ -675,7 +675,7 @@ class TokenDetail(APIViewWithLogger):
class ActionView(APIViewWithLogger):
"""
Base class for api calls that start a Registration.
Base class for api calls that start a Task.
Until it is moved to settings, 'default_action' is a
required hardcoded field.
@ -712,7 +712,7 @@ class ActionView(APIViewWithLogger):
"""
Will ensure the request data contains the required data
based on the action serializer, and if present will create
a Registration and the linked actions, attaching notes
a Task and the linked actions, attaching notes
based on running of the the pre_approve validation
function on all the actions.
"""
@ -747,10 +747,10 @@ class ActionView(APIViewWithLogger):
ip_addr = request.META['REMOTE_ADDR']
keystone_user = request.keystone_user
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip=ip_addr, keystone_user=keystone_user,
action_view=self.__class__.__name__)
registration.save()
task.save()
for i, act in enumerate(act_list):
if act['serializer'] is not None:
@ -758,7 +758,7 @@ class ActionView(APIViewWithLogger):
else:
data = {}
action = act['action'](
data=data, registration=registration,
data=data, task=task,
order=i
)
@ -767,11 +767,11 @@ class ActionView(APIViewWithLogger):
except Exception as e:
notes = {
'errors':
[("Error: '%s' while setting up registration. " +
"See registration itself for details.") % e],
'registration': registration.uuid
[("Error: '%s' while setting up task. " +
"See task itself for details.") % e],
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -788,9 +788,9 @@ class ActionView(APIViewWithLogger):
# send initial conformation email:
email_conf = class_conf.get('emails', {}).get('initial', None)
send_email(registration, email_conf)
send_email(task, email_conf)
return {'registration': registration}
return {'task': task}
else:
errors = {}
for act in act_list:
@ -798,17 +798,17 @@ class ActionView(APIViewWithLogger):
errors.update(act['serializer'].errors)
return {'errors': errors}
def approve(self, registration):
def approve(self, task):
"""
Approves the registration and runs the post_approve steps.
Approves the task and runs the post_approve steps.
Will create a token if required, otherwise will run the
submit steps.
"""
registration.approved = True
registration.approved_on = timezone.now()
registration.save()
task.approved = True
task.approved_on = timezone.now()
task.save()
action_models = registration.actions
action_models = task.actions
actions = []
valid = True
@ -827,11 +827,11 @@ class ActionView(APIViewWithLogger):
except Exception as e:
notes = {
'errors':
[("Error: '%s' while approving registration. " +
"See registration itself for details.") % e],
'registration': registration.uuid
[("Error: '%s' while approving task. " +
"See task itself for details.") % e],
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -853,7 +853,7 @@ class ActionView(APIViewWithLogger):
if valid:
if need_token:
token = create_token(registration)
token = create_token(task)
try:
class_conf = settings.ACTIONVIEW_SETTINGS[
self.__class__.__name__]
@ -861,18 +861,18 @@ class ActionView(APIViewWithLogger):
# will throw a key error if the token template has not
# been specified
email_conf = class_conf['emails']['token']
send_email(registration, email_conf, token)
send_email(task, email_conf, token)
return Response({'notes': ['created token']},
status=200)
except KeyError as e:
notes = {
'errors':
[("Error: '%s' while sending " +
"token. See registration " +
"token. See task " +
"itself for details.") % e],
'registration': registration.uuid
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -894,11 +894,11 @@ class ActionView(APIViewWithLogger):
notes = {
'errors':
[("Error: '%s' while submitting " +
"registration. See registration " +
"task. See task " +
"itself for details.") % e],
'registration': registration.uuid
'task': task.uuid
}
create_notification(registration, notes)
create_notification(task, notes)
import traceback
trace = traceback.format_exc()
@ -913,18 +913,18 @@ class ActionView(APIViewWithLogger):
}
return Response(response_dict, status=500)
registration.completed = True
registration.completed_on = timezone.now()
registration.save()
task.completed = True
task.completed_on = timezone.now()
task.save()
# Sending confirmation email:
class_conf = settings.ACTIONVIEW_SETTINGS.get(
self.__class__.__name__, {})
email_conf = class_conf.get(
'emails', {}).get('completed', None)
send_email(registration, email_conf)
send_email(task, email_conf)
return Response(
{'notes': "Registration completed successfully."},
{'notes': "Task completed successfully."},
status=200)
return Response({'errors': ['actions invalid']}, status=400)
return Response({'errors': ['actions invalid']}, status=400)
@ -939,26 +939,26 @@ class CreateProject(ActionView):
Unauthenticated endpoint bound primarily to NewProject.
This process requires approval, so this will validate
incoming data and create a registration to be approved
incoming data and create a task to be approved
later.
"""
self.logger.info("(%s) - Starting new project registration." %
self.logger.info("(%s) - Starting new project task." %
timezone.now())
processed = self.process_actions(request)
errors = processed.get('errors', None)
if errors:
self.logger.info("(%s) - Validation errors with registration." %
self.logger.info("(%s) - Validation errors with task." %
timezone.now())
return Response(errors, status=400)
notes = {
'notes':
['New registration for CreateProject.']
['New task for CreateProject.']
}
create_notification(processed['registration'], notes)
self.logger.info("(%s) - Registration created." % timezone.now())
return Response({'notes': ['registration created']}, status=200)
create_notification(processed['task'], notes)
self.logger.info("(%s) - Task created." % timezone.now())
return Response({'notes': ['task created']}, status=200)
class AttachUser(ActionView):
@ -974,7 +974,7 @@ class AttachUser(ActionView):
"""
This endpoint requires either Admin access or the
request to come from a project_owner.
As such this Registration is considered pre-approved.
As such this Task is considered pre-approved.
Runs process_actions, then does the approve step and
post_approve validation, and creates a Token if valid.
"""
@ -983,14 +983,14 @@ class AttachUser(ActionView):
errors = processed.get('errors', None)
if errors:
self.logger.info("(%s) - Validation errors with registration." %
self.logger.info("(%s) - Validation errors with task." %
timezone.now())
return Response(errors, status=400)
registration = processed['registration']
task = processed['task']
self.logger.info("(%s) - AutoApproving AttachUser request."
% timezone.now())
return self.approve(registration)
return self.approve(task)
class ResetPassword(ActionView):
@ -1006,14 +1006,14 @@ class ResetPassword(ActionView):
errors = processed.get('errors', None)
if errors:
self.logger.info("(%s) - Validation errors with registration." %
self.logger.info("(%s) - Validation errors with task." %
timezone.now())
return Response(errors, status=400)
registration = processed['registration']
task = processed['task']
self.logger.info("(%s) - AutoApproving Resetuser request."
% timezone.now())
return self.approve(registration)
return self.approve(task)
class EditUser(ActionView):
@ -1067,7 +1067,7 @@ class EditUser(ActionView):
"""
This endpoint requires either mod access or the
request to come from a project_owner.
As such this Registration is considered pre-approved.
As such this Task is considered pre-approved.
Runs process_actions, then does the approve step and
post_approve validation, and creates a Token if valid.
"""
@ -1076,11 +1076,11 @@ class EditUser(ActionView):
errors = processed.get('errors', None)
if errors:
self.logger.info("(%s) - Validation errors with registration." %
self.logger.info("(%s) - Validation errors with task." %
timezone.now())
return Response(errors, status=400)
registration = processed['registration']
task = processed['task']
self.logger.info("(%s) - AutoApproving EditUser request."
% timezone.now())
return self.approve(registration)
return self.approve(task)

View File

@ -25,7 +25,7 @@ class Migration(migrations.Migration):
('need_token', models.BooleanField()),
('order', models.IntegerField()),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('registration', models.ForeignKey(to='api.Registration')),
('task', models.ForeignKey(to='api.Task')),
],
),
]

View File

@ -34,7 +34,7 @@ class Action(models.Model):
state = models.CharField(max_length=200, default="default")
valid = models.BooleanField(default=False)
need_token = models.BooleanField()
registration = models.ForeignKey('api.Registration')
task = models.ForeignKey('api.Task')
order = models.IntegerField()
@ -77,11 +77,11 @@ class BaseAction(object):
By using 'get_cache' and 'set_cache' they can pass data along which
may be needed by the action later. This cache is backed to the database.
Passing data along to other actions is done via the registration and
Passing data along to other actions is done via the task and
it's cache, but this is in memory only, so it is only useful during the
same action stage ('post_approve', etc.).
Other than the registration cache, actions should not be altering database
Other than the task cache, actions should not be altering database
models other than themselves. This is not enforced, just a guideline.
"""
@ -89,7 +89,7 @@ class BaseAction(object):
token_fields = []
def __init__(self, data, action_model=None, registration=None,
def __init__(self, data, action_model=None, task=None,
order=None):
"""
Build itself around an existing database model,
@ -115,7 +115,7 @@ class BaseAction(object):
action_name=self.__class__.__name__,
action_data=data,
need_token=need_token,
registration=registration,
task=task,
order=order
)
action.save()
@ -144,11 +144,11 @@ class BaseAction(object):
def add_note(self, note):
"""
Logs the note, and also adds it to the registration action notes.
Logs the note, and also adds it to the task action notes.
"""
self.logger.info("(%s) - %s" % (timezone.now(), note))
note = "%s - (%s)" % (note, timezone.now())
self.action.registration.add_action_note(
self.action.task.add_action_note(
unicode(self), note)
def pre_approve(self):
@ -218,7 +218,7 @@ class NewUser(UserAction):
user = id_manager.find_user(self.username)
keystone_user = self.action.registration.keystone_user
keystone_user = self.action.task.keystone_user
if not keystone_user['project_id'] == self.project_id:
self.add_note('Project id does not match keystone user project.')
@ -392,7 +392,7 @@ class NewProject(UserAction):
def _post_approve(self):
project_id = self.get_cache('project_id')
if project_id:
self.action.registration.cache['project_id'] = project_id
self.action.task.cache['project_id'] = project_id
self.add_note("Project already created.")
return
@ -410,7 +410,7 @@ class NewProject(UserAction):
(e, self.project_name))
raise
# put project_id into action cache:
self.action.registration.cache['project_id'] = project.id
self.action.task.cache['project_id'] = project.id
self.set_cache('project_id', project.id)
self.add_note("New project '%s' created." % self.project_name)
@ -423,7 +423,7 @@ class NewProject(UserAction):
if self.valid:
project_id = self.get_cache('project_id')
self.action.registration.cache['project_id'] = project_id
self.action.task.cache['project_id'] = project_id
project = id_manager.get_project(project_id)
@ -551,7 +551,7 @@ class EditUser(UserAction):
user = id_manager.find_user(self.username)
keystone_user = self.action.registration.keystone_user
keystone_user = self.action.task.keystone_user
if not keystone_user['project_id'] == self.project_id:
self.add_note('Project id does not match keystone user project.')

View File

@ -13,7 +13,7 @@
# under the License.
from django.test import TestCase
from stacktask.api.models import Registration
from stacktask.api.models import Task
from stacktask.api.v1.tests import FakeManager, setup_temp_cache
from stacktask.api.v1 import tests
from stacktask.base.models import NewUser, NewProject, ResetUser, EditUser
@ -35,7 +35,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({'test_project': project}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -46,7 +46,7 @@ class BaseActionTests(TestCase):
'roles': ['Member']
}
action = NewUser(data, registration=registration, order=1)
action = NewUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -84,7 +84,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({'test_project': project}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -95,7 +95,7 @@ class BaseActionTests(TestCase):
'roles': ['Member']
}
action = NewUser(data, registration=registration, order=1)
action = NewUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -130,7 +130,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({'test_project': project}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -141,7 +141,7 @@ class BaseActionTests(TestCase):
'roles': ['Member']
}
action = NewUser(data, registration=registration, order=1)
action = NewUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -164,7 +164,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -175,7 +175,7 @@ class BaseActionTests(TestCase):
'roles': ['Member']
}
action = NewUser(data, registration=registration, order=1)
action = NewUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, False)
@ -200,7 +200,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -210,7 +210,7 @@ class BaseActionTests(TestCase):
'project_name': 'test_project',
}
action = NewProject(data, registration=registration, order=1)
action = NewProject(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -221,7 +221,7 @@ class BaseActionTests(TestCase):
tests.temp_cache['projects']['test_project'].name,
'test_project')
self.assertEquals('admin' in tests.temp_cache['users'], True)
self.assertEquals(registration.cache, {'project_id': 2})
self.assertEquals(task.cache, {'project_id': 2})
token_data = {'password': '123456'}
action.submit(token_data)
@ -244,7 +244,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -254,7 +254,7 @@ class BaseActionTests(TestCase):
'project_name': 'test_project',
}
action = NewProject(data, registration=registration, order=1)
action = NewProject(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -265,7 +265,7 @@ class BaseActionTests(TestCase):
tests.temp_cache['projects']['test_project'].name,
'test_project')
self.assertEquals('admin' in tests.temp_cache['users'], True)
self.assertEquals(registration.cache, {'project_id': 2})
self.assertEquals(task.cache, {'project_id': 2})
action.post_approve()
self.assertEquals(action.valid, True)
@ -273,7 +273,7 @@ class BaseActionTests(TestCase):
tests.temp_cache['projects']['test_project'].name,
'test_project')
self.assertEquals('admin' in tests.temp_cache['users'], True)
self.assertEquals(registration.cache, {'project_id': 2})
self.assertEquals(task.cache, {'project_id': 2})
token_data = {'password': '123456'}
action.submit(token_data)
@ -300,7 +300,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -310,7 +310,7 @@ class BaseActionTests(TestCase):
'project_name': 'test_project',
}
action = NewProject(data, registration=registration, order=1)
action = NewProject(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -320,7 +320,7 @@ class BaseActionTests(TestCase):
self.assertEquals(
tests.temp_cache['projects']['test_project'].name,
'test_project')
self.assertEquals(registration.cache, {'project_id': 2})
self.assertEquals(task.cache, {'project_id': 2})
token_data = {'password': '123456'}
action.submit(token_data)
@ -347,7 +347,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({project.name: project}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -357,7 +357,7 @@ class BaseActionTests(TestCase):
'project_name': 'test_project',
}
action = NewProject(data, registration=registration, order=1)
action = NewProject(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, False)
@ -379,7 +379,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -389,7 +389,7 @@ class BaseActionTests(TestCase):
'project_name': 'test_project',
}
action = ResetUser(data, registration=registration, order=1)
action = ResetUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -413,7 +413,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -423,7 +423,7 @@ class BaseActionTests(TestCase):
'project_name': 'test_project',
}
action = ResetUser(data, registration=registration, order=1)
action = ResetUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, False)
@ -452,7 +452,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({'test_project': project}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -464,7 +464,7 @@ class BaseActionTests(TestCase):
'remove': False
}
action = EditUser(data, registration=registration, order=1)
action = EditUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -497,7 +497,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({'test_project': project}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -509,7 +509,7 @@ class BaseActionTests(TestCase):
'remove': False
}
action = EditUser(data, registration=registration, order=1)
action = EditUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -544,7 +544,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({'test_project': project}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -556,7 +556,7 @@ class BaseActionTests(TestCase):
'remove': True
}
action = EditUser(data, registration=registration, order=1)
action = EditUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -588,7 +588,7 @@ class BaseActionTests(TestCase):
setup_temp_cache({'test_project': project}, {user.name: user})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin',
'project_mod'],
'project_id': 'test_project_id'})
@ -600,7 +600,7 @@ class BaseActionTests(TestCase):
'remove': True
}
action = EditUser(data, registration=registration, order=1)
action = EditUser(data, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)

View File

@ -36,7 +36,7 @@ class DefaultProjectResources(BaseAction):
def _validate(self):
project_id = self.action.registration.cache.get('project_id', None)
project_id = self.action.task.cache.get('project_id', None)
valid = False
if project_id:
@ -49,7 +49,7 @@ class DefaultProjectResources(BaseAction):
def _setup_resources(self):
neutron = openstack_clients.get_neutronclient()
project_id = self.action.registration.cache['project_id']
project_id = self.action.task.cache['project_id']
if not self.get_cache('network_id'):
try:
@ -69,11 +69,11 @@ class DefaultProjectResources(BaseAction):
self.set_cache('network_id', network['network']['id'])
self.add_note("Network %s created for project %s" %
(self.defaults['network_name'],
self.action.registration.cache['project_id']))
self.action.task.cache['project_id']))
else:
self.add_note("Network %s already created for project %s" %
(self.defaults['network_name'],
self.action.registration.cache['project_id']))
self.action.task.cache['project_id']))
if not self.get_cache('subnet_id'):
try:
@ -118,10 +118,10 @@ class DefaultProjectResources(BaseAction):
raise
self.set_cache('router_id', router['router']['id'])
self.add_note("Router created for project %s" %
self.action.registration.cache['project_id'])
self.action.task.cache['project_id'])
else:
self.add_note("Router already created for project %s" %
self.action.registration.cache['project_id'])
self.action.task.cache['project_id'])
try:
interface_body = {
@ -159,7 +159,7 @@ class AddAdminToProject(BaseAction):
def _validate(self):
project_id = self.action.registration.cache.get('project_id', None)
project_id = self.action.task.cache.get('project_id', None)
valid = False
if project_id:
@ -182,7 +182,7 @@ class AddAdminToProject(BaseAction):
id_manager = IdentityManager()
project = id_manager.get_project(
self.action.registration.cache['project_id'])
self.action.task.cache['project_id'])
try:
user = id_manager.find_user(name="admin")
role = id_manager.find_role(name="admin")
@ -196,7 +196,7 @@ class AddAdminToProject(BaseAction):
self.action.save()
self.add_note(
'Admin has been added to %s.' %
self.action.registration.cache['project_id'])
self.action.task.cache['project_id'])
def _submit(self, token_data):
pass

View File

@ -13,7 +13,7 @@
# under the License.
from django.test import TestCase
from stacktask.api.models import Registration
from stacktask.api.models import Task
from stacktask.api.v1.tests import FakeManager, setup_temp_cache
from stacktask.api.v1 import tests
from stacktask.tenant_setup.models import DefaultProjectResources, AddAdminToProject
@ -80,16 +80,16 @@ class TenantSetupActionTests(TestCase):
Base case, setup resources, no issues.
"""
setup_neutron_cache()
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin']})
registration.cache = {'project_id': "1"}
task.cache = {'project_id': "1"}
data = {
'setup_resources': True,
}
action = DefaultProjectResources(data, registration=registration,
action = DefaultProjectResources(data, task=task,
order=1)
action.pre_approve()
@ -118,14 +118,14 @@ class TenantSetupActionTests(TestCase):
No project id given, should do nothing.
"""
setup_neutron_cache()
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin']})
data = {
'setup_resources': True,
}
action = DefaultProjectResources(data, registration=registration,
action = DefaultProjectResources(data, task=task,
order=1)
action.pre_approve()
@ -149,16 +149,16 @@ class TenantSetupActionTests(TestCase):
Told not to setup, should do nothing.
"""
setup_neutron_cache()
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin']})
data = {
'setup_resources': False,
}
registration.cache = {'project_id': "1"}
task.cache = {'project_id': "1"}
action = DefaultProjectResources(data, registration=registration,
action = DefaultProjectResources(data, task=task,
order=1)
action.pre_approve()
@ -183,16 +183,16 @@ class TenantSetupActionTests(TestCase):
"""
setup_neutron_cache()
global neutron_cache
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin']})
data = {
'setup_resources': True,
}
registration.cache = {'project_id': "1"}
task.cache = {'project_id': "1"}
action = DefaultProjectResources(data, registration=registration,
action = DefaultProjectResources(data, task=task,
order=1)
action.pre_approve()
@ -243,12 +243,12 @@ class TenantSetupActionTests(TestCase):
setup_temp_cache({'test_project': project}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin']})
registration.cache = {'project_id': "test_project_id"}
task.cache = {'project_id': "test_project_id"}
action = AddAdminToProject({}, registration=registration, order=1)
action = AddAdminToProject({}, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)
@ -271,12 +271,12 @@ class TenantSetupActionTests(TestCase):
setup_temp_cache({'test_project': project}, {})
registration = Registration.objects.create(
task = Task.objects.create(
reg_ip="0.0.0.0", keystone_user={'roles': ['admin']})
registration.cache = {'project_id': "test_project_id"}
task.cache = {'project_id': "test_project_id"}
action = AddAdminToProject({}, registration=registration, order=1)
action = AddAdminToProject({}, task=task, order=1)
action.pre_approve()
self.assertEquals(action.valid, True)

View File

@ -83,7 +83,7 @@ ACTIONVIEW_SETTINGS = {
'reply': 'no-reply@example.com',
'html_template': 'completed.txt',
'template': 'completed.txt',
'subject': 'Registration completed'
'subject': 'Task completed'
}
}
},
@ -105,7 +105,7 @@ ACTIONVIEW_SETTINGS = {
'reply': 'no-reply@example.com',
'html_template': 'completed.txt',
'template': 'completed.txt',
'subject': 'Registration completed'
'subject': 'Task completed'
}
},
'actions': [
@ -125,7 +125,7 @@ ACTIONVIEW_SETTINGS = {
'reply': 'no-reply@example.com',
'html_template': 'completed.txt',
'template': 'completed.txt',
'subject': 'Registration completed'
'subject': 'Task completed'
}
}
}