summaryrefslogtreecommitdiff
path: root/client/discovery.go
blob: 49df8b2b779e73212221c79d0a2b607a0935394e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package client

import (
	"strings"

	"github.com/eduvpn/eduvpn-common/i18nerr"
	"github.com/eduvpn/eduvpn-common/types/cookie"
	discotypes "github.com/eduvpn/eduvpn-common/types/discovery"
)

func (c *Client) hasDiscovery() bool {
	// see https://git.sr.ht/~fkooman/vpn-user-portal/tree/v3/item/src/OAuth/VpnClientDb.php
	return strings.HasPrefix(c.Name, "org.eduvpn.app")
}

// DiscoOrganizations gets the organizations list from the discovery server with search string `search`
// If the list cannot be retrieved an error is returned.
// If this is the case then a previous version of the list is returned if there is any.
// This takes into account the frequency of updates, see: https://github.com/eduvpn/documentation/blob/v3/SERVER_DISCOVERY.md#organization-list.
func (c *Client) DiscoOrganizations(ck *cookie.Cookie, search string) (*discotypes.Organizations, error) {
	// Not supported with Let's Connect! & govVPN
	if !c.hasDiscovery() {
		return nil, i18nerr.NewInternal("Server/organization discovery with this client ID is not supported")
	}

	orgs, err := c.cfg.Discovery().Organizations(ck.Context())
	if err != nil {
		err = i18nerr.Wrap(err, "An error occurred after getting the discovery files for the list of organizations")
	}
	if orgs == nil {
		return nil, err
	}

	// convert to public subset
	var retOrgs []discotypes.Organization
	for _, v := range orgs.List {
		if !v.Matches(search) {
			continue
		}
		retOrgs = append(retOrgs, v.Organization)
	}
	return &discotypes.Organizations{
		List: retOrgs,
	}, err
}

// DiscoServers gets the servers list from the discovery server with search string `search`
// If the list cannot be retrieved an error is returned.
// If this is the case then a previous version of the list is returned if there is any.
// This takes into account the frequency of updates, see: https://github.com/eduvpn/documentation/blob/v3/SERVER_DISCOVERY.md#server-list.
func (c *Client) DiscoServers(ck *cookie.Cookie, search string) (*discotypes.Servers, error) {
	// Not supported with Let's Connect! & govVPN
	if !c.hasDiscovery() {
		return nil, i18nerr.NewInternal("Server/organization discovery with this client ID is not supported")
	}

	servs, err := c.cfg.Discovery().Servers(ck.Context())
	if err != nil {
		err = i18nerr.Wrap(err, "An error occurred after getting the discovery files for the list of servers")
	}
	if servs == nil {
		return nil, err
	}

	// convert to public subset
	var retServs []discotypes.Server
	for _, v := range servs.List {
		if !v.Matches(search) {
			continue
		}
		retServs = append(retServs, v.Server)
	}
	return &discotypes.Servers{
		List: retServs,
	}, err
}