コード例 #1
0
ファイル: auth.py プロジェクト: jvperrin/ocfweb
    def _decorator(request, *args, **kwargs):
        try:
            user = logged_in_user(request)
        except KeyError:
            user = None

        if user and user_is_group(logged_in_user(request)):
            return function(request, *args, **kwargs)

        return render(request, 'group_accounts_only.html', {
            'user': user,
        }, status=403)
コード例 #2
0
ファイル: auth.py プロジェクト: sberkun/ocfweb
    def _decorator(request: HttpRequest, *args: Any, **kwargs: Any) -> Any:
        try:
            user: Optional[str] = logged_in_user(request)
        except KeyError:
            user = None

        if user and user_is_group(logged_in_user(request)):
            return function(request, *args, **kwargs)

        return render(
            request, 'group_accounts_only.html', {
                'user': user,
            }, status=403,
        )
コード例 #3
0
def vhost_mail(request):
    user = logged_in_user(request)
    vhosts = []

    with _txn() as c:
        for vhost in sorted(vhosts_for_user(user)):
            addresses = sorted(vhost.get_forwarding_addresses(c))
            vhosts.append({
                'domain':
                vhost.domain,
                'addresses':
                addresses,
                'has_wildcard':
                any(address.is_wildcard for address in addresses),
            })

    return render(
        request,
        'account/vhost_mail/index.html',
        {
            'title': 'Mail Virtual Hosting',
            'vhosts': vhosts,
            'example_csv': EXAMPLE_CSV,
        },
    )
コード例 #4
0
def ocf_template_processor(request):
    hours = Day.from_date(date.today())
    real_ip = get_real_ip(request)
    user = logged_in_user(request)
    return {
        'base_css_classes': ' '.join(get_base_css_classes(request)),
        'current_lab_hours': hours,
        'is_ocf_ip': is_ocf_ip(ip_address(real_ip)) if real_ip else True,
        'join_staff_url': request.build_absolute_uri(reverse('about-staff')),
        'lab_is_open': hours.is_open(),
        'lab_status': get_lab_status(),
        'ocfweb_version': ocfweb_version(),
        'request_full_path': request.get_full_path(),
        'user': user,
        'user_is_group': user is not None and user_is_group(user),
    }
コード例 #5
0
ファイル: context_processors.py プロジェクト: jvperrin/ocfweb
def ocf_template_processor(request):
    hours = Day.from_date(date.today())
    real_ip = get_real_ip(request)
    user = logged_in_user(request)
    return {
        'base_css_classes': ' '.join(get_base_css_classes(request)),
        'current_lab_hours': hours,
        'is_ocf_ip': is_ocf_ip(ip_address(real_ip)) if real_ip else True,
        'join_staff_url': request.build_absolute_uri(reverse('about-staff')),
        'lab_is_open': hours.is_open(),
        'lab_status': get_lab_status(),
        'ocfweb_version': ocfweb_version(),
        'request_full_path': request.get_full_path(),
        'user': user,
        'user_is_group': user is not None and user_is_group(user),
    }
コード例 #6
0
def api_vhost_mail(request):
    user = logged_in_user(request)
    vhosts = []

    with _txn() as c:
        for vhost in sorted(vhosts_for_user(user)):
            addresses = {}
            for forwarding_addr in sorted(vhost.get_forwarding_addresses(c)):
                addresses[forwarding_addr.address] = list(
                    forwarding_addr.forward_to)
            vhosts.append({
                'domain': vhost.domain,
                'addresses': addresses,
            })

    return JsonResponse(vhosts, safe=False)
コード例 #7
0
def vhost_mail_csv_export(request, domain):
    user = logged_in_user(request)
    vhost = _get_vhost(user, domain)
    if not vhost:
        _error(request, f'You cannot use the domain: "{domain}"')

    with _txn() as c:
        addresses = (addr for addr in sorted(vhost.get_forwarding_addresses(c))
                     if not addr.is_wildcard)

    response = HttpResponse(
        _write_csv(addresses),
        content_type='text/csv',
    )
    # See https://docs.djangoproject.com/en/1.11/ref/request-response/
    response['Content-disposition'] = f'attachment; filename="{domain}.csv"'
    return response
