Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pull request update/241203 #482

Merged
merged 4 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
EMPTY_UUID,
FORMATTED_MONEY_TYPES
} from "utils/constants";
import { formatUTC } from "utils/datetime";
import { EN_FULL_FORMAT, format, secondsToMilliseconds } from "utils/datetime";
import { isEmpty as isEmptyObject } from "utils/objects";
import { getResourcesLink } from "utils/organizationConstraints/getResourcesLink";
import { CELL_EMPTY_VALUE } from "utils/tables";
Expand Down Expand Up @@ -73,7 +73,7 @@ const buildDescription = ({ type, definition, formatter, rawString = false }) =>
{ id: "expiringBudgetPolicyDescription" },
{
budget: formatter(FORMATTED_MONEY_TYPES.COMMON, totalBudget),
startDate: formatUTC(startDate),
startDate: format(secondsToMilliseconds(startDate), EN_FULL_FORMAT),
strong: (chunks) => (rawString ? chunks : <strong>{chunks}</strong>)
}
);
Expand All @@ -86,7 +86,7 @@ const buildDescription = ({ type, definition, formatter, rawString = false }) =>
} = definition;

const commonValues = {
startDate: formatUTC(startDate),
startDate: format(secondsToMilliseconds(startDate), EN_FULL_FORMAT),
strong: (chunks) => (rawString ? chunks : <strong>{chunks}</strong>)
};

Expand Down
8 changes: 6 additions & 2 deletions optscale_client/rest_api_client/client_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,8 +274,12 @@ def invite_url(id=None):
def invite_create(self, params):
return self.post(self.invite_url(), params)

def invite_list(self):
return self.get(self.invite_url())
def invite_list(self, organization_id=None, email=None):
params = {
"organization_id": organization_id,
"email": email
}
return self.get(self.invite_url() + self.query_url(**params))

def invite_accept(self, invite_id):
return self.patch(self.invite_url(invite_id), {'action': 'accept'})
Expand Down
4 changes: 2 additions & 2 deletions rest_api/rest_api_server/controllers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,9 +555,9 @@ def assign_role_to_user(self, user_id, scope_id, purpose,
LOG.error('Assign error: %s' % str(ex))
raise FailedDependency(Err.OE0435, [str(ex)])

def get_user_info(self):
def get_user_info(self, user_id=None):
try:
user_id = self.get_user_id()
user_id = user_id or self.get_user_id()
if user_id is None:
return {}
self.auth_client.token = self.token
Expand Down
28 changes: 26 additions & 2 deletions rest_api/rest_api_server/controllers/invite.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
import requests
import uuid
from sqlalchemy import and_, or_
import tools.optscale_time as opttime
from etcd import EtcdKeyNotFound

Expand Down Expand Up @@ -201,8 +202,31 @@ def delete_invite(self, invite):
invite_assignment.deleted_at = opttime.utcnow_timestamp()
super().delete(invite.id)

def list(self, user_id, user_info):
invites = super().list(email=user_info['email'])
def list(self, organization_id=None, email=None):
query = self.session.query(self.model_type).filter(
self.model_type.deleted_at == 0)
if email:
query = query.filter(self.model_type.email == email)
if organization_id:
pool_query = self.session.query(Pool.id).filter(
Pool.deleted_at == 0,
Pool.organization_id == organization_id
)
# get invites ids by invites assignments scopes
subquery = self.session.query(InviteAssignment.invite_id).filter(
InviteAssignment.deleted_at == 0,
or_(
and_(
InviteAssignment.scope_type == InviteAssignmentScopeTypes.ORGANIZATION,
InviteAssignment.scope_id == organization_id),
and_(
InviteAssignment.scope_type == InviteAssignmentScopeTypes.POOL,
InviteAssignment.scope_id.in_(pool_query)),
)
)
query = query.filter(self.model_type.id.in_(subquery))
invites = query.all()

now = opttime.utcnow_timestamp()
result = []
for invite in invites:
Expand Down
2 changes: 2 additions & 0 deletions rest_api/rest_api_server/controllers/shareable_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ def _check_resource(self, resource, organization_id=None):
resource['id']])
if resource.get('cluster_id'):
raise WrongArgumentsException(Err.OE0481, [resource['id']])
if not resource.get('active'):
raise WrongArgumentsException(Err.OE0443, [resource['id']])

