Ejemplo n.º 1
0
def addAPI(request):
    operation_id = request.POST.get('operation_id')
    profile_id = request.POST.get('profile_id')

    testconfig = TestConfiguration.objects.get(
        owner=request.user,
        pk=profile_id,
    )

    api = API(request.session.get('obp'))
    api_version = settings.API_VERSION
    swagger = api.get_swagger(api_version)

    request_body = {}
    urlpath = ''
    params = ''
    remark = ''

    for path, data in swagger['paths'].items():
        if 'get' in data:
            method = 'get'
        if 'post' in data:
            method = 'post'
        if 'put' in data:
            method = 'put'
        if 'delete' in data:
            method = 'delete'

        if data[method]['operationId'] == operation_id:
            urlpath = get_urlpath(testconfig, path)
            remark = data[method]['summary']
        if method == 'post' or method == 'put':
            request_body = {}
            definition = data[method]['parameters'][0] if len(
                data[method]['parameters']) > 0 else None
            definition = definition['schema']['$ref'][14:]
            params = swagger['definitions'][definition]
            if len(params["required"]) > 0:
                for field in params["required"]:
                    # Match Profile variables
                    field_names = [
                        f.name for f in TestConfiguration._meta.fields
                    ]
                    if field in field_names:
                        request_body[field] = getattr(testconfig, field)
                    else:
                        try:
                            request_body[field] = params["properties"][
                                field].get("example", "")
                        except:
                            request_body[field] = None
            params = json.dumps(request_body, indent=4)

    #if not re.match("^{.*}$", json_body):
    #    json_body = "{{{}}}".format(json_body)

    profile_list = ProfileOperation.objects.filter(operation_id=operation_id,
                                                   profile_id=profile_id)

    if profile_list is None or len(profile_list) == 0:
        replica_id = 1
    else:
        replica_id = max([profile.replica_id for profile in profile_list]) + 1

    ProfileOperation.objects.create(profile_id=profile_id,
                                    operation_id=operation_id,
                                    json_body=params,
                                    order=100,
                                    urlpath=urlpath,
                                    remark=remark,
                                    replica_id=replica_id,
                                    is_deleted=0)

    return JsonResponse({
        'state': True,
        'profile_id': profile_id,
        'operation_id': operation_id,
        'json_body': params,
        'order': 100,
        'urlpath': urlpath,
        'remark': remark,
        'replica_id': replica_id,
        'is_deleted': 0
    })
Ejemplo n.º 2
0
 def dispatch(self, request, *args, **kwargs):
     self.api = API(request.session.get('obp'))
     return super(DetailView, self).dispatch(request, *args, **kwargs)
