def pie_chart(items, width=440, height=190):
    return '//chart.googleapis.com/chart?cht=p3&chd=t:{0}&chs={1}x{2}&chl={3}'.format(
        quote(','.join([str(item[1]) for item in items])),
        width,
        height,
        quote('|'.join([str(item[0]) for item in items])),
    )
Example #2
0
def google_static_map(obj, width, height, zoom):
    """
    Generates a static google map for the event location.
    """
    if isinstance(obj, Event):
        location = quote(obj.location.mappable_location)
        marker = quote('{:.6},{:.6}'.format(obj.location.lat,
                                            obj.location.lon))
    elif isinstance(obj, EventLocation):
        location = quote(obj.mappable_location)
        marker = quote('{:.6},{:.6}'.format(obj.lat, obj.lon))
    else:
        return ''
    if settings.EVENT_HIDPI_STATIC_MAPS:
        scale = 2
    else:
        scale = 1
    key = settings.GOOGLE_API_KEY
    url = "https://maps.googleapis.com/maps/api/staticmap?size={width}x{height}&scale={scale}&format=png&markers={marker}&sensor=false&zoom={zoom}&key={key}".format(
        **locals()).encode('utf-8')
    url = sign_url(input_url=url,
                   secret=settings.GOOGLE_STATIC_MAPS_API_SECRET)

    return mark_safe(
        "<img src='{url}' width='{width}' height='{height}' />".format(
            **locals()))
Example #3
0
def google_interactive_map(event, width, height, zoom, map_type='roadmap'):
    """
    Generates an interactive google map for the event location.
    """
    location = quote(event.location.mappable_location)
    api_key = settings.EVENT_GOOGLE_MAPS_API_KEY
    center = marker = quote('{:.6},{:.6}'.format(event.location.lat, event.location.lon))
    return mark_safe('<iframe width="{width}" height="{height}" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q={location}&zoom={zoom}&center={center}&maptype={map_type}&key={api_key}" allowfullscreen></iframe>'.format(**locals()))
Example #4
0
def google_calendar_url(event):
    if not isinstance(event, Event):
        return ''
    title = quote(event.title)
    start_date = get_utc(event.start_datetime()).strftime("%Y%m%dT%H%M%SZ")
    end_date = get_utc(event.end_datetime()).strftime("%Y%m%dT%H%M%SZ")
    url = _get_current_domain() + event.get_absolute_url()
    location = quote(event.mappable_location)
    return "http://www.google.com/calendar/event?action=TEMPLATE&text={title}&dates={start_date}/{end_date}&sprop=website:{url}&location={location}&trp=true".format(**locals())
Example #5
0
def google_calendar_url(event):
    if not isinstance(event, Event):
        return ''
    title = quote(event.title)
    start_date = get_utc(event.start_datetime()).strftime("%Y%m%dT%H%M%SZ")
    end_date = get_utc(event.end_datetime()).strftime("%Y%m%dT%H%M%SZ")
    url = _get_current_domain() + event.get_absolute_url()
    location = quote(event.mappable_location)
    return "http://www.google.com/calendar/event?action=TEMPLATE&text={title}&dates={start_date}/{end_date}&sprop=website:{url}&location={location}&trp=true".format(
        **locals())
def google_interactive_map(event, width, height, zoom, map_type='roadmap'):
    """
    Generates an interactive google map for the event location.
    """
    location = quote(event.location.mappable_location)
    api_key = settings.EVENT_GOOGLE_MAPS_API_KEY
    center = marker = quote('{:.6},{:.6}'.format(event.location.lat,
                                                 event.location.lon))
    return mark_safe(
        '<iframe width="{width}" height="{height}" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q={location}&zoom={zoom}&center={center}&maptype={map_type}&key={api_key}" allowfullscreen></iframe>'
        .format(**locals()))
