VPN client status and connectivity

The ComponentContext instance offers properties and methods that let the custom component interact with the VPN client. Below is a simple example of a custom component that offers VPN connectivity.

<template>
  <p>VPN status: {{ isConnected ? 'connected' : 'disconnected' }}</p>
  <button @click="toggleVpn()" :disabled="!agent">
    {{ isConnected ? 'Disconnect' : 'Connect' }}
  </button>
</template>

<script>
export default {
  name: 'vpn-connect',
  props: ['context'],
  data() {
    return { agent: null, vpnClientStatus: null };
  },
  computed: {
    isConnected() {
      return this.vpnClientStatus?.status === 'connected';
    }
  },
  methods: {
    toggleVpn() {
      if (this.agent) {
        // Tests whether the currently logged in user has VPN access for
        // the "active device".
        if (!this.context.testVpnAccess(this.agent.publicId)) {
          alert('Not allowed!');
          return;
        }
        this.context.toggleVpn(this.agent.publicId);
      }
    }
  },
  created() {
    const client = this.context.createResourceDataClient();
    
    // Queries the "active device" on this page.
    client.query({ selector: 'Agent', fields: ['publicId'] }, result => {
      this.agent = result[0].data;
    });
    
    // Sets the current VPN client status
    this.vpnClientStatus = this.context.vpnClientStatus;
    
    // Starts listening for updates to the VPN client status
    this.context.onvpnclientstatuschange = newStatus => {
      this.vpnClientStatus = newStatus;
    }
  },
};
</script>

<style scoped></style>
<script>
  import { onMount } from 'svelte';

  export let context;
  let agent;
  let vpnClientStatus;
  
  $: isConnected = vpnClientStatus?.status === 'connected';
  
  onMount(() => {
    const client = context.createResourceDataClient();
    
    // Queries the "active device" on this page.
    client.query({ selector: 'Agent', fields: ['publicId'] }, result => {
      agent = result[0].data;
    });
    
    // Sets the current VPN client status
    vpnClientStatus = context.vpnClientStatus;
    
    // Starts listening for updates to the VPN client status
    context.onvpnclientstatuschange = newStatus => {
      vpnClientStatus = newStatus;
    }
  });
  
  function toggleVpn() {
    if (agent) {
      // Tests whether the currently logged in user has VPN access for
      // the "active device".
      if (!context.testVpnAccess(agent.publicId)) {
        alert('Not allowed!');
        return;
      }
      context.toggleVpn(agent.publicId);
    }
  }
</script>

<p>VPN status: { isConnected ? 'connected' : 'disconnected' }</p>
<button disabled={!agent} on:click={toggleVpn}>
  { isConnected ? 'Disconnect' : 'Connect' }
</button>

<style></style>

Did this page help you?