コード例 #8
0
ファイル: context_processors.py プロジェクト: sberkun/ocfweb
def ocf_template_processor(request: HttpRequest) -> Dict[str, Any]:
    hours_listing = get_hours_listing()
    real_ip, _ = get_client_ip(request)
    user = logged_in_user(request)
    return {
        'base_css_classes': ' '.join(get_base_css_classes(request)),
        'current_lab_hours': hours_listing.hours_on_date(),
        'holidays': hours_listing.holidays,
        'is_ocf_ip': is_ocf_ip(ip_address(real_ip)) if real_ip else True,
        'join_staff_url': request.build_absolute_uri(reverse('about-staff')),
        'lab_is_open': hours_listing.is_open(),
        'lab_status': get_lab_status(),
        'ocfweb_version': ocfweb_version(),
        'request_full_path': request.get_full_path(),
        'user': user,
        'user_is_group': user is not None and user_is_group(user),
    }
コード例 #9
0
ファイル: vhost_mail.py プロジェクト: ocf/ocfweb
def vhost_mail_csv_import(request: HttpRequest,
                          domain: str) -> HttpResponseRedirect:
    user = logged_in_user(request)
    vhost = _get_vhost(user, domain)
    if not vhost:
        _error(request, f'You cannot use the domain: "{domain}"')

    addresses = _parse_csv(request, domain)

    # Add new addresses and update existing if the recipients changed
    with _txn() as c:
        existing_addrs = {
            addr.address: addr
            for addr in vhost.get_forwarding_addresses(c)
        }

        for from_addr, to_addrs in addresses.items():
            if from_addr in existing_addrs:
                existing_addr = existing_addrs[from_addr]
                if to_addrs != existing_addr.forward_to:
                    new = MailForwardingAddress(
                        address=from_addr,
                        crypt_password=existing_addr.crypt_password,
                        forward_to=to_addrs,
                        last_updated=None,
                    )
                    vhost.remove_forwarding_address(c, from_addr)
                else:
                    new = None
            else:
                new = MailForwardingAddress(
                    address=from_addr,
                    crypt_password=None,
                    forward_to=to_addrs,
                    last_updated=None,
                )

            if new is not None:
                vhost.add_forwarding_address(c, new)

    messages.add_message(request, messages.SUCCESS, 'Import successful!')
    return _redirect_back()
コード例 #10
0
ファイル: vhost_mail.py プロジェクト: jvperrin/ocfweb
def vhost_mail(request):
    user = logged_in_user(request)
    vhosts = []

    with _txn() as c:
        for vhost in sorted(vhosts_for_user(user)):
            addresses = sorted(vhost.get_forwarding_addresses(c))
            vhosts.append({
                'domain': vhost.domain,
                'addresses': addresses,
                'has_wildcard': any(address.is_wildcard for address in addresses),
            })

    return render(
        request,
        'account/vhost_mail/index.html',
        {
            'title': 'Mail Virtual Hosting',
            'vhosts': vhosts,
        },
    )
コード例 #11
0
def logout(request: HttpRequest) -> Union[HttpResponseRedirect, HttpResponse]:
    return_to = request.GET.get('next')
    if return_to and _valid_return_path(return_to):
        request.session['login_return_path'] = return_to

    if request.method == 'POST':
        form = forms.Form(request.POST)

        if form.is_valid():
            session_logout(request)
            return redirect_back(request)
    else:
        form = forms.Form()

    return render(
        request,
        'login/ocf/logout.html',
        {
            'form': form,
            'user': logged_in_user(request),
        },
    )