Example #7
0
def google_nav_url(obj):
    """
    Generates a link to get directions to an event or location with google maps.
    """
    if isinstance(obj, Event):
        location = quote(obj.location.mappable_location)
    elif isinstance(obj, EventLocation):
        location = quote(obj.mappable_location)
    else:
        return ''
    return "https://{}/maps?daddr={}".format(settings.EVENT_GOOGLE_MAPS_DOMAIN, location)
Example #8
0
def google_nav_url(obj):
    """
    Generates a link to get directions to an event or location with google maps.
    """
    if isinstance(obj, Event):
        location = quote(obj.location.mappable_location)
    elif isinstance(obj, EventLocation):
        location = quote(obj.mappable_location)
    else:
        return ''
    return "https://{}/maps?daddr={}".format(settings.EVENT_GOOGLE_MAPS_DOMAIN,
                                             location)
Example #9
0
def dashboard(request):
    try:
        user_id = request.session["user_id"]
    except KeyError:
        url = os.environ["SHIBBOLETH_ROOT"] + "/Login?target="
        param = request.build_absolute_uri(
            request.path) + "user/login.callback"
        param = quote(param)
        url = url + param
        return redirect(url)

    user = User.objects.get(id=user_id)

    user_meta = {
        "name": user.full_name,
        "cn": user.cn,
        "department": user.department,
        "intranet_groups": user.raw_intranet_groups,
        "apps": []
    }

    user_apps = App.objects.filter(user=user)

    for app in user_apps:
        user_meta["apps"].append({
            "name": app.name,
            "id": app.id,
            "token": app.api_token,
            "created": app.created,
            "updated": app.last_updated
        })

    initial_data = json.dumps(user_meta, cls=DjangoJSONEncoder)
    return render(request, 'dashboard.html', {'initial_data': initial_data})
def google_static_map(event, width, height, zoom):
    """
    Generates a static google map for the event location.
    """
    location = quote(event.location.mappable_location)

    return mark_safe('<iframe width="100%%" height="450" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?q=%s&key=%s" allowfullscreen></iframe>' % (location, settings.GOOGLE_MAPS_API_KEY))
Example #11
0
def facebook_login_widget(context, perms=None, login_button_text='Login with Facebook'):
    context = copy(context)
    login_redirect_uri = 'http://%s%s' % (
        Site.objects.get_current().domain, 
        reverse_lazy('facebook_login_callback')
    )
    csrf_token = unicode(context['csrf_token'])
    context['request'].session['facebook_state'] = csrf_token
    
    if perms:
        perms = ['email'] + perms.split(',')
    else:
        perms = ['email']
    
    context.update({
        'auth_url': quote(facebook.auth_url(
            settings.FACEBOOK_APP_ID, 
            login_redirect_uri,
            perms,
            csrf_token
        )),
        'login_button_text': login_button_text
    })
    
    return context
Example #12
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:
            assert isinstance(m, LoginMethod)
            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

            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)
Example #13
0
def google_static_map(obj, width, height, zoom):
    """
    Generates a static google map for the event location.
    """
    if isinstance(obj, Event):
        location = quote(obj.location.mappable_location)
        marker = quote('{:.6},{:.6}'.format(obj.location.lat, obj.location.lon))
    elif isinstance(obj, EventLocation):
        location = quote(obj.mappable_location)
        marker = quote('{:.6},{:.6}'.format(obj.lat, obj.lon))
    else:
        return ''
    if settings.EVENT_HIDPI_STATIC_MAPS:
        scale = 2
    else:
        scale = 1
    return mark_safe("<img src='http://maps.googleapis.com/maps/api/staticmap?size={width}x{height}&scale={scale}&format=png&markers={marker}&sensor=false&zoom={zoom}' width='{width}' height='{height}' />".format(**locals()))
Example #14
0
def google_nav_url(event):
    """
    Generates a link to get directions to an event with google maps.
    """
    if not isinstance(event, Event):
        return ''
    location = quote(event.location.mappable_location)
    return "https://{}/maps?daddr={}".format(settings.EVENT_GOOGLE_MAPS_DOMAIN, location)
