summaryrefslogtreecommitdiff
path: root/internal/config/v2/convert.go
blob: 675d2745201529da4ae6ba1c8fb4f4b8a4d5accf (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
77
78
79
80
81
82
83
84
85
86
87
88
package v2

import (
	"maps"
	"time"

	"codeberg.org/eduVPN/eduvpn-common/internal/config/v1"
	"codeberg.org/eduVPN/eduvpn-common/types/server"
)

func v1AuthTime(st time.Time, ost time.Time) time.Time {
	// OAuth start time can be zero
	if ost.IsZero() {
		return st
	}
	return ost
}

func convertV1Server(list v1.InstituteServers, iscurrent bool, t server.Type) (map[ServerKey]*Server, *ServerKey) {
	ret := make(map[ServerKey]*Server)
	var lc *ServerKey
	for k, v := range list.Map {
		key := ServerKey{
			T:  t,
			ID: k,
		}
		if iscurrent && k == list.CurrentURL {
			lc = &key
		}
		prfs := v.Base.Profiles.Public()
		prfs.Current = v.Base.Profiles.Current
		ret[key] = &Server{
			Profiles:          prfs,
			LastAuthorizeTime: v1AuthTime(v.Base.StartTime, v.Base.StartTimeOAuth),
			ExpireTime:        v.Base.ExpireTime,
		}
	}
	return ret, lc
}

// FromV1 converts a version 1 state struct into a v2 one
func FromV1(ver1 *v1.V1) *V2 {
	gsrvs := ver1.Servers

	var lc *ServerKey
	cust, glc := convertV1Server(gsrvs.Custom, gsrvs.IsType == v1.CustomServerType, server.TypeCustom)
	if lc == nil {
		lc = glc
	}
	res, glc := convertV1Server(gsrvs.Institute, gsrvs.IsType == v1.InstituteAccessServerType, server.TypeInstituteAccess)
	if lc == nil {
		lc = glc
	}

	maps.Copy(res, cust)
	sec := gsrvs.SecureInternetHome
	// if the home organization ID is filled we have secure internet present
	if sec.HomeOrganizationID == "" {
		return &V2{
			Discovery:  ver1.Discovery,
			List:       res,
			LastChosen: lc,
		}
	}
	v, ok := sec.BaseMap[sec.CurrentLocation]
	if v != nil && ok {
		t := ServerKey{
			T:  server.TypeSecureInternet,
			ID: sec.HomeOrganizationID,
		}
		if gsrvs.IsType == v1.SecureInternetServerType {
			lc = &t
		}
		prfs := v.Profiles.Public()
		prfs.Current = v.Profiles.Current
		res[t] = &Server{
			CountryCode:       sec.CurrentLocation,
			Profiles:          prfs,
			LastAuthorizeTime: v1AuthTime(v.StartTime, v.StartTimeOAuth),
			ExpireTime:        v.ExpireTime,
		}
	}
	return &V2{
		Discovery:  ver1.Discovery,
		List:       res,
		LastChosen: lc,
	}
}