def update(request, user_app_id):
    """Update record"""

    data = request.DATA

    user = helpers.get_user(request)

    data = helpers.set_null_values_if_not_exist(data, get_fields())

    try:
        item = get_application_model().objects.get(pk=user_app_id)
    except get_application_model().DoesNotExist:
        return {'code': 'user_app/not_found', 'values': [user_app_id]}, 404, False

    data['client_type'] = AbstractApplication.CLIENT_CONFIDENTIAL
    data['authorization_grant_type'] = AbstractApplication.GRANT_PASSWORD
    data['skip_authorization'] = True
    data['client_id'] = generate_client_id()
    data['client_secret'] = generate_client_secret()

    helpers.json_to_objects(item, data)
    item.user = user
    item.save()

    return {'code': 'ok', 'data': helpers.objects_to_json(request, [item])}, 200, item
def get_item_by_client_id(request, user_app_client_id):
    from oauth2_provider.models import get_application_model

    try:
        item = get_application_model().objects.get(client_id=user_app_client_id)
    except get_application_model().DoesNotExist:
        return {'code': 'user_app/not_found', 'values': [user_app_client_id]}, 404, False

    return {'code': 'ok', 'data': helpers.objects_to_json(request, [item])}, 200, item
def delete(request, user_app_id):
    """Update record"""

    from oauth2_provider.models import get_application_model

    try:
        item = get_application_model().objects.get(pk=user_app_id)
    except get_application_model().DoesNotExist:
        return {'code': 'user_app/not_found', 'values': [user_app_id]}, 404

    item.delete()

    return {'code': 'ok'}, 200
Beispiel #4
0
 def _set_token(self, request, response):
     if request.user and request.user.is_authenticated():
         access_token = request.META.get('ACCESS_TOKEN', None)
         if access_token is None:
             Application = get_application_model()
             geoserver_app = Application.objects.get(name="GeoServer")
             token = generate_token()
             ttl = datetime.datetime.now() + datetime.timedelta(days=3)
             AccessToken.objects.get_or_create(user=request.user,
                                               application=geoserver_app,
                                               expires=ttl,
                                               token=token)
             access_token = token
         response.set_cookie(
             settings.ACCESS_TOKEN_NAME,
             access_token,
             max_age=settings.SESSION_COOKIE_AGE,
             domain=settings.SESSION_COOKIE_DOMAIN,
             path=settings.SESSION_COOKIE_PATH,
             secure=settings.SESSION_COOKIE_SECURE or None,
             httponly=settings.SESSION_COOKIE_HTTPONLY or None,)
         patch_vary_headers(response, ('Cookie',))
     else:
         response.delete_cookie(settings.ACCESS_TOKEN_NAME,
                                domain=settings.SESSION_COOKIE_DOMAIN)
Beispiel #5
0
 def get_form_class(self):
     return forms.modelform_factory(
         get_application_model(),
         fields=(
             "name", "redirect_uris"
         )
     )
Beispiel #6
0
    def get(self, request, format=None):
        requester_app = request.auth.application
        target_app = request.query_params.get('target_app', '').strip()
        if target_app:
            qs = get_application_model().objects.all()
            target_app = generics.get_object_or_404(qs, client_id=target_app)
            try:
                AppToAppPermission.objects.get(requester=requester_app, target=target_app)
            except AppToAppPermission.DoesNotExist:
                raise PermissionDenied("no permissions for app %s" % target_app)
        else:
            target_app = requester_app

        secret = target_app.client_secret
        user = request.user

        payload = UserSerializer(user).data
        delete_fields = ['last_login', 'date_joined', 'uuid']
        for field in delete_fields:
            if field in payload:
                del payload[field]
        if not target_app.include_ad_groups:
            del payload['ad_groups']

        payload['iss'] = 'https://api.hel.fi/sso'  # FIXME: Make configurable
        payload['sub'] = str(user.uuid)
        payload['aud'] = target_app.client_id
        payload['exp'] = request.auth.expires
        encoded = jwt.encode(payload, secret, algorithm='HS256')

        ret = dict(token=encoded, expires_at=request.auth.expires)
        return Response(ret)
Beispiel #7
0
 def form_valid(self, form):
     # Make sure registrants can't disable the authorization step.
     # Only site admins can do that.
     original_object = get_application_model().objects.get(
         pk=form.instance.pk)
     form.instance.skip_authorization = original_object.skip_authorization
     return super(OAuthAppUpdate, self).form_valid(form)
Beispiel #8
0
def get_user_from_token(token):
    """
    Return a User model record based on the token.
    :param token: token dictionary object
    :return: User Model record
    """
    # retrieve our oauth2 application model.
    app = get_application_model().objects.get(name=settings.OAUTH2_APPLICATION_NAME)

    # Retrieve the access token and refresh token for the user.
    try:
        at = AccessToken.objects.get(application=app, token=token['access_token'])  # Hit the db indexes.
    except:
        return None

    # Check to see if the access token has expired.
    if at.expires < now():
        return None

    try:
        return get_user_model().objects.get(pk=at.user_id)
    except ObjectDoesNotExist:
        pass

    return None
Beispiel #9
0
 def load_application(self, client_id, request):
     applications = oauth2_models.get_application_model()
     try:
         request.client = applications.objects.get(client_id=client_id)
         return request.client
     except applications.DoesNotExist:
         return None
Beispiel #10
0
def get_or_create_token(user, client="GeoServer"):
    if not user or user.is_anonymous:
        return None
    try:
        application = get_application_model()
        app = application.objects.get(name=client)

        # Let's create the new AUTH TOKEN
        existing_token = None
        try:
            existing_token = AccessToken.objects.filter(user=user, application=app).order_by('-expires').first()
            if existing_token and existing_token.is_expired():
                existing_token.delete()
                existing_token = None
        except BaseException:
            existing_token = None
            tb = traceback.format_exc()
            if tb:
                logger.debug(tb)

        if not existing_token:
            token = create_auth_token(user, client)
        else:
            token = existing_token

        return token
    except BaseException:
        tb = traceback.format_exc()
        if tb:
            logger.debug(tb)
def get_list(request):
    from oauth2_provider.models import get_application_model

    try:
        items = get_application_model().objects.all()
    except:
        items = []

    return {'code': 'ok', 'data': helpers.objects_to_json(request, items)}, 200, items
Beispiel #12
0
def get_admin_token():
    Application = get_application_model()
    app = Application.objects.get(name="GeoServer")
    token = generate_token()
    AccessToken.objects.get_or_create(
        user=get_default_user(),
        application=app,
        expires=datetime.datetime.now() + datetime.timedelta(days=3),
        token=token)
    return token
Beispiel #13
0
def create_auth_token(user, client="GeoServer"):
    expires = make_token_expiration()
    Application = get_application_model()
    app = Application.objects.get(name=client)
    (access_token, created) = AccessToken.objects.get_or_create(
        user=user,
        application=app,
        expires=expires,
        token=generate_token())
    return access_token
Beispiel #14
0
def apps(request):
    username = request.user.get_username()
    user = User.objects.get(username=username)
    thrift_apps = App.objects.filter(user=user)
    oauth_apps = get_application_model().objects.filter(user=request.user)

    c = {
        'login': username,
        'thrift_apps': thrift_apps,
        'oauth_apps': oauth_apps}
    return render_to_response('apps.html', c)
