示例#1
0
    def process_request(self, request):
        domain = request.get_host().lower().split(":")[0]
        status = self.lookup_site(request, domain)

        # Site found
        if status:
            return

        # If in domain-test mode
        if settings.SITE_DOMAIN_TEST_SUFFIX is not None:
            suffix = settings.SITE_DOMAIN_TEST_SUFFIX
            test_domain = domain.replace(suffix, '')
            test_domain = test_domain.replace('--', '.')
            status = self.lookup_site(request, test_domain)

            # Site found
            if status:
                return

        # Unknown host name, redirect to the main site
        central_domain = Site.get_central().domain
        if settings.SITE_DOMAIN_TEST_SUFFIX is not None:
            central_domain = "%s%s" % (
                central_domain.replace('.', '--'),
                settings.SITE_DOMAIN_TEST_SUFFIX,
            )
        return redirect('//%s/' % central_domain)
示例#2
0
def logout(request):
    """Log out from this site and the central site"""
    if request.site.is_central():
        # Central site
        if 'sso' not in request.GET:
            # Simply logging out from the central site - no SSO action required
            log_user_out(request)
            return redirect('cms:page')
        else:
            # This is an SSO logout request from a non-central site; log out here first and send them back
            log_user_out(request)
            return redirect(request.GET.get('next', reverse('cms:page')))
    else:
        # Non-central site
        if 'sso' not in request.GET:
            # Logging out of a non-central site - send a logout request to the central site first, then return here.
            # Add 'sso' parameter to the central site logout request to signal that this is an SSO logout.
            # Also add 'sso' parameter in the return address to signal that SSO is complete.
            return_address = 'https://%s%s?sso' % (request.site.domain, reverse('user:login.logout'))
            return redirect('https://%s%s?sso&next=%s' % (
                Site.get_central().domain,
                reverse('user:login.logout'),
                urlquote(return_address),
            ))
        else:
            # Single signout is completed; now log out here
            log_user_out(request)
            return redirect('cms:page')
示例#3
0
def sso_login_url(site, user, next):
    """Returns the URL for SSO login on the central site, given a local path for
    the return URL on the local site."""
    return_address = 'https://%s%s' % (site.domain, next)
    hmac_b64 = sso_hmac(user)
    return 'https://%s%s?next=%s&user_id=%s&hmac=%s' % (
        Site.get_central().domain,
        reverse('user:login.single_signon_login'),
        urlquote(return_address),
        urlquote(str(user.id)),
        urlquote(hmac_b64),
    )
示例#4
0
    def process_request(self, request):
        try:
            domain = request.get_host().lower().split(":")[0]
            request.site = cache.get('site.domain.%s' % domain)
            if request.site is None:
                request.site = Site.objects.get(domain=domain)
                cache.set('site.domain.%s' % domain, request.site, 60 * 60 * 24)

            request.urlconf = request.site.urlconf()
            urlresolvers.set_urlconf(request.site.urlconf())
        except Site.DoesNotExist:
            # Unknown host name, redirect to the main site.
            # Rendering 404 in the main site's layout would probably also make sense, but don't do that for now since
            # all links will be relative and hence keep the incorrect host name.
            return redirect('https://%s/' % Site.get_central().domain)
示例#5
0
    def render(self, context):
        try:
            return self.urlnode.render(context)
        except NoReverseMatch as e:
            if urlresolvers.get_urlconf() == settings.URLCONF_CENTRAL:
                raise

            try:
                # Try to resolve the same URL on the central site
                urlresolvers.set_urlconf(settings.URLCONF_CENTRAL)
                resolved_url = self.urlnode.render(context)

                # Found a central match; reset the urlconf and return an absolute URL
                urlresolvers.set_urlconf(settings.URLCONF_LOCAL)
                return "https://%s%s" % (Site.get_central().domain, resolved_url)
            except NoReverseMatch:
                # It doesn't resolve on the central site either; reset the urlconf and raise the original exception
                urlresolvers.set_urlconf(settings.URLCONF_LOCAL)
                raise e
