Example #1
0
def log_session(request: HttpRequest) -> HttpResponse:
    """Primary API endpoint for session tracking.

    Desktops have a cronjob that calls this endpoint: https://git.io/vpIKX
    """

    remote_ip = ip_address(get_client_ip(request)[0])

    if not is_ocf_ip(remote_ip):
        return HttpResponse('Not Authorized', status=401)

    try:
        host = _get_desktops().get(remote_ip)

        if not host:
            raise ValueError(f'IP {remote_ip} does not belong to a desktop')

        body = json.loads(request.body.decode('utf-8'))
        state = State[body.get('state')]  # triggers KeyError
        user = body.get('user')

        if state is State.cleanup or not user:
            # sessions also get periodically cleaned up: https://git.io/vpwg8
            _close_sessions(host)
        elif state is State.active and _session_exists(host, user):
            _refresh_session(host, user)
        else:
            _new_session(host, user)

        return HttpResponse(status=204)

    except (KeyError, ValueError) as e:
        return HttpResponseBadRequest(e)
Example #2
0
def ocf_template_processor(request):
    hours = Day.from_date(date.today())
    real_ip = get_real_ip(request)
    return {
        'lab_is_open': hours.is_open(),
        'current_lab_hours': hours,
        'lab_status': get_lab_status(),
        'base_css_classes': ' '.join(get_base_css_classes(request)),
        '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')),
        'ocfweb_version': ocfweb_version(),
    }
Example #3
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),
    }
Example #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),
    }
Example #5
0
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),
    }
Example #6
0
def host(bot, msg):
    """Print information about an internal or external hostname."""
    # TODO: also support reverse DNS lookup if given an IP
    # TODO: ipv6 support
    host = msg.match.group(1).lower().rstrip('.')

    # Find the IP
    if '.' not in host:
        host += '.ocf.berkeley.edu'

    try:
        ip = socket.gethostbyname(host)
    except socket.error as ex:
        msg.respond(str(ex))
        return

    reverse_dns: Optional[str]
    try:
        reverse_dns, _, _ = socket.gethostbyaddr(ip)
    except socket.error:
        reverse_dns = None

    if net.is_ocf_ip(ipaddress.ip_address(ip)):
        ocf_host_info = 'OCF host'

        hosts_from_ldap = hosts.hosts_by_filter(f'(ipHostNumber={ip})')
        if hosts_from_ldap:
            ldap, = hosts_from_ldap
            ocf_host_info += ' ({}, puppet env: {})'.format(
                ldap['type'],
                ldap['environment'][0] if 'environment' in ldap else None,
            )
        else:
            ocf_host_info += ' (not in LDAP?)'
    else:
        ocf_host_info = 'not an OCF host'

    msg.respond(
        '{host}: {ip} ({reverse_dns}) | {ocf_host_info}'.format(
            host=host,
            ip=ip,
            reverse_dns=reverse_dns if reverse_dns else 'no reverse dns',
            ocf_host_info=ocf_host_info,
        ),
        ping=False,
    )
Example #7
0
def update_inventory(request):

    desktop_ip = request.META['REMOTE_ADDR']

    if not is_ocf_ip(ip_address(desktop_ip)):
        return HttpResponse('Not Authorized', status=401)

    try:
        hardware = json_load_string(request.body.decode('utf-8'))

        hostname = hardware['hostname']

        if not hostname == _get_hostname(desktop_ip):
            return HttpResponse('Not Authorized', status=401)

        if hostname == '' or hostname is None:
            raise ValueError('Invalid host "{}"'.format(hostname))

        for device in hardware['devices']:
            device_class = device['class']
            if device_class == '' or device_class is None:
                raise ValueError('Invalid device class "{}"'.format(device_class))

            device_merchant = device['merchant']
            if device_merchant == '' or device_merchant is None:
                raise ValueError('Invalid device merchant "{}"'.format(device_merchant))

            device_name = device['name']
            if device_name == '' or device_name is None:
                raise ValueError('Invalid device name "{}"'.format(device_name))

            _add_desktop_device(hostname, device_class, device_merchant, device_name)

        return HttpResponse(status=204)

    except ValueError as e:
        return HttpResponseBadRequest(e)
Example #8
0
def test_is_ocf_ip_failure():
    with pytest.raises(AssertionError):
        is_ocf_ip('169.229.226.12')
Example #9
0
def test_is_ocf_ip(ip, expected):
    assert is_ocf_ip(ip) is expected
Example #10
0
def test_is_ocf_ip_failure():
    with pytest.raises(AssertionError):
        is_ocf_ip('169.229.226.12')
Example #11
0
def test_is_ocf_ip(ip, expected):
    assert is_ocf_ip(ip) is expected