Beispiel #15
0
def get_auth_token(user, client="GeoServer"):
    if not user or user.is_anonymous:
        return None
    try:
        Application = get_application_model()
        app = Application.objects.get(name=client)
        access_token = AccessToken.objects.filter(user=user, application=app).order_by('-expires').first()
        return access_token
    except BaseException:
        tb = traceback.format_exc()
        if tb:
            logger.debug(tb)
Beispiel #16
0
    def setUp(self):
        """
        Create a superuser and standard user.
        Create an Oauth2 app for superuser.
        """
        self.superuser = get_user_model().objects.create_superuser('admin', password='******', email='*****@*****.**')
        self.user = get_user_model().objects.create_user('test', password='******', email='*****@*****.**')

        self.app = get_application_model().objects.create(
            name='app',
            client_type=get_application_model().CLIENT_CONFIDENTIAL,
            authorization_grant_type=get_application_model().GRANT_CLIENT_CREDENTIALS,
            user=self.superuser
        )

        self.access_token = AccessToken.objects.create(user=self.superuser,
                                                       token='token_monster',
                                                       application=self.app,
                                                       expires=now() + timedelta(seconds=300))

        self.auth_valid = self._gen_authorization_header(self.access_token.token)
        self.auth_invalid = self._gen_authorization_header("fake-token")
Beispiel #17
0
def delete_old_tokens(user, client='GeoServer'):
    application = get_application_model()
    app = application.objects.get(name=client)

    # Lets delete the old one
    try:
        old_tokens = AccessToken.objects.filter(user=user, application=app).order_by('-expires')
        for old in old_tokens:
            if old.is_expired():
                old.delete()
    except BaseException:
        tb = traceback.format_exc()
        if tb:
            logger.debug(tb)
Beispiel #18
0
 def authenticate_credentials(self, userid, password):
     """
     Authenticate the userid and password against username and password.
     """
     from oauth2_provider.models import get_application_model
     Application = get_application_model()
     if self.client_ids and not userid in self.client_ids:
         raise exceptions.AuthenticationFailed('Invalid client_id')
     try:
         app = Application.objects.get(client_id=userid)
     except ObjectDoesNotExist:
         raise exceptions.AuthenticationFailed('Invalid client_id')
     if userid==app.client_id and password==app.client_secret:
         #print 'did login',userid
         return (AnonymousUser, app)
     raise exceptions.AuthenticationFailed('Invalid username/password')
Beispiel #19
0
def create_access_token(user, scope):
    """
    Takes a user instance and return an access_token as a JsonResponse
    instance.

    :param user: django user instance
    :param scope: should be valid oauth scope value
    :return: Token dictionary object

    """

    # retrieve our oauth2 application model
    app = get_application_model().objects.get(name=settings.OAUTH2_APPLICATION_NAME)

    # Delete any existing access and refresh tokens.
    try:
        at = AccessToken.objects.get(user=user, application=app)
        RefreshToken.objects.get(user=user, access_token=at).delete()
        at.delete()
    except:
        pass

    # Generate new tokens
    atoken = generate_token()
    rtoken = generate_token()

    # Setup the access token expiration value.
    expires = now() + timedelta(seconds=oauth2_settings.ACCESS_TOKEN_EXPIRE_SECONDS)

    # Create the access token model object.
    access_token = AccessToken.objects.\
        create(user=user,
               application=app,
               expires=expires,
               token=atoken,
               scope=scope)

    # Create the refresh token model object.
    RefreshToken.objects.\
        create(user=user,
               application=app,
               token=rtoken,
               access_token=access_token)

    # Return dictionary object with token information.
    return build_token_dict(access_token)
Beispiel #20
0
def create_auth_token(user, client="GeoServer"):
    if not user or user.is_anonymous:
        return None
    expires = make_token_expiration()
    try:
        Application = get_application_model()
        app = Application.objects.get(name=client)
        (access_token, created) = AccessToken.objects.get_or_create(
            user=user,
            application=app,
            expires=expires,
            token=generate_token())
        return access_token
    except BaseException:
        tb = traceback.format_exc()
        if tb:
            logger.debug(tb)
Beispiel #21
0
def do_login(sender, user, request, **kwargs):
    """
    Take action on user login. Generate a new user access_token to be shared
    with GeoServer, and store it into the request.session
    """
    if user and user.is_authenticated():
        token = None
        try:
            Application = get_application_model()
            app = Application.objects.get(name="GeoServer")

            # Lets create a new one
            token = generate_token()

            AccessToken.objects.get_or_create(
                user=user,
                application=app,
                expires=datetime.datetime.now() +
                datetime.timedelta(
                    days=1),
                token=token)
        except BaseException:
            u = uuid.uuid1()
            token = u.hex

        # Do GeoServer Login
        url = "%s%s?access_token=%s" % (settings.OGC_SERVER['default']['PUBLIC_LOCATION'],
                                        'ows?service=wms&version=1.3.0&request=GetCapabilities',
                                        token)

        cj = cookielib.CookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

        jsessionid = None
        try:
            opener.open(url)
            for c in cj:
                if c.name == "JSESSIONID":
                    jsessionid = c.value
        except BaseException:
            u = uuid.uuid1()
            jsessionid = u.hex

        request.session['access_token'] = token
        request.session['JSESSIONID'] = jsessionid
Beispiel #22
0
    def setUpClass(self):
        super(APITestBaseCase, self).setUpClass()
        Application = get_application_model()
        self.user_app = mommy.make(
            'users.User',
            username="******",
            password="******",
            email="*****@*****.**"
        )
        self.application = Application(
            name="Test Application",
            user=self.user_app,
            client_type=Application.CLIENT_CONFIDENTIAL,
            authorization_grant_type=Application.GRANT_PASSWORD,
        )
        self.application.save()
        self.factory = APIRequestFactory()
        self.client = APIClient()

        oauth2_settings._SCOPES = ['read', 'write', 'groups']
Beispiel #23
0
def is_access_token_valid(token):
    """
    Verify that the token information is valid and not expired
    :param token: token dictionary object
    :return: True is token is valid or False if invalid
    """

    # retrieve our oauth2 application model.
    app = get_application_model().objects.get(name=settings.OAUTH2_APPLICATION_NAME)

    # Retrieve the access token and refresh token for the user.
    try:
        at = AccessToken.objects.get(application=app, token=token['access_token'])  # Hit the db indexes.
    except:
        return False

    # Check to see if the access token has expired.
    if at.expires < now():
        return False

    return True
    def get_form_kwargs(self):
        kwargs = super(AuthorizationView, self).get_form_kwargs()

        # the application instance is needed by our custom AllowForm
        # to properly initialize choices for the scope field
        if self.request.method == 'GET':
            kwargs['application'] = self.oauth2_data['application']
        else:
            # in case of a PUT or POST request we must load
            # the application instance from `client_id` param in
            # the POST dict because self.oauth2_data is empty.
            client_id = self.request.POST.get('client_id')

            Application = get_application_model()
            try:
                application = Application.objects.get(client_id=client_id)
                kwargs['application'] = application
            except Application.DoesNotExist:
                logger.warning("no application found with client_id '%s'", client_id)

        return kwargs