示例#6
0
def edit(request, forening_id):
    current_forening = Forening.objects.filter(
        id=forening_id,
    ).prefetch_related(
        # We need just one level of parents
        'parents',

        # Get all children and their children
        'children',
        'children__children',

        # Get the parents of all those children
        'children__parents',
        'children__children__parents',
    ).get()

    if current_forening not in request.user.all_foreninger():
        raise PermissionDenied

    # The parent choices are tricky to define in the forms API, so do it here.
    # Note that we're intentionally letting users choose parents among only
    # those they have permission to.
    all_sorted = request.user.all_foreninger_sorted()
    parents_choices = {
        'forening': all_sorted['forening'],
        'turlag': all_sorted['turlag'],
    }

    # If the parent of the current forening isn't in the user's permissions, we
    # still need to include that one as an available parent so that they're
    # able to make changes.
    if current_forening.type != 'sentral':
        for current_parent in current_forening.get_main_foreninger():
            if (current_parent not in parents_choices['forening'] and
                    current_parent not in parents_choices['turlag']):
                parents_choices[current_parent.type].append(current_parent)

    zipcode = current_forening.zipcode
    form_zipcode_area = zipcode.area if zipcode is not None else ''

    form = EditForeningForm(request.user, initial={
        'forening': current_forening.id,
        'focus_id': current_forening.focus_id,
        'parents': current_forening.parents.all(),
        'name': current_forening.name,
        'type': current_forening.type,
        'group_type': current_forening.group_type,
        'description': current_forening.description,
        'turbasen_object_id': current_forening.turbasen_object_id,
        'post_address': current_forening.post_address,
        'visit_address': current_forening.visit_address,
        'zipcode': zipcode.zipcode if zipcode is not None else '',
        'counties': current_forening.counties.all(),
        'choose_contact': 'person' if current_forening.contact_person != '' else 'forening',
        'contact_person': current_forening.contact_person,
        'phone': current_forening.phone,
        'email': current_forening.email,
        'organization_no': current_forening.organization_no,
        'gmap_url': current_forening.gmap_url,
        'facebook_url': current_forening.facebook_url,
        'homepage_url': current_forening.homepage_url,
        'offers_family_membership': current_forening.offers_family_membership,
        'aktivitet_signup_terms_url': current_forening.aktivitet_signup_terms_url,
        'handles_child_payments': current_forening.handles_child_payments,
        'accounting_software': current_forening.accounting_software,
        'accounting_aktivitet_department': current_forening.accounting_aktivitet_department,
        'accounting_aktivitet_debit_account': current_forening.accounting_aktivitet_debit_account,
        'accounting_aktivitet_debit_fee_account': current_forening.accounting_aktivitet_debit_fee_account,
        'accounting_aktivitet_credit_account': current_forening.accounting_aktivitet_credit_account,
    })

    context = {
        'current_forening': current_forening,
        'parents_choices': parents_choices,
        'form': form,
        'form_zipcode_area': form_zipcode_area,
        'admin_user_search_char_length': settings.ADMIN_USER_SEARCH_CHAR_LENGTH,
    }

    # Give URLPicker the homepage site for the current forening. If they don't
    # have one, just use the central site
    relevant_site = current_forening.get_homepage_site() or Site.get_central()
    context.update(url_picker_context(relevant_site))

    if request.method == 'GET':
        return render(request, 'central/admin/foreninger/edit.html', context)

    elif request.method == 'POST':
        form = EditForeningForm(request.user, request.POST)
        if form.is_valid():
            forening = form.cleaned_data['forening']
            forening.parents = form.cleaned_data['parents']
            forening.focus_id = form.cleaned_data['focus_id']
            forening.name = form.cleaned_data['name']
            forening.type = form.cleaned_data['type']
            if forening.type == 'turgruppe':
                forening.group_type = form.cleaned_data['group_type']
            else:
                forening.group_type = ''
            forening.description = form.cleaned_data['description']
            forening.post_address = form.cleaned_data['post_address']
            forening.visit_address = form.cleaned_data['visit_address']
            forening.zipcode = form.cleaned_data['zipcode']
            forening.counties = form.cleaned_data['counties']

            if form.cleaned_data['choose_contact'] == 'person':
                forening.contact_person = form.cleaned_data['contact_person']
            else:
                forening.contact_person = ''

            forening.phone = form.cleaned_data['phone']
            forening.email = form.cleaned_data['email']

            forening.organization_no = form.cleaned_data['organization_no']
            forening.gmap_url = form.cleaned_data['gmap_url']
            forening.facebook_url = form.cleaned_data['facebook_url']
            forening.homepage_url = form.cleaned_data['homepage_url']
            forening.offers_family_membership = form.cleaned_data['offers_family_membership']
            forening.aktivitet_signup_terms_url = form.cleaned_data['aktivitet_signup_terms_url']

            forening.handles_child_payments = form.cleaned_data['handles_child_payments']
            forening.stripe_forening = form.cleaned_data['stripe_forening']
            forening.accounting_software = form.cleaned_data['accounting_software']
            forening.accounting_aktivitet_department = form.cleaned_data['accounting_aktivitet_department']
            forening.accounting_aktivitet_debit_account = form.cleaned_data['accounting_aktivitet_debit_account']
            forening.accounting_aktivitet_debit_fee_account = form.cleaned_data['accounting_aktivitet_debit_fee_account']
            forening.accounting_aktivitet_credit_account = form.cleaned_data['accounting_aktivitet_credit_account']

            forening.save()
            messages.info(request, 'forening_save_success')
            cache.delete('foreninger.all.sorted_by_name')
            cache.delete('foreninger.all.sorted_by_type')
            cache.delete('foreninger.rendered_select')
            cache.delete('forening.%s' % forening.id)
            cache.delete('forening.main_foreninger.%s' % forening.id)
            return redirect('admin:foreninger.edit', current_forening.id)
        else:
            context.update({'form': form})
            return render(
                request,
                'central/admin/foreninger/edit.html',
                context)

    else:
        return redirect('admin:foreninger.edit', current_forening.id)