コード例 #12
0
ファイル: ocf.py プロジェクト: jvperrin/ocfweb
def logout(request):
    return_to = request.GET.get('next')
    if return_to and _valid_return_path(return_to):
        request.session['login_return_path'] = return_to

    if request.method == 'POST':
        form = forms.Form(request.POST)

        if form.is_valid():
            session_logout(request)
            return redirect_back(request)
    else:
        form = forms.Form()

    return render(
        request,
        'login/ocf/logout.html',
        {
            'form': form,
            'user': logged_in_user(request),
        },
    )
コード例 #13
0
def request_vhost(request: HttpRequest) -> HttpResponse:
    user = logged_in_user(request)
    attrs = user_attrs(user)
    is_group = 'callinkOid' in attrs
    error = None

    if has_vhost(user):
        return render(
            request,
            'account/vhost/already_have_vhost.html',
            {
                'title': 'You already have virtual hosting',
                'user': user,
            },
        )
    elif not eligible_for_vhost(user):
        return render(
            request,
            'account/vhost/not_eligible.html',
            {
                'title': 'You are not eligible for virtual hosting',
                'user': user,
            },
        )

    if request.method == 'POST':
        form = VirtualHostForm(is_group, request.POST)

        if form.is_valid():
            requested_subdomain = form.cleaned_data['requested_subdomain']
            university_purpose = form.cleaned_data['university_purpose']
            university_contact = form.cleaned_data['university_contact']
            comments = form.cleaned_data['comments']
            your_name = form.cleaned_data['your_name'] if is_group else attrs[
                'cn'][0]
            your_email = form.cleaned_data['your_email']
            your_position = form.cleaned_data['your_position']

            if not error:
                # send email to hostmaster@ocf and redirect to success page
                ip_addr, _ = get_client_ip(request)

                try:
                    ip_reverse = socket.gethostbyaddr(ip_addr)[0]
                except socket.herror:
                    ip_reverse = 'unknown'

                subject = 'Virtual Hosting Request: {} ({})'.format(
                    requested_subdomain,
                    user,
                )
                message = dedent('''\
                    Virtual Hosting Request:
                      - OCF Account: {user}
                      - OCF Account Title: {title}
                      - Requested Subdomain: {requested_subdomain}
                      - Current URL: https://www.ocf.berkeley.edu/~{user}/

                    University Hostmaster Questions:
                      - Purpose: {university_purpose}
                      - Contact: {university_contact}

                    Comments/Special Requests:
                    {comments}

                    Requested by:
                      - Name: {your_name}
                      - Position: {your_position}
                      - Email: {your_email}
                      - IP Address: {ip_addr} ({ip_reverse})
                      - User Agent: {user_agent}

                    --------
                    Request submitted to ocfweb ({hostname}) on {now}.
                    {full_path}''').format(
                    user=user,
                    title=attrs['cn'][0],
                    requested_subdomain=requested_subdomain,
                    university_purpose=university_purpose,
                    university_contact=university_contact,
                    comments=comments,
                    your_name=your_name,
                    your_position=your_position,
                    your_email=your_email,
                    ip_addr=ip_addr,
                    ip_reverse=ip_reverse,
                    user_agent=request.META.get('HTTP_USER_AGENT'),
                    now=datetime.datetime.now().strftime(
                        '%A %B %e, %Y @ %I:%M:%S %p', ),
                    hostname=socket.gethostname(),
                    full_path=request.build_absolute_uri(),
                )

                try:
                    send_mail(
                        '*****@*****.**' if not settings.DEBUG
                        else current_user_formatted_email(),
                        subject,
                        message,
                        sender=your_email,
                    )
                except Exception as ex:
                    # TODO: report via ocflib
                    print(ex)
                    print('Failed to send vhost request email!')
                    error = \
                        'We were unable to submit your virtual hosting ' + \
                        'request. Please try again or email us at ' + \
                        '*****@*****.**'
                else:
                    return redirect(reverse('request_vhost_success'))
    else:
        # Unsupported left operand type for + ("None") because form might not have been instantiated at this point...
        # but this doesn't matter because of if-else clause
        form = VirtualHostForm(
            is_group, initial={'requested_subdomain':
                               user + '.berkeley.edu'})  # type: ignore

    group_url = f'https://www.ocf.berkeley.edu/~{user}/'

    return render(
        request,
        'account/vhost/index.html',
        {
            'attrs': attrs,
            'error': error,
            'form': form,
            'group_url': group_url,
            'is_group': is_group,
            'title': 'Request virtual hosting',
            'user': user,
        },
    )