def fill_from_mock(apps, schema_editor):
    try:
        with open("mock/user_app/list.json") as f:
            content = f.read()
            f.close()
    except IOError:
        content = "[]"
    records = json.loads(content)

    from oauth2_provider.models import get_application_model, AccessToken, RefreshToken

    for record in records:
        item, created = get_application_model().objects.get_or_create(
            client_id=record["client_id"],
            user_id=record["user_id"],
            redirect_uris=record["redirect_uris"],
            client_type=record["client_type"],
            authorization_grant_type=record["authorization_grant_type"],
            client_secret=record["client_secret"],
            name=record["name"],
            skip_authorization=record["skip_authorization"],
        )
        tokens = record["tokens"]
        for token in tokens:
            item_token, created_token = AccessToken.objects.get_or_create(
                token=token["token"],
                scope=token["scope"],
                application=item,
                user_id=token["user_id"],
                expires=(now() + timedelta(days=365)),
            )
            refresh_tokens = token["refresh_tokens"]
            for refresh_token in refresh_tokens:
                item_refresh_token, created_refresh_token = RefreshToken.objects.get_or_create(
                    token=refresh_token["token"],
                    access_token=item_token,
                    application=item,
                    user_id=refresh_token["user_id"],
                )
def create_console_app(apps, schema_editor):
    """
    Create console application.
    If the application already exists, print an error
    """
    username = OAUTH2_APP_OWNER
    user = User.objects.get(username=username)
    model = get_application_model()
    params = OAUTH2_APP_CLIENTS['console']

    keys = ['name', 'client_id', 'redirect_uris', 'client_type',
            'authorization_grant_type', 'skip_authorization']
    # Raisees KeyError for missing key in params
    [params[k] for k in keys]

    try:
        # see if the model exists
        model.objects.get(user=user, name=params['name'])
        print_if_not_testing("...console app already registered. Skipping.")
    except model.DoesNotExist:
        # if it doesn't create it
        model(user=user, **params).save()
        print_if_not_testing('...success')
def create(request):
    data = request.DATA

    user = helpers.get_user(request)

    data = helpers.set_null_values_if_not_exist(data, get_fields())

    data['client_type'] = AbstractApplication.CLIENT_CONFIDENTIAL
    data['authorization_grant_type'] = AbstractApplication.GRANT_PASSWORD
    data['skip_authorization'] = True
    data['client_id'] = generate_client_id()
    data['client_secret'] = generate_client_secret()

    item, created = get_application_model().objects.get_or_create(client_id=data['client_id'],
                                                                  user=user,
                                                                  redirect_uris=data['redirect_uris'],
                                                                  client_type=data['client_type'],
                                                                  authorization_grant_type=data[
                                                                      'authorization_grant_type'],
                                                                  client_secret=data['client_secret'],
                                                                  name=data['name'],
                                                                  skip_authorization=data['skip_authorization'])

    return {'code': 'ok', 'data': helpers.objects_to_json(request, [item])}, 200, item
Beispiel #28
0
def refresh_access_token(token):
    """
    Refresh the access token from the refresh token, call is_access_token_valid() first.
    :param user: django user object
    :param token: token dictionary object
    :param scope: should be valid oauth scope value
    :return: token dictionary object or empty dictionary object
    """

    # retrieve our oauth2 application model.
    app = get_application_model().objects.get(name=settings.OAUTH2_APPLICATION_NAME)

    # Retrieve the access token and refresh token for the user.
    # Make sure the AT and RT are connected and not stale for some reason
    try:
        at = AccessToken.objects.get(application=app, token=token['access_token'])  # Hit the db indexes.
        rt = RefreshToken.objects.get(access_token=at, token=token['refresh_token'])  # Hit the db indexes.
    except:
        return dict()

    if not rt.user.is_active:
        return dict()

    return create_access_token(rt.user, rt.user.profile.oauth_scope)
Beispiel #29
0
# -* encoding: utf-8 *-
from argparse import _SubParsersAction

import sys
from typing import List

from django.core.management.base import BaseCommand, CommandParser
from django.db import transaction
from django.db.models.query_utils import Q
from django.db.utils import DatabaseError
from oauth2_provider import models as oauth2_models
from typing import Any

from mailauth.management.commands._common import _handle_client_registration, _add_publishing_args

appmodel = oauth2_models.get_application_model()  # type: oauth2_models.Application


class Command(BaseCommand):
    requires_migrations_checks = True

    def add_arguments(self, parser: CommandParser) -> None:
        class SubCommandParser(CommandParser):
            def __init__(self, **kwargs: Any) -> None:
                super().__init__(**kwargs)

        subparsers = parser.add_subparsers(
            dest='scmd',
            title="subcommands",
            parser_class=SubCommandParser
        )  # type: _SubParsersAction
Beispiel #30
0
 class Meta:
     model = get_application_model()
     fields = ('scope', 'name', 'client_type', 'authorization_grant_type',
               'redirect_uris')
from rest_framework.test import APIClient
from test_plus.test import TestCase

from django.core import mail
from django.conf import settings
from django.contrib.auth.models import Group
from django.urls import reverse

from accelerator_abstract.models.base_clearance import (
    CLEARANCE_LEVEL_GLOBAL_MANAGER, CLEARANCE_LEVEL_STAFF)
from impact.tests.factories import (
    ClearanceFactory,
    UserFactory,
)

OAuth_App = get_application_model()
API_GROUPS = [settings.V0_API_GROUP, settings.V1_API_GROUP]
DESCRIPTION_CONTENT = 'DESCRIPTION:Topics: {topics}'
LOCATION_CONTENT = 'LOCATION:{location}\\;'
LOCATION_INFO = 'LOCATION:{location}\\;{meeting_info}'


class APITestCase(TestCase):
    SOME_SITE_NAME = "somesite.com"
    _user_count = 0
    client_class = APIClient
    user_factory = UserFactory

    @classmethod
    def setUpClass(cls):
        [Group.objects.get_or_create(name=name) for name in API_GROUPS]
Beispiel #32
0
 class Meta:
     model = get_application_model()
     fields = ('name', 'client_type', 'authorization_grant_type',
               'redirect_uris', 'logo_uri', 'policy_uri', 'tos_uri',
               'contacts', 'agree')