示例#7
0
def create(request, forening_id):
    current_forening = Forening.objects.get(id=forening_id)

    if current_forening not in request.user.all_foreninger():
        raise PermissionDenied

    # The parent choices are tricky to define in the forms API, so do it here.
    # Note that we're intentionally letting users choose parents among only
    # those they have permission to.
    all_sorted = request.user.all_foreninger_sorted()
    parents_choices = {
        'forening': all_sorted['forening'],
        'turlag': all_sorted['turlag'],
    }

    # If the parent of the current forening isn't in the user's permissions, we
    # still need to include that one as an available parent so that they're
    # able to make changes.
    if current_forening.type != 'sentral':
        for current_parent in current_forening.get_main_foreninger():
            if (current_parent not in parents_choices['forening'] and
                    current_parent not in parents_choices['turlag']):
                parents_choices[current_parent.type].append(current_parent)

    form = CreateForeningForm(request.user, initial={
        'zipcode': '',
    })

    context = {
        'current_forening': current_forening,
        'parents_choices': parents_choices,
        'admin_user_search_char_length': settings.ADMIN_USER_SEARCH_CHAR_LENGTH,
        'form': form,
    }

    # Give URLPicker the homepage site for the current forening. If they don't
    # have one, just use the central site
    relevant_site = current_forening.get_homepage_site() or Site.get_central()
    context.update(url_picker_context(relevant_site))

    if request.method == 'GET':
        return render(request, 'central/admin/foreninger/create.html', context)

    elif request.method == 'POST':

        form = CreateForeningForm(request.user, request.POST)
        if form.is_valid():
            forening = Forening()
            forening.name = form.cleaned_data['name']
            forening.type = form.cleaned_data['type']
            if forening.type == 'turgruppe':
                forening.group_type = form.cleaned_data['group_type']
            else:
                forening.group_type = ''

            forening.save()

            # Set M2M-fields after the initial db-save
            forening.parents = form.cleaned_data['parents']

            # Ensure the Turbasen object is re-saved with applicable
            # M2M-relations
            forening.save_turbasen_object()

            # Add the current user as admin on the new forening
            request.user.add_perm(
                'sherpa/association/user',
                association_id=forening.id,
                created_by=request.user
            )
            request.user.add_perm(
                'sherpa/association/admin',
                association_id=forening.id,
                created_by=request.user
            )
            cache.clear()
            return redirect('admin:foreninger.edit', forening.id)
        else:
            context.update({'form': form})
            return render(
                request,
                'central/admin/foreninger/create.html',
                context)

    else:
        return redirect('admin:foreninger.create', current_forening.id)