コード例 #14
0
def vhost_mail_update(request):
    user = logged_in_user(request)

    # All requests are required to have these
    action = _get_action(request)
    addr_name, addr_domain, addr_vhost = _get_addr(request,
                                                   user,
                                                   'addr',
                                                   required=True)
    addr = (addr_name or '') + '@' + addr_domain

    # These fields are optional; some might be None
    forward_to = _get_forward_to(request)

    new_addr = _get_addr(request, user, 'new_addr', required=False)
    new_addr_name = None
    if new_addr is not None:
        new_addr_name, new_addr_domain, new_addr_vhost = new_addr
        new_addr = (new_addr_name or '') + '@' + new_addr_domain

        # Sanity check: can't move addresses across vhosts
        if new_addr_vhost != addr_vhost:
            _error(
                request,
                'You cannot change an address from "{}" to "{}"!'.format(
                    addr_domain,
                    new_addr_domain,
                ),
            )

    password_hash = _get_password(request, new_addr_name or addr_name)

    # Perform the add/update
    with _txn() as c:
        existing = _find_addr(c, addr_vhost, addr)
        new = None

        if action == 'add':
            if existing is not None:
                _error(request, f'The address "{addr}" already exists!')

            new = MailForwardingAddress(
                address=addr,
                crypt_password=None,
                forward_to=None,
                last_updated=None,
            )
        else:
            if existing is None:
                _error(request, f'The address "{addr}" does not exist!')
            addr_vhost.remove_forwarding_address(c, existing.address)

        if action != 'delete':
            new = new or existing
            if forward_to:
                new = new._replace(forward_to=forward_to)
            if password_hash is REMOVE_PASSWORD:
                new = new._replace(crypt_password=None)
            elif password_hash:
                new = new._replace(crypt_password=password_hash)
            if new_addr:
                new = new._replace(address=new_addr)

        if new is not None:
            addr_vhost.add_forwarding_address(c, new)

    messages.add_message(request, messages.SUCCESS, 'Update successful!')
    return _redirect_back()
コード例 #15
0
ファイル: vhost_mail.py プロジェクト: jvperrin/ocfweb
def vhost_mail_update(request):
    user = logged_in_user(request)

    # All requests are required to have these
    action = _get_action(request)
    addr_name, addr_domain, addr_vhost = _get_addr(request, user, 'addr', required=True)
    addr = (addr_name or '') + '@' + addr_domain

    # These fields are optional; some might be None
    forward_to = _get_forward_to(request)

    new_addr = _get_addr(request, user, 'new_addr', required=False)
    new_addr_name = None
    if new_addr is not None:
        new_addr_name, new_addr_domain, new_addr_vhost = new_addr
        new_addr = (new_addr_name or '') + '@' + new_addr_domain

        # Sanity check: can't move addresses across vhosts
        if new_addr_vhost != addr_vhost:
            _error(
                request,
                'You cannot change an address from "{}" to "{}"!'.format(
                    addr_domain, new_addr_domain,
                ),
            )

    password_hash = _get_password(request, new_addr_name or addr_name)

    # Perform the add/update
    with _txn() as c:
        existing = _find_addr(c, addr_vhost, addr)
        new = None

        if action == 'add':
            if existing is not None:
                _error(request, 'The address "{}" already exists!'.format(addr))

            new = MailForwardingAddress(
                address=addr,
                crypt_password=None,
                forward_to=None,
                last_updated=None,
            )
        else:
            if existing is None:
                _error(request, 'The address "{}" does not exist!'.format(addr))
            addr_vhost.remove_forwarding_address(c, existing.address)

        if action != 'delete':
            new = new or existing
            if forward_to:
                new = new._replace(forward_to=forward_to)
            if password_hash is REMOVE_PASSWORD:
                new = new._replace(crypt_password=None)
            elif password_hash:
                new = new._replace(crypt_password=password_hash)
            if new_addr:
                new = new._replace(address=new_addr)

        if new is not None:
            addr_vhost.add_forwarding_address(c, new)

    messages.add_message(request, messages.SUCCESS, 'Update successful!')
    return _redirect_back()