Beispiel #33
0
def proxy(request, url=None, response_callback=None,
          sec_chk_hosts=True, sec_chk_rules=True, **kwargs):
    # Security rules and settings
    PROXY_ALLOWED_HOSTS = getattr(settings, 'PROXY_ALLOWED_HOSTS', ())

    # Sanity url checks
    if 'url' not in request.GET and not url:
        return HttpResponse("The proxy service requires a URL-encoded URL as a parameter.",
                            status=400,
                            content_type="text/plain"
                            )

    raw_url = url or request.GET['url']
    raw_url = urljoin(
        settings.SITEURL,
        raw_url) if raw_url.startswith("/") else raw_url
    url = urlsplit(raw_url)
    locator = str(url.path)
    if url.query != "":
        locator += '?' + url.query
    if url.fragment != "":
        locator += '#' + url.fragment

    # White-Black Listing Hosts
    if sec_chk_hosts and not settings.DEBUG:
        site_url = urlsplit(settings.SITEURL)
        if site_url.hostname not in PROXY_ALLOWED_HOSTS:
            PROXY_ALLOWED_HOSTS += (site_url.hostname, )

        if check_ogc_backend(geoserver.BACKEND_PACKAGE):
            from geonode.geoserver.helpers import ogc_server_settings
            hostname = (
                ogc_server_settings.hostname,
            ) if ogc_server_settings else ()
            if hostname not in PROXY_ALLOWED_HOSTS:
                PROXY_ALLOWED_HOSTS += hostname

        if url.query and ows_regexp.match(url.query):
            ows_tokens = ows_regexp.match(url.query).groups()
            if len(ows_tokens) == 4 and 'version' == ows_tokens[0] and StrictVersion(
                    ows_tokens[1]) >= StrictVersion("1.0.0") and StrictVersion(
                        ows_tokens[1]) <= StrictVersion("3.0.0") and ows_tokens[2].lower() in (
                            'getcapabilities') and ows_tokens[3].upper() in ('OWS', 'WCS', 'WFS', 'WMS', 'WPS', 'CSW'):
                if url.hostname not in PROXY_ALLOWED_HOSTS:
                    PROXY_ALLOWED_HOSTS += (url.hostname, )

        if not validate_host(
                url.hostname, PROXY_ALLOWED_HOSTS):
            return HttpResponse("DEBUG is set to False but the host of the path provided to the proxy service"
                                " is not in the PROXY_ALLOWED_HOSTS setting.",
                                status=403,
                                content_type="text/plain"
                                )

    # Security checks based on rules; allow only specific requests
    if sec_chk_rules:
        # TODO: Not yet implemented
        pass

    # Collecting headers and cookies
    headers = {}
    cookies = None
    csrftoken = None

    if settings.SESSION_COOKIE_NAME in request.COOKIES and is_safe_url(
            url=raw_url, host=url.hostname):
        cookies = request.META["HTTP_COOKIE"]

    for cook in request.COOKIES:
        name = str(cook)
        value = request.COOKIES.get(name)
        if name == 'csrftoken':
            csrftoken = value
        cook = "%s=%s" % (name, value)
        cookies = cook if not cookies else (cookies + '; ' + cook)

    csrftoken = get_token(request) if not csrftoken else csrftoken

    if csrftoken:
        headers['X-Requested-With'] = "XMLHttpRequest"
        headers['X-CSRFToken'] = csrftoken
        cook = "%s=%s" % ('csrftoken', csrftoken)
        cookies = cook if not cookies else (cookies + '; ' + cook)

    if cookies:
        if 'JSESSIONID' in request.session and request.session['JSESSIONID']:
            cookies = cookies + '; JSESSIONID=' + \
                request.session['JSESSIONID']
        headers['Cookie'] = cookies

    if request.method in ("POST", "PUT") and "CONTENT_TYPE" in request.META:
        headers["Content-Type"] = request.META["CONTENT_TYPE"]

    access_token = None
    if request and 'access_token' in request.session:
        access_token = request.session['access_token']

    if 'HTTP_AUTHORIZATION' in request.META:
        auth = request.META.get(
            'HTTP_AUTHORIZATION',
            request.META.get('HTTP_AUTHORIZATION2'))
        if auth:
            _user = user_from_basic_auth(auth)
            if not _user:
                if 'Bearer' in auth:
                    access_token = auth.replace('Bearer ', '')
                    headers['Authorization'] = auth
            else:
                try:
                    from oauth2_provider.models import AccessToken, get_application_model
                    Application = get_application_model()
                    app = Application.objects.get(name="GeoServer")
                    access_token = AccessToken.objects.filter(user=_user, application=app).order_by('-expires').first()
                except BaseException:
                    traceback.print_exc()
                    logger.error("Could retrieve OAuth2 Access Token for user %s" % _user)

    if access_token and not headers.get('Authorization'):
        headers['Authorization'] = 'Bearer %s' % access_token

    site_url = urlsplit(settings.SITEURL)

    pragma = "no-cache"
    referer = request.META[
        "HTTP_REFERER"] if "HTTP_REFERER" in request.META else \
        "{scheme}://{netloc}/".format(scheme=site_url.scheme,
                                      netloc=site_url.netloc)
    encoding = request.META["HTTP_ACCEPT_ENCODING"] if "HTTP_ACCEPT_ENCODING" in request.META else "gzip"

    headers.update({"Pragma": pragma,
                    "Referer": referer,
                    "Accept-encoding": encoding, })

    if url.scheme == 'https':
        conn = HTTPSConnection(url.hostname, url.port)
    else:
        conn = HTTPConnection(url.hostname, url.port)
    parsed = urlparse(raw_url)
    parsed._replace(path=locator.encode('utf8'))

    _url = parsed.geturl()

    if request.method == "GET" and access_token and 'access_token' not in _url:
        query_separator = '&' if '?' in _url else '?'
        _url = ('%s%saccess_token=%s' %
                (_url, query_separator, access_token))

    conn.request(request.method, _url, request.body, headers)
    response = conn.getresponse()
    content = response.read()
    status = response.status
    content_type = response.getheader("Content-Type", "text/plain")

    # decompress GZipped responses if not enabled
    if content and response.getheader('Content-Encoding') == 'gzip':
        from StringIO import StringIO
        import gzip
        buf = StringIO(content)
        f = gzip.GzipFile(fileobj=buf)
        content = f.read()

    if response_callback:
        kwargs = {} if not kwargs else kwargs
        kwargs.update({
            'response': response,
            'content': content,
            'status': status,
            'content_type': content_type
        })
        return response_callback(**kwargs)
    else:
        # If we get a redirect, let's add a useful message.
        if status in (301, 302, 303, 307):
            _response = HttpResponse(('This proxy does not support redirects. The server in "%s" '
                                      'asked for a redirect to "%s"' % (url, response.getheader('Location'))),
                                     status=status,
                                     content_type=content_type
                                     )
            _response['Location'] = response.getheader('Location')
            return _response
        else:
            return HttpResponse(
                content=content,
                status=status,
                content_type=content_type)
Beispiel #34
0
    def get(self, request, *args, **kwargs):  # noqa  (too complex)
        next_url = request.GET.get('next')
        app = None
        oidc_client = None

        if next_url:
            # Determine application from the 'next' query argument.
            # FIXME: There should be a better way to get the app id.
            params = parse_qs(urlparse(next_url).query)
            client_id = params.get('client_id')

            if client_id and len(client_id):
                client_id = client_id[0].strip()

            if client_id:
                try:
                    app = get_application_model().objects.get(
                        client_id=client_id)
                except get_application_model().DoesNotExist:
                    pass

                try:
                    oidc_client = Client.objects.get(client_id=client_id)
                except Client.DoesNotExist:
                    pass

            next_url = quote(next_url)

        allowed_methods = None
        if app:
            allowed_methods = app.login_methods.all()
        elif oidc_client:
            try:
                client_options = OidcClientOptions.objects.get(
                    oidc_client=oidc_client)
                allowed_methods = client_options.login_methods.all()
            except OidcClientOptions.DoesNotExist:
                pass

        if allowed_methods is None:
            allowed_methods = LoginMethod.objects.all()

        methods = []
        for m in allowed_methods:
            if m.provider_id == 'saml':
                continue  # SAML support removed

            m.login_url = reverse('social:begin',
                                  kwargs={'backend': m.provider_id})
            if next_url:
                m.login_url += '?next=' + next_url

            if m.provider_id in getattr(settings,
                                        'SOCIAL_AUTH_SUOMIFI_ENABLED_IDPS'):
                # This check is used to exclude Suomi.fi auth method when using non-compliant auth provider
                if next_url is None:
                    continue
                if re.match(
                        getattr(settings,
                                'SOCIAL_AUTH_SUOMIFI_CALLBACK_MATCH'),
                        next_url) is None:
                    continue
                m.login_url += '&amp;idp=' + m.provider_id

            methods.append(m)

        if len(methods) == 1:
            return redirect(methods[0].login_url)

        self.login_methods = methods
        return super(LoginView, self).get(request, *args, **kwargs)