def main_site(request):
    return {"main_site": Site.get_central()}
示例#9
0
def login(request):
    if 'authenticated_users' in request.session:
        del request.session['authenticated_users']

    context = {
        'user_password_length': settings.USER_PASSWORD_LENGTH,
        'memberid_lookups_limit': settings.MEMBERID_LOOKUPS_LIMIT,
        'countries': FocusCountry.get_sorted(),
    }

    if request.method == 'GET':
        # If the user is already authenticated, send them straight forwards
        if request.user.is_authenticated():
            return redirect(request.GET.get('next', reverse('user:home')))

        # If logging in on a non-central site, first send the user to the
        # central site to try automatic login. Except if 'sso_checked' is set in
        # session, in which case they've already tried and failed.
        if not request.site.is_central() \
                and 'sso_checked' not in request.session:
            return_address = 'https://%s%s?next=%s' % (
                request.site.domain,
                reverse('user:login.single_signon_return'),
                request.GET.get('next', reverse('user:home')),
            )
            return redirect('https://%s%s?next=%s' % (
                Site.get_central().domain,
                reverse('user:login.single_signon_check'),
                urlquote(return_address),
            ))

        if 'registreringsnokkel' in request.GET:
            try:
                user = User.get_users(include_pending=True).get(
                    pending_registration_key=request.GET['registreringsnokkel']
                )
                context['prefilled_user'] = user
            except User.DoesNotExist:
                pass

        if 'next' in request.GET:
            context['next'] = urlquote(request.GET['next'])
        if request.session.get('OAuth-authorization'):
            context['stripped_layout'] = True

        return render(request, 'common/user/login/login.html', context)

    elif request.method == 'POST':
        matches, message = attempt_login(request)

        if len(matches) == 1:
            if request.session.get('OAuth-authorization'):
                try:
                    o = urlparse(request.GET.get('next', None))
                    client_id = [a[1] for a in parse_qsl(o.query) if a[0] == 'client_id'][0]
                    request.user.last_login_oauth_date = datetime.now()
                    request.user.save()
                    log, created = UserOauthActiveLog.objects.get_or_create(
                        user=request.user,
                        oauth_client_id=client_id,
                        defaults={
                            'first_date': request.user.last_login_oauth_date,
                            'last_date': request.user.last_login_oauth_date
                        })
                    if not created:
                        log.last_date = request.user.last_login_oauth_date
                        log.save()
                except:
                    pass
            else:
                request.user.last_login_site_date = datetime.now()
                request.user.save()

            if request.site.is_central():
                return redirect(request.GET.get('next', reverse('user:home')))
            else:
                if 'sso_checked' in request.session:
                    del request.session['sso_checked']
                return redirect(sso_login_url(
                    request.site,
                    request.user,
                    request.GET.get('next', reverse('user:home')),
                ))

        elif len(matches) > 1:
            # Multiple matches, offer a choice between all matches
            request.session['authenticated_users'] = [u.id for u in matches]
            if 'next' in request.GET:
                return redirect(
                    "%s?next=%s" % (
                        reverse('user:login.choose_authenticated_user'),
                        urlquote(request.GET['next']),
                    )
                )
            else:
                return redirect('user:login.choose_authenticated_user')

        else:
            messages.error(request, message)
            if 'next' in request.GET:
                context['next'] = urlquote(request.GET['next'])
            context['email'] = request.POST['email']
            if request.session.get('OAuth-authorization'):
                context['stripped_layout'] = True
            return render(request, 'common/user/login/login.html', context)

    else:
        return redirect('user:login.login')