def _check_resource_param(self, organization_id, resource_id):
resource = self.cloud_resource_ctrl.get(resource_id)
Expand Down
37 changes: 28 additions & 9 deletions rest_api/rest_api_server/handlers/v2/invites.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
from rest_api.rest_api_server.handlers.v1.base_async import (
BaseAsyncCollectionHandler, BaseAsyncItemHandler)
from rest_api.rest_api_server.handlers.v1.base import BaseAuthHandler
from rest_api.rest_api_server.handlers.v2.base import BaseHandler
from rest_api.rest_api_server.models.enums import InviteAssignmentScopeTypes
from rest_api.rest_api_server.utils import run_task, ModelEncoder, check_dict_attribute
from rest_api.rest_api_server.utils import (run_task, ModelEncoder,
check_dict_attribute)


class InviteAsyncCollectionHandler(BaseAsyncCollectionHandler,
BaseAuthHandler):
BaseAuthHandler, BaseHandler):
def _get_controller_class(self):
return InviteAsyncController

Expand Down Expand Up @@ -217,10 +219,22 @@ async def get(self):
"""
---
description: |
Get list of invites for current user by token
Required permission: TOKEN
Get list of invites. If used with token returns invites for current
user.
Required permission: TOKEN or CLUSTER_SECRET
tags: [invites]
summary: List of invites for current user by token
summary: List of invites
parameters:
- name: organization_id
in: query
description: Organization id to filter
required: false
type: string
- name: email
in: query
type: string
description: invite target email (only with CLUSTER_SECRET)
required: false
responses:
200:
description: Invites list
Expand Down Expand Up @@ -275,11 +289,16 @@ async def get(self):
- OE0234: Forbidden
security:
- token: []
- secret: []
"""

user_id = await self.check_self_auth()
user_info = await self.get_user_info(user_id)
res = await run_task(self.controller.list, user_id, user_info)
if self.check_cluster_secret(raises=False):
email = self.get_arg('email', str, None)
else:
user_id = await self.check_self_auth()
user_info = await self.get_user_info(user_id)
email = user_info['email']
organization_id = self.get_arg('organization_id', str, None)
res = await run_task(self.controller.list, organization_id, email)
invites = {'invites': [invite.to_dict() for invite in res]}
self.write(json.dumps(invites, cls=ModelEncoder))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ async def post(self, organization_id, **url_params):
- OE0384: Invalid resource type
- OE0416: Argument should not contain only whitespaces
- OE0435: Auth call error
- OE0443: Resource is not active
- OE0446: released_at should be greater than acquired_since
- OE0454: Resource does not belong to the organization
- OE0456: Duplicate path parameters in the request body
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ def _create_resource(self):
'resource_type': 'Instance',
'employee_id': self.employee['id'],
'region': 'us-west-1',
'pool_id': self.pool_id
'pool_id': self.pool_id,
'active': True
}
code, created_res = self.cloud_resource_create(
self.cloud_acc['id'], resource)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ def _create_resource(self):
'resource_type': 'Instance',
'employee_id': self.employee['id'],
'region': 'us-west-1',
'pool_id': self.pool_id
'pool_id': self.pool_id,
'active': True
}
code, created_res = self.cloud_resource_create(
self.cloud_acc['id'], resource)
Expand Down
11 changes: 6 additions & 5 deletions rest_api/rest_api_server/tests/unittests/test_employees.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,8 +372,8 @@ def test_delete_reassign_rules(self, p_assignment_list):

@patch('optscale_client.auth_client.client_v2.Client.assignment_list')
def test_delete_reassign_bookings(self, p_assignment_list):
patch('rest_api.rest_api_server.controllers.employee.EmployeeController.'
'auth_client').start()
patch('rest_api.rest_api_server.controllers.employee.'
'EmployeeController.auth_client').start()
patch('rest_api.rest_api_server.controllers.shareable_resource.'
'ShareableBookingController.publish_task').start()
patch('rest_api.rest_api_server.controllers.shareable_resource.'
Expand Down Expand Up @@ -405,7 +405,8 @@ def test_delete_reassign_bookings(self, p_assignment_list):
'name': 'name',
'resource_type': 'Instance',
'employee_id': emp['id'],
'pool_id': self.org['pool_id']
'pool_id': self.org['pool_id'],
'active': True
})
self.assertEqual(code, 201)
self.resources_collection.update_one(
Expand All @@ -421,8 +422,8 @@ def test_delete_reassign_bookings(self, p_assignment_list):
return_value=(200,
[{'user_id': emp['auth_user_id']},
{'user_id': root_emp['auth_user_id']}])).start()
patch('rest_api.rest_api_server.controllers.employee.EmployeeController.'
'auth_client.user_roles_get',
patch('rest_api.rest_api_server.controllers.employee.'
'EmployeeController.auth_client.user_roles_get',
return_value=(200,
[{'user_id': emp['auth_user_id']},
{'user_id': root_emp['auth_user_id']}])).start()
Expand Down
81 changes: 73 additions & 8 deletions rest_api/rest_api_server/tests/unittests/test_invite_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def setUp(self, version='v2'):
}
}