Beispiel #35
0
    def get(self, request, *args, **kwargs):
        next_url = request.GET.get('next')
        app = None
        oidc_client = None

        if next_url:
            # Determine application from the 'next' query argument.
            # FIXME: There should be a better way to get the app id.
            params = parse_qs(urlparse(next_url).query)
            client_id = params.get('client_id')

            if client_id and len(client_id):
                client_id = client_id[0].strip()

            if client_id:
                try:
                    app = get_application_model().objects.get(
                        client_id=client_id)
                except get_application_model().DoesNotExist:
                    pass

                try:
                    oidc_client = Client.objects.get(client_id=client_id)
                except Client.DoesNotExist:
                    pass

            next_url = quote(next_url)

        allowed_methods = None
        if app:
            allowed_methods = app.login_methods.all()
        elif oidc_client:
            try:
                client_options = OidcClientOptions.objects.get(
                    oidc_client=oidc_client)
                allowed_methods = client_options.login_methods.all()
            except OidcClientOptions.DoesNotExist:
                pass

        if allowed_methods is None:
            allowed_methods = LoginMethod.objects.all()

        provider_map = providers.registry.provider_map
        methods = []
        for m in allowed_methods:
            assert isinstance(m, LoginMethod)
            if m.provider_id == 'saml':
                continue  # SAML support removed
            else:
                try:
                    provider_cls = provider_map[m.provider_id]
                except KeyError:
                    continue
                provider = provider_cls(request)
                login_url = provider.get_login_url(request=self.request)
                if next_url:
                    login_url += '?next=' + next_url
            m.login_url = login_url
            methods.append(m)

        if len(methods) == 1:
            return redirect(methods[0].login_url)

        self.login_methods = methods
        return super(LoginView, self).get(request, *args, **kwargs)
Beispiel #36
0
    def get_oauth2_app_by_client_id(self, client_id):
        Application = get_application_model()
        oauth_app = Application.objects.filter(client_id=client_id).first()

        return oauth_app
Beispiel #37
0
        'get_user',
    )


@admin.register(MNApplicationPermission)
class MNApplicationPermissionAdmin(admin.ModelAdmin):
    search_fields = ('name', )


@admin.register(MNGroup)
class MNGroupAdmin(admin.ModelAdmin):
    search_fields = ('name', )
    fieldsets = (
        (None, {
            'fields': ('name', )
        }),
        ("Application permissions", {
            'fields': ('group_permissions', )
        }),
    )  # type: Tuple[Tuple[Union[str, None], Dict[str, Tuple[str, ...]]], ...]
    filter_horizontal = ('group_permissions', )


class MNApplicationAdmin(ApplicationAdmin):
    filter_horizontal = ('required_permissions', )


if get_application_model() == MNApplication:
    admin.site.unregister(MNApplication)
    admin.site.register(MNApplication, MNApplicationAdmin)
Beispiel #38
0
 def get_queryset(self):
     user = self.request.user
     return get_application_model().objects.filter(user=user)
Beispiel #39
0
    def form_valid(self, form):
        client_id = form.cleaned_data["client_id"]
        application = get_application_model().objects.get(client_id=client_id)
        credentials = {
            "client_id":
            form.cleaned_data.get("client_id"),
            "redirect_uri":
            form.cleaned_data.get("redirect_uri"),
            "response_type":
            form.cleaned_data.get("response_type", None),
            "state":
            form.cleaned_data.get("state", None),
            "code_challenge":
            form.cleaned_data.get("code_challenge", None),
            "code_challenge_method":
            form.cleaned_data.get("code_challenge_method", None),
        }
        scopes = form.cleaned_data.get("scope")
        allow = form.cleaned_data.get("allow")

        # Get beneficiary demographic scopes sharing choice
        share_demographic_scopes = form.cleaned_data.get(
            "share_demographic_scopes")
        set_session_auth_flow_trace_value(self.request,
                                          'auth_share_demographic_scopes',
                                          share_demographic_scopes)

        # Get scopes list available to the application
        application_available_scopes = CapabilitiesScopes(
        ).get_available_scopes(application=application)

        # Set scopes to those available to application and beneficiary demographic info choices
        scopes = ' '.join([
            s for s in scopes.split(" ") if s in application_available_scopes
        ])

        # Init deleted counts
        data_access_grant_delete_cnt = 0
        access_token_delete_cnt = 0
        refresh_token_delete_cnt = 0

        try:
            uri, headers, body, status = self.create_authorization_response(
                request=self.request,
                scopes=scopes,
                credentials=credentials,
                allow=allow)
        except OAuthToolkitError as error:
            response = self.error_response(error, application)

            if allow is False:
                (data_access_grant_delete_cnt, access_token_delete_cnt,
                 refresh_token_delete_cnt
                 ) = remove_application_user_pair_tokens_data_access(
                     application, self.request.user)

            beneficiary_authorized_application.send(
                sender=self,
                request=self.request,
                auth_status="FAIL",
                auth_status_code=response.status_code,
                user=self.request.user,
                application=application,
                share_demographic_scopes=share_demographic_scopes,
                scopes=scopes,
                allow=allow,
                access_token_delete_cnt=access_token_delete_cnt,
                refresh_token_delete_cnt=refresh_token_delete_cnt,
                data_access_grant_delete_cnt=data_access_grant_delete_cnt)
            return response

        # Did the beneficiary choose not to share demographic scopes, or the application does not require them?
        if share_demographic_scopes == "False" or (
                allow is True
                and application.require_demographic_scopes is False):
            (data_access_grant_delete_cnt, access_token_delete_cnt,
             refresh_token_delete_cnt
             ) = remove_application_user_pair_tokens_data_access(
                 application, self.request.user)

        beneficiary_authorized_application.send(
            sender=self,
            request=self.request,
            auth_status="OK",
            auth_status_code=None,
            user=self.request.user,
            application=application,
            share_demographic_scopes=share_demographic_scopes,
            scopes=scopes,
            allow=allow,
            access_token_delete_cnt=access_token_delete_cnt,
            refresh_token_delete_cnt=refresh_token_delete_cnt,
            data_access_grant_delete_cnt=data_access_grant_delete_cnt)

        self.success_url = uri
        log.debug("Success url for the request: {0}".format(self.success_url))

        # Extract code from url
        url_query = parse_qs(urlparse(self.success_url).query)
        code = url_query.get('code', [None])[0]

        # Get auth flow trace session values dict.
        auth_dict = get_session_auth_flow_trace(self.request)

        # We are done using auth_uuid, clear it from the session.
        cleanup_session_auth_flow_trace(self.request)

        # Update AuthFlowUuid instance with code.
        update_instance_auth_flow_trace_with_code(auth_dict, code)

        return self.redirect(self.success_url, application)