Ejemplo n.º 3
0
class DetailView(LoginRequiredMixin, FormView):
    """Detail view for a consumer"""
    form_class = ApiConsumersForm
    template_name = "consumers/detail.html"

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(DetailView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(DetailView, self).get_form(*args, **kwargs)
        form.fields['consumer_id'].initial = self.kwargs['consumer_id']
        return form

    def form_valid(self, form):
        """Put limits data to API"""
        try:
            data = ''
            form = ApiConsumersForm(self.request.POST)
            if form.is_valid():
                data = form.cleaned_data

            urlpath = '/management/consumers/{}/consumer/calls_limit'.format(
                data['consumer_id'])

            payload = {
                'per_minute_call_limit': data['per_minute_call_limit'],
                'per_hour_call_limit': data['per_hour_call_limit'],
                'per_day_call_limit': data['per_day_call_limit'],
                'per_week_call_limit': data['per_week_call_limit'],
                'per_month_call_limit': data['per_month_call_limit']
            }
            user = self.api.put(urlpath, payload=payload)
        except APIError as err:
            messages.error(self.request, err)
            return super(DetailView, self).form_invalid(form)

        msg = 'calls limit of consumer {} has been updated successfully.'.format(
            data['consumer_id'])
        messages.success(self.request, msg)
        self.success_url = self.request.path
        return super(DetailView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(DetailView, self).get_context_data(**kwargs)
        api = API(self.request.session.get('obp'))
        try:
            urlpath = '/management/consumers/{}'.format(
                self.kwargs['consumer_id'])
            consumer = api.get(urlpath)
            consumer['created'] = datetime.strptime(
                consumer['created'], settings.API_DATETIMEFORMAT)

            call_limits_urlpath = '/management/consumers/{}/consumer/calls_limit'.format(
                self.kwargs['consumer_id'])
            consumer_call_limtis = api.get(call_limits_urlpath)
            consumer['per_minute_call_limit'] = consumer_call_limtis[
                'per_minute_call_limit']
            consumer['per_hour_call_limit'] = consumer_call_limtis[
                'per_hour_call_limit']
            consumer['per_day_call_limit'] = consumer_call_limtis[
                'per_day_call_limit']
            consumer['per_week_call_limit'] = consumer_call_limtis[
                'per_week_call_limit']
            consumer['per_month_call_limit'] = consumer_call_limtis[
                'per_month_call_limit']

        except APIError as err:
            messages.error(self.request, err)

        context.update({'consumer': consumer})
        return context
Ejemplo n.º 4
0
class CreateView(LoginRequiredMixin, FormView):
    """View to create a customer"""
    form_class = CreateCustomerForm
    template_name = 'customers/create.html'
    success_url = reverse_lazy('customers-create')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(CreateView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(CreateView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")
        fields['last_ok_date'].initial =\
            datetime.datetime.now().strftime(settings.API_DATETIMEFORMAT)
        return form

    def form_valid(self, form):
        data = form.cleaned_data
        urlpath = '/banks/{}/customers'.format(data['bank_id'])
        payload = {
            'user_id':
            data['user_id'],
            'customer_number':
            data['customer_number'],
            'legal_name':
            data['legal_name'],
            'mobile_phone_number':
            data['mobile_phone_number'],
            'email':
            data['email'],
            'face_image': {
                'url': data['face_image_url'],
                'date': data['face_image_date'],
            },
            'date_of_birth':
            data['date_of_birth'],
            'relationship_status':
            data['relationship_status'],
            'dependants':
            data['dependants'],
            'dob_of_dependants':
            data['dob_of_dependants'],
            'credit_rating': {
                'rating': data['credit_rating_rating'],
                'source': data['credit_rating_source'],
            },
            'credit_limit': {
                'currency': data['credit_limit_currency'],
                'amount': data['credit_limit_amount'],
            },
            'highest_education_attained':
            data['highest_education_attained'],
            'employment_status':
            data['employment_status'],
            'kyc_status':
            data['kyc_status'],
            'last_ok_date':
            data['last_ok_date'].strftime(settings.API_DATETIMEFORMAT),
        }
        try:
            result = self.api.post(urlpath, payload=payload)
        except APIError as err:
            messages.error(self.request, err)
            return super(CreateView, self).form_invalid(form)
        except:
            messages.error(self.request, "Unknown Error")
            return super(CreateView, self).form_invalid(form)
        msg = 'Customer number {} for user {} has been created successfully!'.format(  # noqa
            result['customer_number'], data['username'])
        messages.success(self.request, msg)
        return super(CreateView, self).form_valid(form)
Ejemplo n.º 5
0
class UpdateBranchesView(LoginRequiredMixin, FormView):
    template_name = "branches/update.html"
    success_url = '/branches/'
    form_class = CreateBranchForm

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(UpdateBranchesView,
                     self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(UpdateBranchesView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        form.api = self.api
        fields = form.fields
        urlpath = "/banks/{}/branches/{}".format(self.kwargs['bank_id'],
                                                 self.kwargs['branch_id'])
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()

        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")
        try:
            result = self.api.get(urlpath)
            fields['bank_id'].initial = self.kwargs['bank_id']
            fields['branch_id'].initial = self.kwargs['branch_id']
            fields['name'].initial = result['name']
            fields['address'].initial = json.dumps(result['address'], indent=4)
            fields['location_latitude'].initial = result['location'][
                'latitude']
            fields['location_longitude'].initial = result['location'][
                'longitude']
            fields['meta_license_id'].initial = result['meta']['license']['id']
            fields['meta_license_name'].initial = result['meta']['license'][
                'name']
            fields['branch_routing_scheme'].initial = result['branch_routing'][
                'scheme']
            fields['branch_routing_address'].initial = result[
                'branch_routing']['address']
            if result['is_accessible'].lower() == 'true':
                fields['is_accessible'].choices = [(True, True),
                                                   (False, False)]
            else:
                fields['is_accessible'].choices = [(False, False),
                                                   (True, True)]
            fields['accessibleFeatures'].initial = result['accessibleFeatures']
            fields['branch_type'].initial = result['branch_type']
            fields['more_info'].initial = result['more_info']
            fields['phone_number'].initial = result['phone_number']
            fields['lobby'].initial = json.dumps(result['lobby'], indent=4)
            fields['drive_up'].initial = json.dumps(result['drive_up'],
                                                    indent=4)
        except APIError as err:
            messages.error(self.request, err)
        except Exception as err:
            messages.error(self.request, "Unknown Error {}".format(err))

        return form

    def form_valid(self, form):
        data = form.cleaned_data
        urlpath = '/banks/{}/branches/{}'.format(data["bank_id"],
                                                 data["branch_id"])
        payload = {
            #"id": data["branch_id"],
            "bank_id": data["bank_id"],
            "name": data["name"],
            "address": json.loads(data['address']),
            "location": {
                "latitude": float(data["location_latitude"]),
                "longitude": float(data["location_longitude"])
            },
            "meta": {
                "license": {
                    "id": data["meta_license_id"],
                    "name": data["meta_license_name"]
                }
            },
            "lobby": json.loads(data["lobby"]),
            "drive_up": json.loads(data["drive_up"]),
            "branch_routing": {
                "scheme":
                data["branch_routing_scheme"]
                if data["branch_routing_scheme"] != "" else "license name",
                "address":
                data["branch_routing_address"]
                if data["branch_routing_address"] != "" else "license name"
            },
            "is_accessible": data["is_accessible"],
            "accessibleFeatures": data["accessibleFeatures"],
            "branch_type": data["branch_type"],
            "more_info": data["more_info"],
            "phone_number": data["phone_number"]
        }
        try:
            result = self.api.put(urlpath, payload=payload)
            if 'code' in result and result['code'] >= 400:
                error_once_only(self.request, result['message'])
                return super(UpdateBranchesView, self).form_invalid(form)
        except APIError as err:
            messages.error(self.request, err)
            return super(UpdateBranchesView, self).form_invalid(form)
        except:
            messages.error(self.request, "Unknown Error")
            return super(UpdateBranchesView, self).form_invalid(form)
        msg = 'Branch {} for Bank {} has been created successfully!'.format(  # noqa
            data["branch_id"], data["bank_id"])
        messages.success(self.request, msg)
        return super(UpdateBranchesView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(UpdateBranchesView, self).get_context_data(**kwargs)
        self.bank_id = self.kwargs['bank_id']
        self.branch_id = self.kwargs['branch_id']
        context.update({'branch_id': self.branch_id, 'bank_id': self.bank_id})
        return context
Ejemplo n.º 6
0
 def dispatch(self, request, *args, **kwargs):
     self.api = API(request.session.get('obp'))
     return super(UpdateBranchesView,
                  self).dispatch(request, *args, **kwargs)
Ejemplo n.º 7
0
class IndexBranchesView(LoginRequiredMixin, FormView):
    """Index view for branches"""
    template_name = "branches/index.html"
    form_class = CreateBranchForm
    success_url = reverse_lazy('branches_list')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(IndexBranchesView, self).dispatch(request, *args,
                                                       **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(IndexBranchesView, self).get_form(*args, **kwargs)
        # Cannot add api in constructor: super complains about unknown kwarg
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
            fields['is_accessible'].choices = [('', 'Choose...'), (True, True),
                                               (False, False)]
            fields['drive_up'].initial = json.dumps(
                {
                    "monday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "tuesday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "wednesday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "thursday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "friday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "saturday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    },
                    "sunday": {
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }
                },
                indent=4)

            fields['lobby'].initial = json.dumps(
                {
                    "monday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "tuesday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "wednesday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "thursday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "friday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "saturday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }],
                    "sunday": [{
                        "opening_time": "10:00",
                        "closing_time": "18:00"
                    }]
                },
                indent=4)

            fields['address'].initial = json.dumps(
                {
                    "line_1": "No 1 the Road",
                    "line_2": "The Place",
                    "line_3": "The Hill",
                    "city": "Berlin",
                    "county": "String",
                    "state": "Brandenburg",
                    "postcode": "13359",
                    "country_code": "DE"
                },
                indent=4)

        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")

        return form

    def form_valid(self, form):
        try:
            data = form.cleaned_data
            urlpath = '/banks/{}/branches'.format(data['bank_id'])
            payload = {
                "id":
                data["branch_id"],
                "bank_id":
                data["bank_id"],
                "name":
                data["name"],
                "address":
                json.loads(data['address']),
                "location": {
                    "latitude":
                    float(data["location_latitude"])
                    if data["location_latitude"] is not None else 37.0,
                    "longitude":
                    float(data["location_longitude"])
                    if data["location_longitude"] is not None else 110.0
                },
                "meta": {
                    "license": {
                        "id":
                        "PDDL",
                        "name":
                        data["meta_license_name"]
                        if data["meta_license_name"] != "" else "license name"
                    }
                },
                "lobby":
                json.loads(data['lobby']),
                "drive_up":
                json.loads(data["drive_up"]),
                "branch_routing": {
                    "scheme":
                    data["branch_routing_scheme"]
                    if data["branch_routing_scheme"] != "" else "license name",
                    "address":
                    data["branch_routing_address"]
                    if data["branch_routing_address"] != "" else "license name"
                },
                "is_accessible":
                data["is_accessible"]
                if data["is_accessible"] != "" else "false",
                "accessibleFeatures":
                data["accessibleFeatures"] if data["accessibleFeatures"] != ""
                else "accessible features name",
                "branch_type":
                data["branch_type"]
                if data["branch_type"] != "" else "branch type",
                "more_info":
                data["more_info"] if data["more_info"] != "" else "more info",
                "phone_number":
                data["phone_number"]
                if data["phone_number"] != "" else "phone number"
            }
            result = self.api.post(urlpath, payload=payload)
        except APIError as err:
            error_once_only(self.request, err)
            return super(IndexBranchesView, self).form_invalid(form)
        except Exception as err:
            error_once_only(self.request, "Unknown Error")
            return super(IndexBranchesView, self).form_invalid(form)
        if 'code' in result and result['code'] >= 400:
            error_once_only(self.request, result['message'])
            return super(IndexBranchesView, self).form_valid(form)
        msg = 'Branch {} for Bank {} has been created successfully!'.format(
            result['id'], result['bank_id'])
        messages.success(self.request, msg)
        return super(IndexBranchesView, self).form_valid(form)

    def get_banks(self):
        api = API(self.request.session.get('obp'))
        try:
            urlpath = '/banks'
            result = api.get(urlpath)
            if 'banks' in result:
                return [bank['id'] for bank in result['banks']]
            else:
                return []
        except APIError as err:
            messages.error(self.request, err)
            return []

    def get_branches(self, context):

        api = API(self.request.session.get('obp'))
        try:
            self.bankids = self.get_banks()
            branches_list = []
            for bank_id in self.bankids:
                urlpath = '/banks/{}/branches'.format(bank_id)

                result = api.get(urlpath)
                if 'branches' in result:
                    branches_list.extend(result['branches'])
        except APIError as err:
            messages.error(self.request, err)
            return []
        except Exception as inst:
            messages.error(self.request,
                           "Unknown Error {}".format(type(inst).__name__))
            return []

        return branches_list

    def get_context_data(self, **kwargs):
        context = super(IndexBranchesView, self).get_context_data(**kwargs)
        branches_list = self.get_branches(context)
        context.update({
            'branches_list': branches_list,
            'bankids': self.bankids
        })
        return context
Ejemplo n.º 8
0
def dynamicendpoints_save(request):
    parameters_Json_editor = request.POST.get('parameters_Json_editor')
    api = API(request.session.get('obp'))
    urlpath = '/management/dynamic-endpoints'
    result = api.post(urlpath, payload=json.loads(parameters_Json_editor))
    return result
Ejemplo n.º 9
0
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        api = API(self.request.session.get('obp'))
        urlpath = '/management/dynamic-endpoints'
        dynamic_endpoints = []
        try:
            response = api.get(urlpath)
            if 'code' in response and response['code'] >= 400:
                error_once_only(self.request, response['message'])
            else:
                dynamic_endpoints = response['dynamic_endpoints']
        except APIError as err:
            error_once_only(
                self.request,
                Exception(
                    "OBP-API server is not running or do not response properly. "
                    "Please check OBP-API server.    "
                    "Details: " + str(err)))
        except BaseException as err:
            error_once_only(self.request,
                            (Exception("Unknown Error. Details:" + str(err))))
        else:
            # set the default endpoint there, the first item will be the new endpoint.
            default_dynamic_endpoint = {
                "dynamic_endpoint_id": "Try the new endpoint: ",
                "swagger_string": {
                    "swagger": "2.0",
                    "info": {
                        "version": "0.0.1",
                        "title": "Example Title",
                        "description": "Example Description",
                        "contact": {
                            "name": "Example Company",
                            "email": "*****@*****.**",
                            "url": "https://www.tesobe.com/"
                        }
                    },
                    "host": "localhost:8080",
                    "basePath": "/user",
                    "schemes": ["http"],
                    "consumes": ["application/json"],
                    "produces": ["application/json"],
                    "paths": {
                        "/save": {
                            "post": {
                                "parameters": [{
                                    "name": "body",
                                    "in": "body",
                                    "required": "true",
                                    "schema": {
                                        "$ref": "#/definitions/user"
                                    }
                                }],
                                "responses": {
                                    "201": {
                                        "description":
                                        "create user successful and return created user object",
                                        "schema": {
                                            "$ref": "#/definitions/user"
                                        }
                                    },
                                    "500": {
                                        "description": "unexpected error",
                                        "schema": {
                                            "$ref":
                                            "#/responses/unexpectedError"
                                        }
                                    }
                                }
                            }
                        },
                        "/getById/{userId}": {
                            "get": {
                                "description": "get reuested user by user ID",
                                "parameters": [{
                                    "$ref": "#/parameters/userId"
                                }],
                                "consumes": [],
                                "responses": {
                                    "200": {
                                        "description":
                                        "the successful get requested user by user ID",
                                        "schema": {
                                            "$ref": "#/definitions/user"
                                        }
                                    },
                                    "400": {
                                        "description": "bad request",
                                        "schema": {
                                            "$ref":
                                            "#/responses/invalidRequest"
                                        }
                                    },
                                    "404": {
                                        "description": "user not found",
                                        "schema": {
                                            "$ref": "#/definitions/APIError"
                                        }
                                    },
                                    "500": {
                                        "description": "unexpected error",
                                        "schema": {
                                            "$ref":
                                            "#/responses/unexpectedError"
                                        }
                                    }
                                }
                            }
                        },
                        "/listUsers": {
                            "get": {
                                "description": "get list of users",
                                "consumes": [],
                                "responses": {
                                    "200": {
                                        "description": "get all users",
                                        "schema": {
                                            "$ref": "#/definitions/users"
                                        }
                                    },
                                    "404": {
                                        "description": "user not found",
                                        "schema": {
                                            "$ref": "#/definitions/APIError"
                                        }
                                    }
                                }
                            }
                        },
                        "/updateUser": {
                            "put": {
                                "parameters": [{
                                    "name": "body",
                                    "in": "body",
                                    "required": "true",
                                    "schema": {
                                        "$ref": "#/definitions/user"
                                    }
                                }],
                                "responses": {
                                    "200": {
                                        "description":
                                        "create user successful and return created user object",
                                        "schema": {
                                            "$ref": "#/definitions/user"
                                        }
                                    },
                                    "500": {
                                        "description": "unexpected error",
                                        "schema": {
                                            "$ref":
                                            "#/responses/unexpectedError"
                                        }
                                    }
                                }
                            }
                        },
                        "/delete/{userId}": {
                            "delete": {
                                "description": "delete user by user ID",
                                "parameters": [{
                                    "$ref": "#/parameters/userId"
                                }],
                                "consumes": [],
                                "responses": {
                                    "204": {
                                        "description":
                                        "the successful delete user by user ID"
                                    },
                                    "400": {
                                        "description": "bad request",
                                        "schema": {
                                            "$ref":
                                            "#/responses/invalidRequest"
                                        }
                                    },
                                    "500": {
                                        "description": "unexpected error",
                                        "schema": {
                                            "$ref":
                                            "#/responses/unexpectedError"
                                        }
                                    }
                                }
                            }
                        }
                    },
                    "definitions": {
                        "user": {
                            "type": "object",
                            "properties": {
                                "id": {
                                    "type": "integer",
                                    "description": "user ID"
                                },
                                "first_name": {
                                    "type": "string"
                                },
                                "last_name": {
                                    "type": "string"
                                },
                                "age": {
                                    "type": "integer"
                                },
                                "career": {
                                    "type": "string"
                                }
                            },
                            "required": ["first_name", "last_name", "age"]
                        },
                        "users": {
                            "description": "array of users",
                            "type": "array",
                            "items": {
                                "$ref": "#/definitions/user"
                            }
                        },
                        "APIError": {
                            "description": "content any error from API",
                            "type": "object",
                            "properties": {
                                "errorCode": {
                                    "description":
                                    "content error code relate to API",
                                    "type": "string"
                                },
                                "errorMessage": {
                                    "description":
                                    "content user-friendly error message",
                                    "type": "string"
                                }
                            }
                        }
                    },
                    "responses": {
                        "unexpectedError": {
                            "description": "unexpected error",
                            "schema": {
                                "$ref": "#/definitions/APIError"
                            }
                        },
                        "invalidRequest": {
                            "description": "invalid request",
                            "schema": {
                                "$ref": "#/definitions/APIError"
                            }
                        }
                    },
                    "parameters": {
                        "userId": {
                            "name": "userId",
                            "in": "path",
                            "required": "true",
                            "type": "string",
                            "description": "user ID"
                        }
                    }
                }
            }
            dynamic_endpoints.insert(0, default_dynamic_endpoint)

            # replace all the json list to json object.
            for i in range(len(dynamic_endpoints)):
                dynamic_endpoints[i]['swagger_string'] = json.dumps(
                    dynamic_endpoints[i]['swagger_string'])
            context.update({'dynamic_endpoints': dynamic_endpoints})
        return context
Ejemplo n.º 10
0
class InvitationView(LoginRequiredMixin, FormView):
    """View to create a User Invitation"""
    form_class = CreateInvitationForm
    template_name = 'users/invitation.html'
    success_url = reverse_lazy('my-user-invitation')

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(InvitationView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(InvitationView, self).get_form(*args, **kwargs)
        form.api = self.api
        fields = form.fields
        try:
            fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, "Unknown Error")
        return form

    def form_valid(self, form, **kwargs):
        data = form.cleaned_data
        post_url_path = '/banks/{}/user-invitation'.format(data['bank_id'])
        get_url_path = '/banks/{}/user-invitations'.format(data['bank_id'])
        invitations = []
        payload = {
            'first_name': data['first_name'],
            'last_name': data['last_name'],
            'email': data['email'],
            'company': data['company'],
            'country': data['country'],
            'purpose': 'DEVELOPER'
        }
        context = self.get_context_data(**kwargs)
        try:
            result = self.api.post(post_url_path, payload=payload)
            if 'code' in result and result['code'] >= 400:
                messages.error(self.request, result['message'])
                return super(InvitationView, self).form_valid(form)
            else:
                self.get_invitations(context, get_url_path, invitations)
                msg = 'User Invitation ({}) at Bank({}) has been {}!'.format(
                    result['first_name'], data['bank_id'], result['status'])
                messages.success(self.request, msg)
                return self.render_to_response(context)
        except APIError as err:
            messages.error(self.request, err)
            return super(InvitationView, self).form_invalid(form)
        except Exception as err:
            messages.error(self.request, "Unknown Error:{}".format(str(err)))
            return super(InvitationView, self).form_invalid(form)

    def get_invitations(self, context, get_url_path, invitations):
        response = self.api.get(get_url_path)
        if 'code' in response and response['code'] >= 400:
            messages.error(self.request, response['message'])
        else:
            invitations = invitations + response['user_invitations']
        context.update({
            'invitations': invitations,
        })
Ejemplo n.º 11
0
class MyDetailView(LoginRequiredMixin, FormView):
    """Detail view for a current user"""
    form_class = AddEntitlementForm
    template_name = 'users/detail.html'

    def dispatch(self, request, *args, **kwargs):
        self.api = API(request.session.get('obp'))
        return super(MyDetailView, self).dispatch(request, *args, **kwargs)

    def get_form(self, *args, **kwargs):
        form = super(MyDetailView, self).get_form(*args, **kwargs)
        try:
            form.fields['bank_id'].choices = self.api.get_bank_id_choices()
        except APIError as err:
            messages.error(self.request, err)
        except:
            messages.error(self.request, 'Unknown Error')
        return form

    def form_valid(self, form):
        """Posts entitlement data to API"""
        try:
            data = form.cleaned_data
            urlpath = '/users/{}/entitlements'.format(data['user_id'])
            payload = {
                'bank_id': data['bank_id'],
                'role_name': data['role_name'],
            }
            entitlement = self.api.post(urlpath, payload=payload)
            if 'code' in entitlement and entitlement['code'] >= 400:
                messages.error(self.request, entitlement['message'])
            else:
                msg = 'Entitlement with role {} has been added.'.format(
                    entitlement['role_name'])
                messages.success(self.request, msg)
            self.success_url = self.request.path
        except APIError as err:
            messages.error(self.request, err)
            return super(MyDetailView, self).form_invalid(form)
        except Exception as err:
            messages.error(self.request, 'Unknown Error. {}'.format(err))
            return super(MyDetailView, self).form_invalid(form)
        else:
            return super(MyDetailView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(MyDetailView, self).get_context_data(**kwargs)
        # NOTE: assuming there is just one user with that email address
        # The API needs a call 'get user by id'!
        user = {}
        try:
            urlpath = '/users/current'
            user = self.api.get(urlpath)
            context['form'].fields['user_id'].initial = user['user_id']
        except APIError as err:
            messages.error(self.request, err)
        except Exception as err:
            messages.error(self.request, 'Unknown Error')

        context.update({
            'apiuser': user,  # 'user' is logged-in user in template context
        })
        return context