コード例 #16
0
def request_vhost(request):
    user = logged_in_user(request)
    attrs = user_attrs(user)
    error = None

    if has_vhost(user):
        return render(
            request,
            'account/vhost/already_have_vhost.html',
            {
                'title': 'You already have virtual hosting',
                'user': user,
            },
        )

    if request.method == 'POST':
        form = VirtualHostForm(request.POST)

        if form.is_valid():
            requested_subdomain = form.cleaned_data['requested_subdomain']
            requested_why = form.cleaned_data['requested_why']
            comments = form.cleaned_data['comments']
            your_name = form.cleaned_data['your_name']
            your_email = form.cleaned_data['your_email']
            your_position = form.cleaned_data['your_position']

            if not error:
                # send email to hostmaster@ocf and redirect to success page
                ip_addr = get_real_ip(request)

                try:
                    ip_reverse = socket.gethostbyaddr(ip_addr)[0]
                except:
                    ip_reverse = 'unknown'

                subject = 'Virtual Hosting Request: {} ({})'.format(
                    requested_subdomain,
                    user,
                )
                message = dedent('''\
                    Virtual Hosting Request:
                      - OCF Account: {user}
                      - OCF Account Title: {title}
                      - Requested Subdomain: {requested_subdomain}
                      - Current URL: https://www.ocf.berkeley.edu/~{user}/

                    Request Reason:
                    {requested_why}

                    Comments/Special Requests:
                    {comments}

                    Requested by:
                      - Name: {your_name}
                      - Position: {your_position}
                      - Email: {your_email}
                      - IP Address: {ip_addr} ({ip_reverse})
                      - User Agent: {user_agent}

                    --------
                    Request submitted to ocfweb ({hostname}) on {now}.
                    {full_path}''').format(
                    user=user,
                    title=attrs['cn'][0],
                    requested_subdomain=requested_subdomain,
                    requested_why=requested_why,
                    comments=comments,
                    your_name=your_name,
                    your_position=your_position,
                    your_email=your_email,
                    ip_addr=ip_addr,
                    ip_reverse=ip_reverse,
                    user_agent=request.META.get('HTTP_USER_AGENT'),
                    now=datetime.datetime.now().strftime(
                        '%A %B %e, %Y @ %I:%M:%S %p',
                    ),
                    hostname=socket.gethostname(),
                    full_path=request.build_absolute_uri(),
                )

                try:
                    send_mail(
                        '*****@*****.**' if not settings.DEBUG else current_user_formatted_email(),
                        subject,
                        message,
                        sender=your_email,
                    )
                except Exception as ex:
                    # TODO: report via ocflib
                    print(ex)
                    print('Failed to send vhost request email!')
                    error = \
                        'We were unable to submit your virtual hosting ' + \
                        'request. Please try again or email us at ' + \
                        '*****@*****.**'
                else:
                    return redirect(reverse('request_vhost_success'))
    else:
        form = VirtualHostForm(initial={'requested_subdomain': user + '.berkeley.edu'})

    group_url = 'https://www.ocf.berkeley.edu/~{0}/'.format(user)

    return render(
        request,
        'account/vhost/index.html',
        {
            'attrs': attrs,
            'error': error,
            'form': form,
            'group_url': group_url,
            'title': 'Request berkeley.edu virtual hosting',
            'user': user,
        },
    )