from django.utils.timezone import now
from django.test import Client, TestCase
from django.contrib.auth.models import User
from oauth2_provider.models import AccessToken, get_application_model

import json
from datetime import datetime, timedelta
import numpy as np
import pytz

from datastore import models

ApplicationModel = get_application_model()


class OAuthTestCase(TestCase):

    @classmethod
    def setUpTestData(cls):
        """
        Includes a client, a demo user/project_owner, an application model
        and an Oauth token.
        """
        super(OAuthTestCase, cls).setUpTestData()

        cls.client = Client()
        cls.user = User.objects.create_user(
            "username", "*****@*****.**", "123456")
        cls.project_owner = cls.user.projectowner

        cls.project = models.Project.objects.create(
Beispiel #41
0
def create_application():
    Application = get_application_model()
    Application.objects.get_or_create(name='GeoServer')
Beispiel #42
0
 def get_queryset(self):
     Application = get_application_model()
     return Application.objects.filter(user=self.request.user)
Beispiel #43
0
 def form_valid(self, form):
     app = get_application_model()
     form.instance.authorization_grant_type = app.GRANT_AUTHORIZATION_CODE
     return super(LimitedApplicationRegistration, self).form_valid(form)
Beispiel #44
0
 def tearDown(self):
     super().tearDown()
     get_application_model().objects.all().delete()
Beispiel #45
0
import ddt
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.utils import override_settings
from edx_oauth2_provider.tests.factories import ClientFactory
import httpretty
from oauth2_provider.models import get_application_model

from openedx.core.djangoapps.api_admin.models import ApiAccessRequest, ApiAccessConfig
from openedx.core.djangoapps.api_admin.tests.factories import (
    ApiAccessRequestFactory, ApplicationFactory, CatalogFactory)
from openedx.core.djangoapps.api_admin.tests.utils import VALID_DATA
from student.tests.factories import UserFactory

Application = get_application_model()  # pylint: disable=invalid-name

MOCK_CATALOG_API_URL_ROOT = 'https://api.example.com/'


class ApiAdminTest(TestCase):
    def setUp(self):
        super(ApiAdminTest, self).setUp()
        ApiAccessConfig(enabled=True).save()


@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls',
                     'Test only valid in lms')
class ApiRequestViewTest(ApiAdminTest):
    def setUp(self):
        super(ApiRequestViewTest, self).setUp()
Beispiel #46
0
    def get(self, request, *args, **kwargs):
        # Copy/Pasta'd from oauth2_provider.views.BaseAuthorizationView.get
        try:
            scopes, credentials = self.validate_authorization_request(request)
            # all_scopes = get_scopes_backend().get_all_scopes()
            # kwargs["scopes"] = scopes
            # kwargs["scopes_descriptions"] = [all_scopes[scope] for scope in scopes]
            # at this point we know an Application instance with such client_id exists in the database

            # TODO: Cache this!
            application = get_application_model().objects.get(
                client_id=credentials["client_id"])

            kwargs["client_id"] = credentials["client_id"]
            kwargs["redirect_uri"] = credentials["redirect_uri"]
            kwargs["response_type"] = credentials["response_type"]
            kwargs["state"] = credentials["state"]
            try:
                kwargs["application"] = {
                    "name": application.applicationinfo.get_visible_name(),
                }
                if application.applicationinfo.icon:
                    kwargs["application"][
                        'image'] = application.applicationinfo.icon.url
                if application.applicationinfo.website_url:
                    kwargs["application"][
                        "url"] = application.applicationinfo.website_url
                app_scopes = [
                    s for s in re.split(
                        r'[\s\n]+', application.applicationinfo.allowed_scopes)
                    if s
                ]
            except ApplicationInfo.DoesNotExist:
                app_scopes = ["r:profile"]
                kwargs["application"] = dict(name=application.name,
                                             scopes=app_scopes)

            filtered_scopes = set(app_scopes) & set(scopes)
            kwargs['scopes'] = list(filtered_scopes)
            all_scopes = get_scopes_backend().get_all_scopes()
            kwargs['scopes_descriptions'] = {
                scope: all_scopes[scope]
                for scope in scopes
            }

            self.oauth2_data = kwargs

            # Check to see if the user has already granted access and return
            # a successful response depending on "approval_prompt" url parameter
            require_approval = request.GET.get(
                "approval_prompt", oauth2_settings.REQUEST_APPROVAL_PROMPT)

            # If skip_authorization field is True, skip the authorization screen even
            # if this is the first use of the application and there was no previous authorization.
            # This is useful for in-house applications-> assume an in-house applications
            # are already approved.
            if application.skip_authorization:
                success_url = self.get_authorization_redirect_url(
                    " ".join(kwargs['scopes']), credentials)
                return Response({'success_url': success_url})

            elif require_approval == "auto" and not request.user.is_anonymous:
                tokens = get_access_token_model().objects.filter(
                    user=request.user,
                    application=application,
                    expires__gt=timezone.now()).all()

                # check past authorizations regarded the same scopes as the current one
                for token in tokens:
                    if token.allow_scopes(scopes):
                        success_url = self.get_authorization_redirect_url(
                            " ".join(kwargs['scopes']), credentials)
                        return Response({'success_url': success_url})

            return Response(kwargs)

        except OAuthToolkitError as error:
            return Response({'error': error.oauthlib_error.description},
                            status=HTTP_400_BAD_REQUEST)