Example #15
0
def dashboard(request):
    try:
        user_id = request.session["user_id"]
    except KeyError:
        url = os.environ["SHIBBOLETH_ROOT"] + "/Login?target="
        param = request.build_absolute_uri(
            request.path) + "user/login.callback"
        param = quote(param)
        url = url + param
        return redirect(url)

    user = User.objects.get(id=user_id)

    if not user.agreement:
        if request.method != "POST":
            return render(request, "agreement.html",
                          {'fair_use': FAIR_USE_POLICY})

        try:
            agreement = strtobool(request.POST["agreement"])
        except (KeyError, ValueError):
            return render(
                request, "agreement.html", {
                    'fair_use': FAIR_USE_POLICY,
                    "error": "You must agree to the fair use policy"
                })

        if agreement:
            user.agreement = True
            user.save()
        else:
            return render(
                request, "agreement.html", {
                    'fair_use': FAIR_USE_POLICY,
                    "error": "You must agree to the fair use policy"
                })

    user_meta = {
        "name": user.full_name,
        "cn": user.cn,
        "department": user.department,
        "intranet_groups": user.raw_intranet_groups,
        "apps": []
    }

    user_apps = App.objects.filter(user=user)

    for app in user_apps:
        user_meta["apps"].append({
            "name": app.name,
            "id": app.id,
            "token": app.api_token,
            "created": app.created,
            "updated": app.last_updated
        })

    initial_data = json.dumps(user_meta, cls=DjangoJSONEncoder)
    return render(request, 'dashboard.html', {'initial_data': initial_data})
Example #16
0
def google_plus_login_widget(context, login_button_text='Login with Google'):
    from tunobase.social_media.google_plus import utils
    context = copy(context)
    context.update({
        'auth_url': quote(utils.FLOW.step1_get_authorize_url()),
        'login_button_text': login_button_text
    })
    
    return context
Example #17
0
def google_nav_url(event):
    """
    Generates a link to get directions to an event with google maps.
    """
    if not isinstance(event, Event):
        return ''
    location = quote(event.location.mappable_location)
    return "https://{}/maps?daddr={}".format(settings.EVENT_GOOGLE_MAPS_DOMAIN,
                                             location)
Example #18
0
def google_calendar_url(event):
    """
    Generates a link to add the event to your google calendar.
    """
    if not isinstance(event, Event):
        return ''
    title = quote(event.title)
    start_date = _get_utc(event.start).strftime("%Y%m%dT%H%M%SZ")
    if event.end:
        end_date = _get_utc(event.end).strftime("%Y%m%dT%H%M%SZ")
    else:
        end_date = start_date
    url = Site.objects.get(id=current_site_id()).domain + event.get_absolute_url()
    if event.location:
        location = quote(event.location.mappable_location)
    else:
        location = None
    return "http://www.google.com/calendar/event?action=TEMPLATE&text={title}&dates={start_date}/{end_date}&sprop=website:{url}&location={location}&trp=true".format(**locals())
Example #19
0
def google_static_map(event, width, height, zoom):
    """
    Generates a static google map for the event location.
    """
    marker = quote('{:.6},{:.6}'.format(event.location.lat, event.location.lon))
    if settings.EVENT_HIDPI_STATIC_MAPS:
        scale = 2
    else:
        scale = 1
    return "<img src='http://maps.googleapis.com/maps/api/staticmap?size={width}x{height}&scale={scale}&format=png&markers={marker}&sensor=false&zoom={zoom}' width='{width}' height='{height}' />".format(**locals())
