Exemplo n.º 1
0
from core_resources.helpers.api_library import APIResponse, APIConverter
from oauth2_provider.decorators import protected_resource
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from core_resources.proto import APIV1_pb2 as API
from core_resources.models import User
from django.views import View


@method_decorator(protected_resource(), name='dispatch')
@method_decorator(csrf_exempt, name='dispatch')
class UsersView(View):

    def get(self, request, *args, **kwargs):
        all = request.GET.get('all', None)

        # Get By Id
        if 'user_id' in kwargs:
            user_id = kwargs['user_id']

            if User.objects.filter(pk=user_id):
                db_user = User.objects.get(pk=user_id)
                pb_user = APIConverter.convert_to_pb_user(db_user, all=all, extra=True)
                return APIResponse.api_response_get(pb_user)
            else:
                return APIResponse.api_error_response(404, 'Does Not Exist User')
        else:
            db_users = User.objects.all()
            pb_user_list = API.UserList()

            aux_users = []
Exemplo n.º 2
0
class BadgerView(View):
    action = 'grant'

    @method_decorator(protected_resource(scopes=['badger']))
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, badge: str, email: str) -> HttpResponse:
        user = request.user
        action = self.action

        # See which roles this user can manage.
        may_manage = {}
        for role in user.roles.all():
            for manage_role in role.may_manage_roles.all():
                may_manage[manage_role.name] = manage_role

        if badge not in may_manage:
            log.warning(
                'User %s tried to %s badge %r to user %s, is not allowed to grant that badge.',
                user, action, badge, email)
            return HttpResponseForbidden()

        # Try to find the target user.
        try:
            target_user: bid_main_models.User = UserModel.objects.get(
                email=email)
        except UserModel.DoesNotExist:
            log.warning('User %s tried to %s badge %r to nonexistant user %s.',
                        user, action, badge, email)
            return HttpResponseUnprocessableEntity()

        # Check the role for being an active badge.
        role = may_manage[badge]
        if not role.is_badge:
            log.warning('User %s tried to %s non-badge role %r to user %s.',
                        user, action, badge, email)
            return HttpResponseForbidden()
        if not role.is_active:
            log.warning('User %s tried to %s non-active badge %r to user %s.',
                        user, action, badge, email)
            return HttpResponseForbidden()

        # Grant/revoke the role to/from the target user.
        if action == 'grant':
            log.info('User %s grants role %r to user %s.', user, badge, email)
            action_flag = ADDITION
            if role in target_user.roles.all():
                log.debug('User %s already has role %r', email, badge)
                return JsonResponse({'result': 'no-op'})
            target_user.roles.add(role)
            change_message = f'Granted role {badge}.'
        elif action == 'revoke':
            log.info('User %s revokes role %r from user %s.', user, badge,
                     email)
            action_flag = DELETION
            if role not in target_user.roles.all():
                log.debug('User %s already does not have role %r', email,
                          badge)
                return JsonResponse({'result': 'no-op'})
            target_user.roles.remove(role)
            change_message = f'Revoked role {badge}.'
        else:
            log.warning('unknown action %r', action)
            return HttpResponseUnprocessableEntity('unknown action')
        target_user.save()

        LogEntry.objects.log_action(
            user_id=user.id,
            content_type_id=ContentType.objects.get_for_model(UserModel).pk,
            object_id=target_user.id,
            object_repr=str(target_user),
            action_flag=action_flag,
            change_message=change_message)

        return JsonResponse({'result': 'ok'})
Exemplo n.º 3
0
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.decorators import protected_resource

from expenses.models import Category, DeletionRecord, DATA_MODELS, STR_TO_DATA_MODEL_MAP
from expenses.utils import parse_dt


def hello(_request):
    return JsonResponse({
        "auth_url": reverse("oauth2_provider:authorize"),
        "token_url": reverse("oauth2_provider:token"),
    })


@method_decorator([protected_resource(), csrf_exempt], name="dispatch")
class PostJsonEndpoint(View):
    def get(self, _request):
        return JsonResponse({"error": "Only POST requests allowed"},
                            status=400)

    def post(self, request):
        try:
            req_data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "POST data must be JSON"},
                                status=400)

        out, status = self.get_response(request, req_data)
        return JsonResponse(out, status=status)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
from django.conf.urls import url
from .urls import urlpatterns
from oauth2_provider.decorators import protected_resource
from .views.run import simple_search, run_custom_public_read_api_by_slug

urlpatterns += [
    url(r'^api/oauth2/(?P<database_name>[^/]+)/(?P<collection_name>[^/]+)/(?P<slug>[^.]+).(?P<output_type>[^/]+)$',
        protected_resource()(simple_search),
        name="djmongo_api_oauth2_simple_search"),
    url(r'^api/custom/oauth2/(?P<slug>\S+)$',
        protected_resource()(run_custom_public_read_api_by_slug),
        name="djmongo_run_custom_oauth2_read_api_by_slug"),
]
Exemplo n.º 5
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4
from django.conf.urls import url
from .views import write_to_collection_httpauth
from .oauth_views import write_to_collection_oauth2
from .urls import urlpatterns
from oauth2_provider.decorators import protected_resource

urlpatterns += [

    # Call / Run the write API
    url(r'^api/oauth2/(?P<slug>[^/]+)$',
        protected_resource()(write_to_collection_oauth2),
        name="djmongo_api_write_to_collection_with_oauth2"),
]
Exemplo n.º 6
0
 def wrapper(request, *args, **kwargs):
     if request.META.get('HTTP_AUTHORIZATION', '').startswith('Bearer'):
         return protected_resource(scopes=scopes)(view)(request, *args,
                                                        **kwargs)
     else:
         return view(request, *args, **kwargs)