summaryrefslogtreecommitdiff
path: root/windows/WinUI/CentralAPI.cs
blob: 8c36f455970ab1d06b6dd83cf5c4678b81bb1410 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace WinUI
{
    class CentralAPI
    {
        private static volatile CentralAPI instance;
        private static object syncRoot = new Object();

        private CookieContainer cookieContainer;
        private HttpClientHandler clientHandler;
        private HttpClient client;

        private CentralServer server;
        public CentralServer Central
        {
            get
            {
                return this.server;
            }
            set
            {
                this.server = value;
                WriteCentralConfig();
                UpdateRequestHeaders();
            }
        }

        public static CentralAPI Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = new CentralAPI();
                        }
                    }
                }

                return instance;
            }
        }



        private CentralAPI()
        {
#if DEBUG
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
#endif
            cookieContainer = new CookieContainer();
            clientHandler = new HttpClientHandler
            {
                AllowAutoRedirect = true,
                UseCookies = true,
                CookieContainer = cookieContainer
            };
            
            client = new HttpClient(clientHandler);

            string centralConfigPath = CentralConfigFile();
            if (File.Exists(centralConfigPath))
            {
                byte[] tmp = File.ReadAllBytes(centralConfigPath);
                string json = Encoding.UTF8.GetString(tmp).Trim();
                Central = JsonConvert.DeserializeObject<CentralServer>(json);
            }
            else
            {
                Central = new CentralServer();
            }
        }

        public bool HasAccessToken()
        {
            if (Central == null)
                return false;

            return !string.IsNullOrEmpty(Central.APIKey);
        }

        private string ZeroTierDir()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\ZeroTier\\One";
        }

        private string CentralConfigFile()
        {
            return ZeroTierDir() + "\\central.conf";
        }

        public void WriteCentralConfig()
        {
            string json = JsonConvert.SerializeObject(Central);
            byte[] tmp = Encoding.UTF8.GetBytes(json);
            File.WriteAllBytes(CentralConfigFile(), tmp);
        }

        private void UpdateRequestHeaders()
        {
            if (client.DefaultRequestHeaders.Contains("Authorization"))
            {
                client.DefaultRequestHeaders.Remove("Authorization");
            }

            if (!string.IsNullOrEmpty(Central.APIKey))
            {
                client.DefaultRequestHeaders.Add("Authorization", "bearer " + Central.APIKey);
            }
        }

        public async Task<bool> Login(string email, string password, bool isNewUser)
        {
            string postURL = Central.ServerURL + "/api/_auth/local";
            CentralLogin login = new CentralLogin(email, password, isNewUser);
            var content = new StringContent(JsonConvert.SerializeObject(login), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(postURL, content);

            if (!response.IsSuccessStatusCode)
            {
                return false;
            }

            string resContent = await response.Content.ReadAsStringAsync();

            CentralUser user = JsonConvert.DeserializeObject<CentralUser>(resContent);

            if (user.Tokens.Count == 0)
            {
                // create token
                user = await CreateAuthToken(user);
            }

            Central.APIKey = user.Tokens[0];

            UpdateRequestHeaders();
            WriteCentralConfig();

            return true;
        }

        public async Task<CentralUser> CreateAuthToken(CentralUser user)
        {
            string randomTokenURL = Central.ServerURL + "/api/randomToken";
            HttpResponseMessage response = await client.GetAsync(randomTokenURL);

            if (!response.IsSuccessStatusCode)
            {
                // TODO: throw an error
                return null;
            }

            string resContent = await response.Content.ReadAsStringAsync();

            CentralToken t = JsonConvert.DeserializeObject<CentralToken>(resContent);

            user.Tokens.Add(t.Token);

            string tokenObj = "{ \"tokens\": " + JsonConvert.SerializeObject(user.Tokens) + " } ";

            string postURL = Central.ServerURL + "/api/user/" + user.Id;
            var postContent = new StringContent(tokenObj, Encoding.UTF8, "application/json");
            response = await client.PostAsync(postURL, postContent);

            if (!response.IsSuccessStatusCode)
            {
                // TODO: thrown an error
                return null;
            }

            resContent = await response.Content.ReadAsStringAsync();
            user = JsonConvert.DeserializeObject<CentralUser>(resContent);

            return user;
        }

        public async Task<List<CentralNetwork>> GetNetworkList()
        {
            string networkURL = Central.ServerURL + "/api/network";

            HttpResponseMessage response = await client.GetAsync(networkURL);

            if (!response.IsSuccessStatusCode)
            {
                // TODO:  Throw Error
                return new List<CentralNetwork>();
            }

            string resContent = await response.Content.ReadAsStringAsync();

            List<CentralNetwork> networkList = JsonConvert.DeserializeObject<List<CentralNetwork>>(resContent);

            return networkList;
        }

        public async Task<CentralNetwork> CreateNewNetwork()
        {
            string networkURL = Central.ServerURL + "/api/network?easy=1";
            CentralNetwork network = new CentralNetwork();
            network.Config = new CentralNetwork.CentralNetworkConfig();
            network.Config.Name = NetworkNameGenerator.GenerateName();
            string jsonNetwork = JsonConvert.SerializeObject(network);
            var postContent = new StringContent(jsonNetwork, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(networkURL, postContent);

            if (!response.IsSuccessStatusCode)
            {
                return null;
            }

            string resContent = await response.Content.ReadAsStringAsync();

            CentralNetwork newNetwork = JsonConvert.DeserializeObject<CentralNetwork>(resContent);

            return newNetwork;
        }

        public async Task<bool> AuthorizeNode(string nodeAddress, string networkId)
        {
            string json = "{ \"config\": { \"authorized\": true } }";
            string postURL = Central.ServerURL + "/api/network/" + networkId + "/member/" + nodeAddress;
            var postContent = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(postURL, postContent);

            if (response.IsSuccessStatusCode)
            {
                return true;
            }

            return false;
        }
    }
}