Example #20
0
def authorise(request):
    client_id = request.GET.get("client_id", None)
    state = request.GET.get("state", None)
    if not (client_id and state):
        response = PrettyJsonResponse({
            "ok": False,
            "error": "incorrect parameters supplied"
        })
        response.status_code = 400
        return response

    try:
        # We only allow the process to happen if the app exists and has not
        # been flagged as deleted
        app = App.objects.filter(client_id=client_id, deleted=False)[0]
    except IndexError:
        response = PrettyJsonResponse({
            "ok":
            False,
            "error":
            "App does not exist for client id"
        })
        response.status_code = 400
        return response

    if app.callback_url is None or app.callback_url.strip() == "":
        response = PrettyJsonResponse({
            "ok":
            False,
            "error": ("This app does not have a callback URL set. "
                      "If you are the developer of this app, "
                      "please ensure you have set a valid callback "
                      "URL for your application in the Dashboard. "
                      "If you are a user, please contact the app's "
                      "developer to rectify this.")
        })
        response.status_code = 400
        return response

    # Sign the app and state pair before heading to Shibboleth to help protect
    # against CSRF and XSS attacks
    signer = TimestampSigner()
    data = app.client_id + state
    signed_data = signer.sign(data)

    # Build Shibboleth callback URL
    url = os.environ.get("SHIBBOLETH_ROOT") + "/Login?target="
    target = request.build_absolute_uri(
        "/oauth/shibcallback?appdata={}".format(signed_data))
    target = quote(target)
    url += target

    # Send the user to Shibboleth to log in
    return redirect(url)
Example #21
0
    def dispatch(self, request, *args, **kwargs):
        """
        Most views in a CMS require a login, so this is the default setup.

        If a login is not required then the requires_login property
        can be set to False to disable this.
        """
        if (not request.user.is_authenticated()) and self.requires_login:
            return redirect('%s?next=%s' % (resolve_url(settings.LOGIN_URL),
                                            quote(request.get_full_path())))
        return super(View, self).dispatch(request, *args, **kwargs)
Example #22
0
 def render(self, context):
     event = self.event.resolve(context)
     width = self.width
     height = self.height
     zoom = self.zoom
     marker = quote('{:.6},{:.6}'.format(event.event_location.lat, event.event_location.lon))
     if settings.MZEVENTS_HIDPI_STATIC_MAPS:
         scale = 2
     else:
         scale = 1
     return "<img src='http://maps.googleapis.com/maps/api/staticmap?size={width}x{height}&scale={scale}&format=png&markers={marker}&sensor=false&zoom={zoom}' width='{width}' height='{height}' />".format(**locals())
Example #23
0
def google_calendar_url(event):
    """
    Generates a link to add the event to your google calendar.
    """
    if not isinstance(event, Event):
        return ''
    title = quote(event.title)
    start_date = _get_utc(event.start).strftime("%Y%m%dT%H%M%SZ")
    if event.end:
        end_date = _get_utc(event.end).strftime("%Y%m%dT%H%M%SZ")
    else:
        end_date = start_date
    url = Site.objects.get(
        id=current_site_id()).domain + event.get_absolute_url()
    if event.location:
        location = quote(event.location.mappable_location)
    else:
        location = None
    return "http://www.google.com/calendar/event?action=TEMPLATE&text={title}&dates={start_date}/{end_date}&sprop=website:{url}&location={location}&trp=true".format(
        **locals())
Example #24
0
def cutretelegram_enviar_mensaje(msg, chatid):
    if not chatid or not msg:
        return
    api_telegram = "https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}"
    url = api_telegram.format(settings.TELEGRAM_TOKEN, chatid, quote(msg))
    # logging.info(url)
    try:
        urllib.request.urlopen(url, timeout=2)
        logging.debug("Enviado por telegram: '{}'".format(msg))
    except Exception as e:
        logging.error(e)
Example #25
0
def set_item_learning_objectives(data, form):
    # over-writes current ID list
    id_list = []
    if not isinstance(data['learningObjectiveIds'], list):
        data['learningObjectiveIds'] = [data['learningObjectiveIds']]
    for _id in data['learningObjectiveIds']:
        if '@' in _id:
            id_list.append(Id(quote(_id)))
        else:
            id_list.append(Id(_id))
    form.set_learning_objectives(id_list)
    return form