Beispiel #47
0
    def get(self, request, *args, **kwargs):
        # Note: This code is copied from https://github.com/evonove/django-oauth-toolkit/blob/34f3b7b3511c15686039079026165feaadb1b87d/oauth2_provider/views/base.py#L111
        # Places that we have changed are noted with ***.
        application = None
        try:
            # *** Moved code to get the require_approval value earlier on so we can
            # circumvent our custom code in the case when auto_even_if_expired
            # isn't required.
            require_approval = request.GET.get(
                "approval_prompt",
                oauth2_settings.REQUEST_APPROVAL_PROMPT,
            )
            if require_approval != 'auto_even_if_expired':
                return super(EdxOAuth2AuthorizationView,
                             self).get(request, *args, **kwargs)

            scopes, credentials = self.validate_authorization_request(request)
            all_scopes = get_scopes_backend().get_all_scopes()
            kwargs["scopes_descriptions"] = [
                all_scopes[scope] for scope in scopes
            ]
            kwargs['scopes'] = scopes

            # at this point we know an Application instance with such client_id exists in the database
            application = get_application_model().objects.get(
                client_id=credentials['client_id'])
            content_orgs = ApplicationOrganization.get_related_org_names(
                application,
                relation_type=ApplicationOrganization.RELATION_TYPE_CONTENT_ORG
            )
            kwargs['application'] = application
            kwargs['content_orgs'] = content_orgs
            kwargs['client_id'] = credentials['client_id']
            kwargs['redirect_uri'] = credentials['redirect_uri']
            kwargs['response_type'] = credentials['response_type']
            kwargs['state'] = credentials['state']

            self.oauth2_data = kwargs
            # following two loc are here only because of https://code.djangoproject.com/ticket/17795
            form = self.get_form(self.get_form_class())
            kwargs['form'] = form

            # If skip_authorization field is True, skip the authorization screen even
            # if this is the first use of the application and there was no previous authorization.
            # This is useful for in-house applications-> assume an in-house applications
            # are already approved.
            if application.skip_authorization:
                uri, headers, body, status = self.create_authorization_response(
                    request=self.request,
                    scopes=" ".join(scopes),
                    credentials=credentials,
                    allow=True)
                return HttpResponseUriRedirect(
                    uri, application.get_allowed_schemes())

            # *** Changed the if statement that checked for require_approval to an assert.
            assert require_approval == 'auto_even_if_expired'
            tokens = get_access_token_model().objects.filter(
                user=request.user,
                application=kwargs['application'],
                # *** Purposefully keeping this commented out code to highlight that
                # our version of the implementation does NOT filter by expiration date.
                # expires__gt=timezone.now(),
            ).all()

            # check past authorizations regarded the same scopes as the current one
            for token in tokens:
                if token.allow_scopes(scopes):
                    uri, headers, body, status = self.create_authorization_response(
                        request=self.request,
                        scopes=" ".join(scopes),
                        credentials=credentials,
                        allow=True)
                    return HttpResponseUriRedirect(
                        uri, application.get_allowed_schemes())

            # render an authorization prompt so the user can approve
            # the application's requested scopes
            return self.render_to_response(self.get_context_data(**kwargs))

        except OAuthToolkitError as error:
            return self.error_response(error, application)
Beispiel #48
0
 class Meta:
     model = get_application_model()
     fields = ('client_id', 'name', 'client_type', 'redirect_uris',
               'created', 'updated')
Beispiel #49
0
 def _get_client_data(client_index):
     app = get_application_model().objects.all()[client_index]
     return app.client_id, app.client_secret
Beispiel #50
0
 def get_form_class(self):
     return modelform_factory(get_application_model(),
                              fields=('name', 'redirect_uris',
                                      'client_type'))
Beispiel #51
0
    search_fields = [u'token', u'user__username', u'access_token__token']


@reregister(models.Grant)
class DOTGrantAdmin(ModelAdmin):
    """
    Custom Grant Admin
    """
    date_hierarchy = u'expires'
    list_display = [u'code', u'user', u'application', u'expires']
    list_filter = [u'application']
    raw_id_fields = [u'user']
    search_fields = [u'code', u'user__username']


@reregister(models.get_application_model())
class DOTApplicationAdmin(ModelAdmin):
    """
    Custom Application Admin
    """
    list_display = [u'name', u'user', u'client_type', u'authorization_grant_type', u'client_id']
    list_filter = [u'client_type', u'authorization_grant_type', u'skip_authorization']
    raw_id_fields = [u'user']
    search_fields = [u'name', u'user__username', u'client_id']


class ApplicationAccessAdmin(ModelAdmin):
    """
    ModelAdmin for ApplicationAccess
    """
    list_display = ['application', 'scopes', 'filters']
Beispiel #52
0
 def get_form_class(self):
     return forms.modelform_factory(get_application_model(),
                                    fields=("name", "redirect_uris"))
class IDTokenAdmin(admin.ModelAdmin):
    list_display = ("jti", "user", "application", "expires")
    raw_id_fields = ("user", )
    search_fields = ("token", ) + (("user__email", ) if has_email else ())
    list_filter = ("application", )


class RefreshTokenAdmin(admin.ModelAdmin):
    list_display = ("token", "user", "application")
    raw_id_fields = ("user", "access_token")
    search_fields = ("token", ) + (("user__email", ) if has_email else ())
    list_filter = ("application", )


application_model = get_application_model()
access_token_model = get_access_token_model()
grant_model = get_grant_model()
id_token_model = get_id_token_model()
refresh_token_model = get_refresh_token_model()

application_admin_class = get_application_admin_class()
access_token_admin_class = get_access_token_admin_class()
grant_admin_class = get_grant_admin_class()
id_token_admin_class = get_id_token_admin_class()
refresh_token_admin_class = get_refresh_token_admin_class()

admin.site.register(application_model, application_admin_class)
admin.site.register(access_token_model, access_token_admin_class)
admin.site.register(grant_model, grant_admin_class)
admin.site.register(id_token_model, id_token_admin_class)
Beispiel #54
0
 class Meta:
     model = get_application_model()
     fields = ('url', 'name', 'description', 'client_id', 'scope',
               'website')
     read_only_fields = ('url', 'client_id')
Beispiel #55
0
    def migrate_oauth_tokens(self):
        from oauth2_provider import models as oa2_models
        from django.contrib.auth import get_user_model

        app_model = oa2_models.get_application_model()
        at_model = oa2_models.get_access_token_model()
        rt_model = oa2_models.get_refresh_token_model()
        user_model = get_user_model()

        # Old database:
        # +---------------+--------------+------+-----+---------+----------------+
        # | Field         | Type         | Null | Key | Default | Extra          |
        # +---------------+--------------+------+-----+---------+----------------+
        # | id            | int(11)      | NO   | PRI | NULL    | auto_increment |
        # | client_id     | varchar(40)  | NO   | MUL | NULL    |                |
        # | user_id       | int(11)      | NO   | MUL | NULL    |                |
        # | token_type    | varchar(40)  | YES  |     | NULL    |                |
        # | access_token  | varchar(255) | YES  | UNI | NULL    |                |
        # | refresh_token | varchar(255) | YES  | UNI | NULL    |                |
        # | expires       | datetime     | YES  |     | NULL    |                |
        # | _scopes       | text         | YES  |     | NULL    |                |
        # | host_label    | varchar(255) | YES  |     | NULL    |                |
        # | subclient     | varchar(40)  | YES  |     | NULL    |                |
        # +---------------+--------------+------+-----+---------+----------------+

        migrated = 0

        # Get an in-memory maping from client ID to application.
        apps = {app.client_id: app for app in app_model.objects.all()}

        # Some optimisation to only fetch a user when it's different than the previous one.
        last_user = None
        skip_user_id = None

        # noinspection PyProtectedMember
        sql = (
            f"SELECT client_id, user_id, access_token, refresh_token, expires, "
            f"_scopes as scopes, host_label, subclient "
            f"FROM token "
            f"WHERE "
            f" expires > now() "
            f" and access_token  not in (select token from {at_model._meta.db_table}) "
            f" and refresh_token not in (select token from {rt_model._meta.db_table}) "
            f"ORDER BY user_id")

        for result in query(sql):

            # Some optimisation to only fetch a user when it's different than the previous one.
            if skip_user_id is not None:
                if result.user_id == skip_user_id:
                    continue
                # We've skipped that user, time to forget about it.
                skip_user_id = None

            if last_user is None or last_user.id != result.user_id:
                try:
                    user = user_model.objects.get(id=result.user_id)
                except user_model.DoesNotExist:
                    self.stdout.write(
                        self.style.WARNING(
                            f'User {result.user_id} does not exist, skipping tokens'
                        ))
                    skip_user_id = result.user_id
                    continue

                last_user = user
            else:
                user = last_user

            app = apps[result.client_id]

            at = at_model(
                user=user,
                token=result.access_token,
                application=app,
                expires=localise_datetime(result.expires),
                scope=result.scopes or '',
                host_label=result.host_label or '',
                subclient=result.subclient or '',
            )
            at.save()

            if result.refresh_token:
                rt = rt_model(
                    user=user,
                    token=result.refresh_token,
                    application=app,
                    access_token=at,
                )
                rt.save()

            migrated += 1

        self.stdout.write(
            self.style.SUCCESS('Migrated %d OAuth2 tokens' % migrated))