user_assignments = [
self.user_assignments = [
{
'assignment_id': self.gen_id(),
'assignment_resource': root_organization['id'],
Expand All @@ -82,21 +82,24 @@ def setUp(self, version='v2'):

patch('rest_api.rest_api_server.controllers.invite.'
'InviteController.get_user_auth_assignments',
return_value=user_assignments).start()
return_value=self.user_assignments).start()
patch('rest_api.rest_api_server.controllers.employee.'
'EmployeeController.notification_domain_blacklist').start()
self.mock_user_info(self.owner_email)

def mock_user_info(self, email, name='default'):
patch(
'rest_api.rest_api_server.handlers.v1.base.'
'BaseAuthHandler._get_user_info',
return_value={
value = {
'id': self.user_id,
'display_name': name,
'email': email,
'is_password_autogenerated': False
}).start()
}
patch('rest_api.rest_api_server.handlers.v1.base.'
'BaseAuthHandler._get_user_info',
return_value=value).start()
patch('rest_api.rest_api_server.controllers.base.'
'BaseController.get_user_info',
return_value=value).start()

def test_create_duplicate_scope_id(self):
self.correct_body['invites'][self.email_1].append(
Expand Down Expand Up @@ -235,7 +238,9 @@ def test_create_invalid_invites(self):
self.assertEqual(response['error']['reason'],
'invites should be a dictionary')

def test_list(self):
def test_list_by_token(self):
patch('rest_api.rest_api_server.handlers.v1.base.BaseAuthHandler.'
'check_cluster_secret', return_value=False).start()
code, response = self.client.invite_create(self.correct_body)
self.assertEqual(code, 201)
self.mock_user_info(self.email_1)
Expand All @@ -254,6 +259,66 @@ def test_list(self):
self.assertEqual(invites[0]['owner_name'], 'default')
self.assertEqual(len(invites[0]['invite_assignments']), 1)

def test_list_by_secret(self):
patch('rest_api.rest_api_server.handlers.v1.base.BaseAuthHandler.'
'check_cluster_secret', return_value=True).start()
code, response = self.client.invite_create(self.correct_body)
self.mock_user_info(self.email_1)
self.assertEqual(code, 201)
code, response = self.client.invite_list()
self.assertEqual(code, 200)
self.assertEqual(len(response['invites']), 2)

def test_list_by_email(self):
patch('rest_api.rest_api_server.handlers.v1.base.BaseAuthHandler.'
'check_cluster_secret', return_value=True).start()
code, response = self.client.invite_create(self.correct_body)
self.assertEqual(code, 201)
self.mock_user_info(self.email_1)
code, response = self.client.invite_list(email=self.email_1)
self.assertEqual(code, 200)
invites = response['invites']
self.assertEqual(len(invites), 1)
self.assertEqual(invites[0]['email'], self.email_1)

def test_list_organization_id(self):
code, response = self.client.invite_create(self.correct_body)
self.assertEqual(code, 201)
_, organization = self.client.organization_create(
{'name': 'org2'})
self.assertEqual(code, 201)
user_assignments = self.user_assignments.copy()
user_assignments.append({
'assignment_id': self.gen_id(),
'assignment_resource': organization['id'],
'assignment_resource_type': 2,
'role_id': 3,
'role_name': 'Manager',
'role_scope': None
})
patch('rest_api.rest_api_server.controllers.invite.'
'InviteController.get_user_auth_assignments',
return_value=user_assignments).start()
params = {
'invites': {
'[email protected]': [
{'scope_id': organization['pool_id'],
'scope_type': 'pool',
'purpose': 'optscale_engineer'}
]
}
}
code, response = self.client.invite_create(params)
self.assertEqual(code, 201)
patch('rest_api.rest_api_server.handlers.v1.base.BaseAuthHandler.'
'check_cluster_secret', return_value=True).start()
code, response = self.client.invite_list(
organization_id=organization['id'])
self.assertEqual(code, 200)
self.assertEqual(len(response['invites']), 1)
self.assertEqual(response['invites'][0]['email'],
list(params['invites'])[0])

def test_accept_invite(self):
body = {
'invites': {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def setUp(self, version='v2'):

def _create_resource(self, employee_id=None, pool_id=None,
is_shareable=True, resource_type='Instance',
tags=None):
tags=None, active=True):
if not employee_id:
employee_id = self.employee['id']
if not pool_id:
Expand All @@ -85,6 +85,8 @@ def _create_resource(self, employee_id=None, pool_id=None,
'region': 'us-west-1',
'pool_id': pool_id
}
if active:
resource['active'] = True
if tags:
resource['tags'] = tags
code, created_res = self.cloud_resource_create(self.cloud_acc['id'],
Expand Down
Loading