Example #26
0
def google_static_map(event, width, height, zoom):
    """
    Generates a static google map for the event location.
    """
    marker = quote('{:.6},{:.6}'.format(event.location.lat,
                                        event.location.lon))
    if settings.EVENT_HIDPI_STATIC_MAPS:
        scale = 2
    else:
        scale = 1
    return "<img src='http://maps.googleapis.com/maps/api/staticmap?size={width}x{height}&scale={scale}&format=png&markers={marker}&sensor=false&zoom={zoom}' width='{width}' height='{height}' />".format(
        **locals())
Example #27
0
def get_thumbor_thumbnail_url(image, **kwargs):
    storage = image.storage
    thumbor_server = settings.THUMBOR_SERVER_EXTERNAL
    url = quote(image.url)
    if hasattr(storage, "key"):
        try:
            url = storage.key(image.name)
        except NotImplementedError:
            pass
        else:
            thumbor_server = settings.THUMBOR_SERVER
    return generate_url(url, thumbor_server=thumbor_server, **kwargs)
Example #28
0
def clean_id(_id):
    """
    Django seems to un-url-safe the IDs passed in to the rest framework views,
    so we need to url-safe them, then convert them to OSID IDs
    """
    if isinstance(_id, basestring):
        if _id.find('@') >= 0:
            return Id(quote(_id))
        else:
            return Id(_id)
    else:
        return _id
Example #29
0
 def render(self, context):
     event = self.event.resolve(context)
     width = self.width
     height = self.height
     zoom = self.zoom
     marker = quote('{:.6},{:.6}'.format(event.lat, event.lon))
     if settings.MZEVENTS_HIDPI_STATIC_MAPS:
         scale = 2
     else:
         scale = 1
     return "<img src='http://maps.googleapis.com/maps/api/staticmap?size={width}x{height}&scale={scale}&format=png&markers={marker}&sensor=false&zoom={zoom}' width='{width}' height='{height}' />".format(
         **locals())
Example #30
0
 def dispatch(self, request, *args, **kwargs):
     """
     In a CMS most views tipically require a login, so this is the default
     setup, if a login is not required then the requires_login property
     can be set to False to disable this.
     """
     if (not request.user.is_authenticated()) and self.requires_login:
         return redirect('%s?next=%s' % (resolve_url(settings.LOGIN_URL), 
                                         quote(request.get_full_path())))
     if not self.has_perm(request.user):
         raise PermissionDenied
     return super(View, self).dispatch(request, *args, **kwargs)
Example #31
0
    def get_response(self, response, context, *args, **kwargs):
        file_type = self.request.GET.get('export_type', 'csv')
        response = HttpResponse(
            content_type="%s; charset=UTF-8" % self.export_mimes[file_type])

        file_name = self.opts.verbose_name.replace(' ', '_')
        if isinstance(file_name, unicode):
            # QP encode for unicode
            file_name = quote(file_name.encode('utf-8'))

        response['Content-Disposition'] = 'attachment; filename="%s.%s"' % (file_name, file_type)

        response.write(getattr(self, 'get_%s_export' % file_type)(context))
        return response
Example #32
0
    def test_url_encode(self):
        pp = "QwToU/09ys0B8SVKmBnv5OKTax2s1+Mlxj0OywiF77U="
        encoded = quote(pp)
        print("\n")
        print(encoded)
        self.assertEquals("QwToU/09ys0B8SVKmBnv5OKTax2s1%2BMlxj0OywiF77U%3D",
                          encoded)

        decoded = unquote(encoded)
        print(decoded)
        self.assertEquals(pp, decoded)

        decoded = unquote(encoded)
        print(decoded)
        self.assertEquals(pp, decoded)