Beispiel #56
0
def get_auth_token(user, client="GeoServer"):
    Application = get_application_model()
    app = Application.objects.get(name=client)
    access_token = AccessToken.objects.filter(
        user=user, application=app).order_by('-expires').first()
    return access_token
Beispiel #57
0
    def post(self, request):
        serializer = RegistrationSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        app_model = get_application_model()
        if ApplicationInfo.objects.filter(
                website_url=serializer.data.get('client_uri')).exists():
            return Response({"error": "Client already registered"},
                            status=HTTP_400_BAD_REQUEST)
        # All domains in URIs must be HTTPS and match
        uris = set()
        schemes = set()

        def parse_uri(uri):
            parsed = urlparse(uri)
            uris.add(parsed.netloc)
            schemes.add(parsed.scheme)

        parse_uri(serializer.data.get('client_uri'))
        parse_uri(serializer.data.get('logo_uri'))
        parse_uri(serializer.data.get('tos_uri'))
        parse_uri(serializer.data.get('policy_uri'))
        for redirect in serializer.data.get('redirect_uris'):
            if app_model.objects.filter(redirect_uris__contains=redirect):
                return Response({"error": "Redirect URI already registered"},
                                status=HTTP_400_BAD_REQUEST)
            parse_uri(redirect)
        if len(uris) > 1:
            return Response({"error": "URIs do not match"},
                            status=HTTP_400_BAD_REQUEST)
        if len(schemes) > 1 or schemes.pop() != 'https':
            return Response({"error": "URI schemes must be HTTPS"},
                            status=HTTP_400_BAD_REQUEST)

        if serializer.data.get('scopes'):
            scopes = serializer.data.get('scopes').split(' ')
            for scope in scopes:
                if scope not in BADGE_CONNECT_SCOPES:
                    return Response({"error": "Invalid scope"},
                                    status=HTTP_400_BAD_REQUEST)
        else:
            # If no scopes provided, we assume they want all scopes
            scopes = BADGE_CONNECT_SCOPES

        if serializer.data.get(
                'token_endpoint_auth_method') != 'client_secret_basic':
            return Response({"error": "Invalid token authentication method"},
                            status=HTTP_400_BAD_REQUEST)

        if 'authorization_code' not in serializer.data.get('grant_types'):
            return Response({"error": "Missing authorization_code grant type"},
                            status=HTTP_400_BAD_REQUEST)

        for grant_type in serializer.data.get('grant_types'):
            if grant_type not in ['authorization_code', 'refresh_token']:
                return Response({"error": "Invalid grant types"},
                                status=HTTP_400_BAD_REQUEST)

        if serializer.data.get('response_types') != ['code']:
            return Response({"error": "Invalid response type"},
                            status=HTTP_400_BAD_REQUEST)

        app = app_model.objects.create()
        app_info = ApplicationInfo(application=app)

        app.name = serializer.data.get('client_name')
        app.redirect_uris = ' '.join(serializer.data.get('redirect_uris'))
        app.authorization_grant_type = app.GRANT_AUTHORIZATION_CODE
        app.save()

        app_info.website_url = serializer.data.get('client_uri')
        app_info.logo_uri = serializer.data.get('logo_uri')
        app_info.policy_uri = serializer.data.get('policy_uri')
        app_info.software_id = serializer.data.get('software_id')
        app_info.software_version = serializer.data.get('software_version')
        app_info.allowed_scopes = ' '.join(scopes)
        app_info.issue_refresh_token = 'refresh_token' in serializer.data.get(
            'grant_types')
        app_info.save()

        response = RegistrationResponseSerializer(instance=app_info)
        return Response(response.data, status=HTTP_201_CREATED)
Beispiel #58
0
 def has_permission(self, request, view):
     Application = get_application_model()
     return Application.objects.filter(user=request.user.id).exists()
Beispiel #59
0
from oauth2_provider.models import get_application_model, AccessToken
from oauth2_provider.tests.test_utils import TestCaseUtils

from .models import Task

from datetime import datetime

try:
    import urllib.parse as urllib
except ImportError:
    import urllib

import json

Application = get_application_model()


class TaskModelTest(TestCase):
    """ 
    Testeando el CRUD del modelo Task 
    """

    def setUp(self):
        self.user = User.objects.create_user('rulz', '*****@*****.**', '12345')
        self.user2 = User.objects.create_user('rulz2', '*****@*****.**', '12345')
        self.task = Task.objects.create(
            name='tarea', description='description tarea', owner=self.user
        )
        #assigned_to, name, description, done, created, modified
Beispiel #60
0
def do_logout(sender, user, request, **kwargs):
    """
    Take action on user logout. Cleanup user access_token and send logout
    request to GeoServer
    """
    if 'access_token' in request.session:
        try:
            Application = get_application_model()
            app = Application.objects.get(name="GeoServer")

            # Lets delete the old one
            try:
                old = AccessToken.objects.get(user=user, application=app)
            except:
                pass
            else:
                old.delete()
        except:
            pass

        # Do GeoServer Logout
        if 'access_token' in request.session:
            access_token = request.session['access_token']
        else:
            access_token = None

        if access_token:
            url = "%s%s?access_token=%s" % (
                settings.OGC_SERVER['default']['PUBLIC_LOCATION'],
                settings.OGC_SERVER['default']['LOGOUT_ENDPOINT'],
                access_token)
            header_params = {"Authorization": ("Bearer %s" % access_token)}
        else:
            url = "%s%s" % (settings.OGC_SERVER['default']['PUBLIC_LOCATION'],
                            settings.OGC_SERVER['default']['LOGOUT_ENDPOINT'])

        param = {}
        data = urllib.urlencode(param)

        cookies = None
        for cook in request.COOKIES:
            name = str(cook)
            value = request.COOKIES.get(name)
            if name == 'csrftoken':
                header_params['X-CSRFToken'] = value

            cook = "%s=%s" % (name, value)
            if not cookies:
                cookies = cook
            else:
                cookies = cookies + '; ' + cook

        if cookies:
            if 'JSESSIONID' in request.session and request.session[
                    'JSESSIONID']:
                cookies = cookies + '; JSESSIONID=' + request.session[
                    'JSESSIONID']
            header_params['Cookie'] = cookies

        gs_request = urllib2.Request(url, data, header_params)

        try:
            urllib2.urlopen(gs_request)
        except:
            tb = traceback.format_exc()
            if tb:
                logger.debug(tb)

        if 'access_token' in request.session:
            del request.session['access_token']

        request.session.modified = True