def main_site(request):
    return {'main_site': Site.get_central()}
示例#11
0
def redirect_admin_central(request):
    return perform_redirect(
        request,
        'https://%s%s' % (Site.get_central().domain, request.get_full_path()),
        include_params=False,
    )
示例#12
0
def create(request, forening_id):
    current_forening = Forening.objects.get(id=forening_id)

    if current_forening not in request.user.all_foreninger():
        raise PermissionDenied

    # The parent choices are tricky to define in the forms API, so do it here.
    # Note that we're intentionally letting users choose parents among only those they have permission to.
    all_sorted = request.user.all_foreninger_sorted()
    parents_choices = {
        'forening': all_sorted['forening'],
        'turlag': all_sorted['turlag'],
    }

    # If the parent of the current forening isn't in the user's permissions, we still need to include that one as an
    # available parent so that they're able to make changes.
    if current_forening.type != 'sentral':
        for current_parent in current_forening.get_main_foreninger():
            if current_parent not in parents_choices['forening'] and current_parent not in parents_choices['turlag']:
                parents_choices[current_parent.type].append(current_parent)

    form = CreateForeningForm(request.user, initial={
        'zipcode': '',
    })

    context = {
        'current_forening': current_forening,
        'parents_choices': parents_choices,
        'admin_user_search_char_length': settings.ADMIN_USER_SEARCH_CHAR_LENGTH,
        'form': form,
    }

    # Give URLPicker the homepage site for the current forening. If they don't have one, just use the central site
    relevant_site = current_forening.get_homepage_site() or Site.get_central()
    context.update(url_picker_context(relevant_site))

    if request.method == 'GET':
        return render(request, 'central/admin/foreninger/create.html', context)

    elif request.method == 'POST':

        form = CreateForeningForm(request.user, request.POST)
        if form.is_valid():
            forening = Forening()
            forening.name = form.cleaned_data['name']
            forening.type = form.cleaned_data['type']
            if forening.type == 'turgruppe':
                forening.group_type = form.cleaned_data['group_type']
            else:
                forening.group_type = ''

            forening.save()

            # Set M2M-fields after the initial db-save
            forening.parents = form.cleaned_data['parents']

            # Ensure the Turbasen object is re-saved with applicable M2M-relations
            forening.save_turbasen_object()

            # Add the current user as admin on the new forening
            role = ForeningRole(
                user=request.user,
                forening=forening,
                role='admin',
            )
            role.save()
            # FIXME: We can't delete the permission cache for all users, so some may find that they can't edit
            # the new forening even though they should be able, until the cache (which is currently 24h) expires.
            cache.delete('user.%s.all_foreninger' % request.user.id)

            messages.info(request, 'forening_create_success')
            request.session['active_forening'] = forening.id
            cache.delete('foreninger.all.sorted_by_name')
            cache.delete('foreninger.all.sorted_by_type')
            cache.delete('foreninger.rendered_select')
            cache.delete('forening.%s' % forening.id)
            cache.delete('forening.main_foreninger.%s' % forening.id)
            return redirect('admin:foreninger.edit', forening.id)
        else:
            context.update({'form': form})
            return render(request, 'central/admin/foreninger/create.html', context)

    else:
        return redirect('admin:foreninger.create', current_forening.id)