Example #33
0
def my_apps(request):
    # Check whether the user is logged in
    try:
        user_id = request.session["user_id"]
    except KeyError:
        # Build Shibboleth callback URL
        url = os.environ["SHIBBOLETH_ROOT"] + "/Login?target="
        param = urllib.parse.urljoin(request.build_absolute_uri(request.path),
                                     "/shibcallback")
        param = quote(param)
        url = url + param

        return redirect(url)

    user = User.objects.get(id=user_id)

    tokens = OAuthToken.objects.filter(user=user)

    authorised_apps = []
    scopes = Scopes()

    for token in tokens:
        authorised_apps.append({
            "id": token.id,
            "active": token.active,
            "app": {
                "id": token.app.id,
                "creator": {
                    "name": token.app.user.full_name,
                    "email": token.app.user.email
                },
                "client_id": token.app.client_id,
                "name": token.app.name,
                "scopes": scopes.scope_dict_all(token.scope.scope_number)
            }
        })

    initial_data_dict = {
        "status": "ONLINE",
        "fullname": user.full_name,
        "user_id": user.id,
        "department": user.department,
        "scopes": scopes.get_scope_map(),
        "apps": authorised_apps
    }

    initial_data = json.dumps(initial_data_dict, cls=DjangoJSONEncoder)
    return render(request, 'appsettings.html', {'initial_data': initial_data})
Example #34
0
def authorise(request):
    client_id = request.GET.get("client_id", None)
    state = request.GET.get("state", None)
    if not (client_id and state):
        response = PrettyJsonResponse({
            "ok": False,
            "error": "incorrect parameters supplied"
        })
        response.status_code = 400
        return response

    try:
        # We only allow the process to happen if the app exists and has not
        # been flagged as deleted
        app = App.objects.filter(client_id=client_id, deleted=False)[0]
    except IndexError:
        response = PrettyJsonResponse({
            "ok": False,
            "error": "App does not exist for client id"
        })
        response.status_code = 400
        return response

    if app.callback_url is None:
        response = PrettyJsonResponse({
            "ok": False,
            "error": "No callback URL set for this app."
        })
        response.status_code = 400
        return response

    # Sign the app and state pair before heading to Shibboleth to help protect
    # against CSRF and XSS attacks
    signer = TimestampSigner()
    data = app.client_id + state
    signed_data = signer.sign(data)

    # Build Shibboleth callback URL
    url = os.environ.get("SHIBBOLETH_ROOT") + "/Login?target="
    target = request.build_absolute_uri(
        "/oauth/shibcallback?appdata={}".format(signed_data)
    )
    target = quote(target)
    url += target

    # Send the user to Shibboleth to log in
    return redirect(url)
def page_not_found(request, exception):
    template_name = 'errors/404.html'
    template = loader.get_template(template_name)
    exception_repr = exception.__class__.__name__
    try:
        message = exception.args[0]
    except (AttributeError, IndexError):
        pass
    else:
        if isinstance(message, str):
            exception_repr = message
    context = {
        'request_path': quote(request.path),
        'exception': exception_repr,
        'user': request.user,
    }
    return HttpResponseNotFound(template.render(context))
Example #36
0
    def dispatch(self, request, *args, **kwargs):
        """
        Most views in a CMS require a login, so this is the default setup.

        If a login is not required then the requires_login property
        can be set to False to disable this.
        """
        if self.requires_login:
            if settings.LOGIN_URL is None or settings.LOGOUT_URL is None:
                raise ImproperlyConfigured(
                    'LOGIN_URL and LOGOUT_URL '
                    'has to be defined if requires_login is True')

            if not request.user.is_authenticated():
                return redirect('%s?next=%s' % (resolve_url(
                    settings.LOGIN_URL), quote(request.get_full_path())))

        return super(View, self).dispatch(request, *args, **kwargs)
Example #37
0
def build_safe_uri(request):
    """
    because Django's request.build_absolute_uri() does not url-escape the
    IDs, it leaves in : and @. Which means that the URIs are not compatible
    with the data stored in the Mongo impl. For example, deleting
    an assessment bank should confirm that there are no assessments, first.
    But the bankId attribute of assessments is stored url-escaped.
    So none will be found, if we rely on the non-url-escaped URIs
    generated by Django.
    """
    uri = ''
    if request.is_secure():
        uri += 'https://'
    else:
        uri += 'http://'
    uri += request.get_host()
    uri += quote(request.get_full_path())

    return append_slash(uri)
