mirror of
https://github.com/OpenBankProject/API-Manager.git
synced 2026-02-06 16:46:57 +00:00
Cleaned up after running pylint
This commit is contained in:
parent
cd382658e0
commit
00cc8e8d76
@ -48,8 +48,8 @@ INSTALLED_APPS = [
|
||||
'oauth',
|
||||
'consumers',
|
||||
'users',
|
||||
# 'api_calls',
|
||||
# 'api_config',
|
||||
#'api_calls',
|
||||
#'api_config',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
@ -176,7 +176,7 @@ OAUTH_CONSUMER_SECRET = None
|
||||
# Local settings can override anything in here
|
||||
try:
|
||||
from apimanager.local_settings import *
|
||||
except:
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
if not OAUTH_CONSUMER_KEY:
|
||||
|
||||
@ -1,18 +1,8 @@
|
||||
"""apimanager URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/1.10/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.conf.urls import url, include
|
||||
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
URLs for apimanager
|
||||
"""
|
||||
|
||||
from django.conf.urls import url, include
|
||||
|
||||
from base.views import HomeView
|
||||
@ -23,6 +13,6 @@ urlpatterns = [
|
||||
url(r'^oauth/', include('oauth.urls')),
|
||||
url(r'^consumers/', include('consumers.urls')),
|
||||
url(r'^users/', include('users.urls')),
|
||||
# url(r'^api_calls/', include('api_calls.urls')),
|
||||
# url(r'^api_config/', include('api_config.urls')),
|
||||
#url(r'^api_calls/', include('api_calls.urls')),
|
||||
#url(r'^api_config/', include('api_config.urls')),
|
||||
]
|
||||
|
||||
@ -1,4 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Module to handle the OBP API
|
||||
|
||||
It instantiates a convenience api object for imports, e.g.:
|
||||
from base.api import api
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
import logging
|
||||
@ -14,41 +20,50 @@ LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
def log(level, message):
|
||||
"""Logs a given message on a given level to log facility"""
|
||||
now = datetime.now().strftime(DATE_FORMAT)
|
||||
msg = '[{}] API: {}'.format(now, message)
|
||||
LOGGER.log(level, msg)
|
||||
|
||||
|
||||
|
||||
class APIError(Exception):
|
||||
"""Exception class for API errors"""
|
||||
pass
|
||||
|
||||
|
||||
|
||||
class API(object):
|
||||
|
||||
def log(self, level, message):
|
||||
now = datetime.now().strftime(DATE_FORMAT)
|
||||
msg = '[{}] API: {}'.format(now, message)
|
||||
LOGGER.log(level, msg)
|
||||
|
||||
"""Implements an interface to the OBP API"""
|
||||
|
||||
def get(self, request, urlpath=''):
|
||||
"""Gets data from the API"""
|
||||
return self.call(request, 'GET', urlpath)
|
||||
|
||||
|
||||
def delete(self, request, urlpath):
|
||||
"""Deletes data from the API"""
|
||||
return self.call(request, 'DELETE', urlpath)
|
||||
|
||||
|
||||
def post(self, request, urlpath, payload):
|
||||
"""Posts data to the API"""
|
||||
return self.call(request, 'POST', urlpath, payload)
|
||||
|
||||
|
||||
def put(self, request, urlpath, payload):
|
||||
"""Puts data onto the API"""
|
||||
return self.call(request, 'PUT', urlpath, payload)
|
||||
|
||||
|
||||
def handle_response(self, response):
|
||||
"""Handles the response, e.g. errors or conversion to JSON"""
|
||||
prefix = 'APIError'
|
||||
if response.status_code in [404, 500]:
|
||||
msg = '{} {}: {}'.format(
|
||||
prefix, response.status_code, response.text)
|
||||
self.log(logging.ERROR, msg)
|
||||
log(logging.ERROR, msg)
|
||||
raise APIError(msg)
|
||||
elif response.status_code in [204]:
|
||||
return response.text
|
||||
@ -61,8 +76,9 @@ class API(object):
|
||||
|
||||
|
||||
def call(self, request, method='GET', urlpath='', payload=None):
|
||||
"""Workhorse which actually calls the API"""
|
||||
url = settings.OAUTH_API + settings.OAUTH_API_BASE_PATH + urlpath
|
||||
self.log(logging.INFO, '{} {}'.format(method, url))
|
||||
log(logging.INFO, '{} {}'.format(method, url))
|
||||
if not hasattr(request, 'api'):
|
||||
request.api = OAuth1Session(
|
||||
settings.OAUTH_CONSUMER_KEY,
|
||||
@ -77,8 +93,6 @@ class API(object):
|
||||
response = request.api.request(method, url)
|
||||
time_end = time.time()
|
||||
elapsed = int((time_end - time_start) * 1000)
|
||||
self.log(logging.INFO, 'Took {} ms'.format(elapsed))
|
||||
log(logging.INFO, 'Took {} ms'.format(elapsed))
|
||||
return self.handle_response(response)
|
||||
|
||||
|
||||
api = API()
|
||||
|
||||
@ -1,5 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
App config for base app
|
||||
"""
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class HomeConfig(AppConfig):
|
||||
name = 'home'
|
||||
class BaseConfig(AppConfig):
|
||||
"""Config for base"""
|
||||
name = 'base'
|
||||
|
||||
@ -1,17 +1,25 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Context processors for base app
|
||||
"""
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from base.api import api
|
||||
|
||||
|
||||
|
||||
def api_root(request):
|
||||
"""Returns the configured API_ROOT"""
|
||||
return {'API_ROOT': settings.OAUTH_API + settings.OAUTH_API_BASE_PATH}
|
||||
|
||||
|
||||
|
||||
def api_username(request):
|
||||
"""Returns the API username of the logged-in user"""
|
||||
if request.user.is_authenticated:
|
||||
data = api.get(request, '/users/current')
|
||||
api_username = data['username']
|
||||
username = data['username']
|
||||
else:
|
||||
api_username = 'not authenticated'
|
||||
return {'API_USERNAME': api_username}
|
||||
username = 'not authenticated'
|
||||
return {'API_USERNAME': username}
|
||||
|
||||
@ -1,18 +1,34 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Base filters
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
|
||||
class BaseFilter(object):
|
||||
"""Base for custom filter classes"""
|
||||
filter_type = None
|
||||
|
||||
def __init__(self, context, request_get):
|
||||
self.context = context
|
||||
self.request_get = request_get
|
||||
|
||||
def _apply(self, data, filter_value):
|
||||
"""
|
||||
Actual application of filter
|
||||
Needs to be implemented by child class!
|
||||
"""
|
||||
raise AttributeError('Not implemented yet!')
|
||||
|
||||
def apply(self, data):
|
||||
"""
|
||||
Apply filter to given data
|
||||
Also setup of context variables for templates
|
||||
"""
|
||||
filter_all = 'active_{}_all'.format(self.filter_type)
|
||||
self.context[filter_all] = True
|
||||
filter_active_value = 'active_{}'.format(self.filter_type)
|
||||
@ -34,6 +50,7 @@ class BaseFilter(object):
|
||||
|
||||
|
||||
class FilterTime(BaseFilter):
|
||||
"""Filter items by datetime"""
|
||||
filter_type = 'time'
|
||||
|
||||
def __init__(self, context, request_get, time_fieldname):
|
||||
|
||||
@ -1,9 +1,13 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Base utilities
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from django.contrib.humanize.templatetags.humanize import naturaltime
|
||||
|
||||
|
||||
|
||||
def json_serial(obj):
|
||||
"""JSON serializer for objects not serializable by default json code"""
|
||||
|
||||
|
||||
@ -1,9 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Views for base app
|
||||
"""
|
||||
|
||||
from django.conf import settings
|
||||
from django.views.generic import TemplateView
|
||||
|
||||
|
||||
class HomeView(TemplateView):
|
||||
"""View for home page"""
|
||||
template_name = "home.html"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
|
||||
@ -1,5 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
App config for consumers app
|
||||
"""
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AppsConfig(AppConfig):
|
||||
"""Config for consumers"""
|
||||
name = 'consumers'
|
||||
|
||||
@ -1,10 +1,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
URLs for consumers app
|
||||
"""
|
||||
|
||||
from django.conf.urls import url
|
||||
|
||||
from .views import IndexView, DetailView, EnableView, DisableView
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^$', IndexView.as_view(), name='consumers-index'),
|
||||
url(r'^(?P<consumer_id>[0-9]+)$', DetailView.as_view(), name='consumers-detail'),
|
||||
url(r'^(?P<consumer_id>[0-9]+)/enable$', EnableView.as_view(), name='consumers-enable'),
|
||||
url(r'^(?P<consumer_id>[0-9]+)/disable$', DisableView.as_view(), name='consumers-disable'),
|
||||
url(r'^$',
|
||||
IndexView.as_view(),
|
||||
name='consumers-index'),
|
||||
url(r'^(?P<consumer_id>[0-9]+)$',
|
||||
DetailView.as_view(),
|
||||
name='consumers-detail'),
|
||||
url(r'^(?P<consumer_id>[0-9]+)/enable$',
|
||||
EnableView.as_view(),
|
||||
name='consumers-enable'),
|
||||
url(r'^(?P<consumer_id>[0-9]+)/disable$',
|
||||
DisableView.as_view(),
|
||||
name='consumers-disable'),
|
||||
]
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import json
|
||||
from copy import deepcopy
|
||||
"""
|
||||
Views of consumers app
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from django.conf import settings
|
||||
@ -11,11 +13,11 @@ from django.views.generic import TemplateView, RedirectView
|
||||
|
||||
from base.api import api, APIError
|
||||
from base.filters import BaseFilter, FilterTime
|
||||
from base.utils import json_serial
|
||||
|
||||
|
||||
|
||||
class FilterAppType(BaseFilter):
|
||||
"""Filter consumers by application type"""
|
||||
filter_type = 'apptype'
|
||||
|
||||
def _apply(self, data, filter_value):
|
||||
@ -24,6 +26,7 @@ class FilterAppType(BaseFilter):
|
||||
|
||||
|
||||
class FilterEnabled(BaseFilter):
|
||||
"""Filter consumers by enabled state"""
|
||||
filter_type = 'enabled'
|
||||
|
||||
def _apply(self, data, filter_value):
|
||||
@ -34,9 +37,11 @@ class FilterEnabled(BaseFilter):
|
||||
|
||||
|
||||
class IndexView(LoginRequiredMixin, TemplateView):
|
||||
"""Index view for consumers"""
|
||||
template_name = "consumers/index.html"
|
||||
|
||||
def scrub(self, consumers):
|
||||
"""Scrubs data in the given consumers to adher to certain formats"""
|
||||
for consumer in consumers:
|
||||
consumer['created'] = datetime.strptime(
|
||||
consumer['created'], settings.API_DATETIMEFORMAT)
|
||||
@ -70,6 +75,7 @@ class IndexView(LoginRequiredMixin, TemplateView):
|
||||
|
||||
|
||||
class DetailView(LoginRequiredMixin, TemplateView):
|
||||
"""Detail view for a consumer"""
|
||||
template_name = "consumers/detail.html"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
@ -91,7 +97,11 @@ class DetailView(LoginRequiredMixin, TemplateView):
|
||||
|
||||
|
||||
class EnableDisableView(LoginRequiredMixin, RedirectView):
|
||||
def get_redirect_url(self,*args, **kwargs):
|
||||
"""View to enable or disable a consumer"""
|
||||
enabled = False
|
||||
success = None
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
try:
|
||||
urlpath = '/management/consumers/{}'.format(kwargs['consumer_id'])
|
||||
payload = {'enabled': self.enabled}
|
||||
@ -108,10 +118,12 @@ class EnableDisableView(LoginRequiredMixin, RedirectView):
|
||||
|
||||
|
||||
class EnableView(EnableDisableView):
|
||||
"""View to enable a consumer"""
|
||||
enabled = True
|
||||
success = "Consumer has been enabled."
|
||||
|
||||
|
||||
class DisableView(EnableDisableView):
|
||||
"""View to disable a consumer"""
|
||||
enabled = False
|
||||
success = "Consumer has been disabled."
|
||||
|
||||
@ -1,5 +1,11 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
App config for OAuth 1 app
|
||||
"""
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class OauthConfig(AppConfig):
|
||||
"""Config for OAuth 1"""
|
||||
name = 'oauth'
|
||||
|
||||
@ -1,3 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
URLs for OAuth 1 app
|
||||
"""
|
||||
|
||||
from django.conf.urls import url
|
||||
|
||||
from .views import InitiateView, AuthorizeView, LogoutView
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Views for OAuth 1 app
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
|
||||
from django.conf import settings
|
||||
@ -14,7 +18,13 @@ from base.api import api
|
||||
|
||||
|
||||
class InitiateView(RedirectView):
|
||||
"""View to initiate OAuth 1 session"""
|
||||
|
||||
def get_callback_uri(self, request):
|
||||
"""
|
||||
Gets the callback URI to where the user shall be returned after
|
||||
authorization at OAuth 1 server
|
||||
"""
|
||||
base_url = '{}://{}'.format(
|
||||
request.scheme, request.environ['HTTP_HOST'])
|
||||
uri = base_url + reverse('oauth-authorize')
|
||||
@ -24,7 +34,7 @@ class InitiateView(RedirectView):
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
callback_uri = self.get_callback_uri(self.request)
|
||||
api = OAuth1Session(
|
||||
session = OAuth1Session(
|
||||
settings.OAUTH_CONSUMER_KEY,
|
||||
client_secret=settings.OAUTH_CONSUMER_SECRET,
|
||||
callback_uri=callback_uri,
|
||||
@ -32,22 +42,27 @@ class InitiateView(RedirectView):
|
||||
|
||||
try:
|
||||
url = settings.OAUTH_API + settings.OAUTH_TOKEN_PATH
|
||||
fetch_response = api.fetch_request_token(url)
|
||||
except ValueError as exc:
|
||||
messages.error(self.request, exc)
|
||||
response = session.fetch_request_token(url)
|
||||
except ValueError as err:
|
||||
messages.error(self.request, err)
|
||||
return reverse('home')
|
||||
|
||||
url = settings.OAUTH_API + settings.OAUTH_AUTHORIZATION_PATH
|
||||
authorization_url = api.authorization_url(url)
|
||||
self.request.session['oauth_token'] = fetch_response.get('oauth_token')
|
||||
self.request.session['oauth_secret'] = fetch_response.get('oauth_token_secret')
|
||||
authorization_url = session.authorization_url(url)
|
||||
self.request.session['oauth_token'] = response.get('oauth_token')
|
||||
self.request.session['oauth_secret'] = response.get('oauth_token_secret')
|
||||
self.request.session.modified = True
|
||||
return authorization_url
|
||||
|
||||
|
||||
class AuthorizeView(RedirectView):
|
||||
"""View to authorize user"""
|
||||
|
||||
def login_to_django(self):
|
||||
# Kind of faking it to establish if a user is authenticated later on
|
||||
"""
|
||||
Logs the user into Django
|
||||
Kind of faking it to establish if a user is authenticated later on
|
||||
"""
|
||||
data = api.get(self.request, '/users/current')
|
||||
userid = data['user_id'] or data['email']
|
||||
username = hashlib.sha256(userid.encode('utf-8')).hexdigest()
|
||||
@ -58,24 +73,26 @@ class AuthorizeView(RedirectView):
|
||||
login(self.request, user)
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
api = OAuth1Session(
|
||||
session = OAuth1Session(
|
||||
settings.OAUTH_CONSUMER_KEY,
|
||||
settings.OAUTH_CONSUMER_SECRET,
|
||||
resource_owner_key=self.request.session['oauth_token'],
|
||||
resource_owner_secret=self.request.session['oauth_secret']
|
||||
)
|
||||
api.parse_authorization_response(self.request.build_absolute_uri())
|
||||
session.parse_authorization_response(self.request.build_absolute_uri())
|
||||
url = settings.OAUTH_API + settings.OAUTH_ACCESS_TOKEN_PATH
|
||||
fetch_response = api.fetch_access_token(url)
|
||||
response = session.fetch_access_token(url)
|
||||
|
||||
self.request.session['oauth_token'] = fetch_response.get('oauth_token')
|
||||
self.request.session['oauth_secret'] = fetch_response.get('oauth_token_secret')
|
||||
self.request.session['oauth_token'] = response.get('oauth_token')
|
||||
self.request.session['oauth_secret'] = response.get('oauth_token_secret')
|
||||
self.login_to_django()
|
||||
redirect_url = self.request.GET.get('next', reverse('consumers-index'))
|
||||
return redirect_url
|
||||
|
||||
|
||||
class LogoutView(RedirectView):
|
||||
"""View to logout"""
|
||||
|
||||
def get_redirect_url(self, *args, **kwargs):
|
||||
logout(self.request)
|
||||
return reverse('home')
|
||||
|
||||
@ -1,5 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
App config for users app
|
||||
"""
|
||||
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
|
||||
class UsersConfig(AppConfig):
|
||||
"""Config for users"""
|
||||
name = 'users'
|
||||
|
||||
@ -1,3 +1,8 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
URLs for users app
|
||||
"""
|
||||
|
||||
from django.conf.urls import url
|
||||
|
||||
from .views import IndexView, DetailView, AddEntitlementView, DeleteEntitlementView
|
||||
|
||||
@ -1,30 +1,32 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Views of users app
|
||||
"""
|
||||
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.http import HttpResponseRedirect
|
||||
from django.urls import reverse
|
||||
from django.views.generic import TemplateView, RedirectView, View
|
||||
from django.views.generic import TemplateView, View
|
||||
|
||||
from base.filters import BaseFilter
|
||||
from base.api import api, APIError
|
||||
|
||||
|
||||
class FilterRoleName(BaseFilter):
|
||||
"""Filter users by role names"""
|
||||
filter_type = 'role_name'
|
||||
|
||||
def _apply(self, data, filter_value):
|
||||
filtered = [x for x in data if filter_value in [e['role_name'] for e in x['entitlements']['list']]]
|
||||
filtered = [x for x in data if filter_value in [
|
||||
e['role_name'] for e in x['entitlements']['list']
|
||||
]]
|
||||
return filtered
|
||||
|
||||
|
||||
|
||||
class IndexView(LoginRequiredMixin, TemplateView):
|
||||
"""Index view for users"""
|
||||
template_name = "users/index.html"
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
@ -56,6 +58,7 @@ class IndexView(LoginRequiredMixin, TemplateView):
|
||||
|
||||
|
||||
class DetailView(LoginRequiredMixin, TemplateView):
|
||||
"""Detail view for a user"""
|
||||
template_name = 'users/detail.html'
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
@ -86,7 +89,10 @@ class DetailView(LoginRequiredMixin, TemplateView):
|
||||
|
||||
|
||||
class AddEntitlementView(LoginRequiredMixin, View):
|
||||
"""View to add an entitlement by role name (and bank ID)"""
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
"""Posts entitlement data to API"""
|
||||
try:
|
||||
urlpath = '/users/{}/entitlements'.format(kwargs['user_id'])
|
||||
payload = {
|
||||
@ -108,7 +114,10 @@ class AddEntitlementView(LoginRequiredMixin, View):
|
||||
|
||||
|
||||
class DeleteEntitlementView(LoginRequiredMixin, View):
|
||||
"""View to delete an entitlement"""
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
"""Deletes entitlement from API"""
|
||||
try:
|
||||
urlpath = '/users/{}/entitlement/{}'.format(
|
||||
kwargs['user_id'], kwargs['entitlement_id'])
|
||||
|
||||
Loading…
Reference in New Issue
Block a user