Example #38
0
def config_osid_object_querier(querier, params):
    for param, value in params.iteritems():
        try:
            method_name = 'match_{0}'.format(underscore(param))
            if hasattr(querier, method_name):
                if param in ['displayName', 'description']:
                    getattr(querier, method_name)(str(value),
                                                  WORDIGNORECASE_STRING_MATCH_TYPE,
                                                  True)
                elif param in ['learningObjectiveId', 'genusType']:
                    if '@' in value:
                        value = quote(value)
                    getattr(querier, method_name)(str(value),
                                                  True)
                else:
                    getattr(querier, method_name)(float(value),
                                                  True)
        except AttributeError:
            pass
    return querier
Example #39
0
	def render(self, context):
		event = self.event.resolve(context)
		width = self.width
		height = self.height
		zoom = self.zoom
		marker = quote('{:.6},{:.6}'.format(event.lat, event.lon))
                maploc = event.mappable_location
		if settings.MZEVENTS_HIDPI_STATIC_MAPS:
			scale = 2
		else:
			scale = 1
                if len(maploc) > 0:
                        return ("<a href='http://maps.google.com/maps?q={maploc}' "
                                "target='_blank'>"
                                "<img src='http://maps.googleapis.com/maps/api/staticmap?"
                                "size={width}x{height}&scale={scale}&format=png&markers={marker}"
                                "&sensor=false&zoom={zoom}' width='{width}' "
                                "height='{height}' /></a><br/>"
                                "<a href='https://maps.google.com/maps?saddr=current+location"
                                "&daddr={maploc}'>Get Directions</a>").format(**locals())
                return ("<img src='http://maps.googleapis.com/maps/api/staticmap?"
                        "size={width}x{height}&scale={scale}&format=png&markers={marker}"
                        "&sensor=false&zoom={zoom}' width='{width}' "
                        "height='{height}' />").format(**locals())
Example #40
0
 def get_redirect_uri(self, request, exception):
     strategy = getattr(request, 'social_strategy', None)
     if strategy.session.get('next') is None:
         return super().get_redirect_uri(request, exception)
     url = '/login/?next=' + quote(strategy.session.get('next'))
     return url
Example #41
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:
            assert isinstance(m, LoginMethod)
            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)
Example #42
0
def google_nav_url(event):
	if not isinstance(event, Event):
		return ''
	location = quote(event.mappable_location)
	return "https://{gmd}/maps?daddr={loc}".format(gmd=settings.MZEVENTS_GOOGLE_MAPS_DOMAIN, loc=location)
Example #43
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)
Example #44
0
def google_nav_url(event):
        location = quote(event.mappable_location)
        return "https://{}/maps?daddr={}".format(settings.GEOCODERS_GOOGLE_MAPS_DOMAIN, location)
Example #45
0
def google_nav_url(event):
    if not isinstance(event, Event):
        return ''
    location = quote(event.event_location.mappable_location)
    return "https://{}/maps?daddr={}".format(settings.MZEVENTS_GOOGLE_MAPS_DOMAIN.decode('utf-8'), location)
Example #46
0
 def get_redirect_uri(self, request, exception):
     strategy = getattr(request, 'social_strategy', None)
     if strategy.session.get('next') is None:
         return super().get_redirect_uri(request, exception)
     url = '/login/?next=' + quote(strategy.session.get('next'))
     return url
Example #47
0
def google_nav_url(event):
    if not isinstance(event, Event):
        return ''
    location = quote(event.mappable_location)
    return "https://{}/maps?daddr={}".format(
        settings.MZEVENTS_GOOGLE_MAPS_DOMAIN, location)
Example #48
0
 def _canviEstat(self, client, estatInicial):
     #type: () => HttpResponse
     url = self.urlBase + 'presenciaSetmanal/modificaEstatControlAssistencia/{2}/{0}/{1}'.format(
         self.alumne.pk, self.impartirDilluns.pk, quote(estatInicial))
     #print ("debug:::", url)
     return client.get(url)