-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cs
More file actions
191 lines (183 loc) · 6.76 KB
/
Server.cs
File metadata and controls
191 lines (183 loc) · 6.76 KB
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
namespace Webtech3;
/**
<summary> Main class. Realize server instance. </summary>
<example>
Simple example.
<code>
using Webtech3;
class PingPongExample {
[APIInfo(url: "/ping")]
public static async Task Pong(Request req, Response res) {
Logger.Info("Pong", "Ping request catched");
await res.ResponseText("Pong");
}
}
class PongMain {
public static async Task Main() {
var api = new RestAPI(typeof(PingPongExample));
var server = new Server() { Api = api }; //without args listen on 127.0.0.1:8888
Console.CancelKeyPress += (_, e) => { //need for correct end of work with Ctrl+C
e.Cancel = true;
server.Work = false; //stop the server
};
Logger.Info("main", "Working started");
await server.Listen();
}
}
</code>
</example>
<example>
Example with auth.
<code>
static class WithAuthExample {
[APIInfo(url: "/test", auth: true)]
public static async Task TestAuth(Request req, Response res) {
await res.ResponseText("Response if you authorized by header only.");
}
}
class AuthMain {
public static async Task Main() {
var users_repo = new UsersList(
new User(ID: 0, Login_hash: "tyson", Password_hash: "punch")
);
var auth = new BasicAuth() { Users = users_repo };
var api = new RestAPI() { Authentificator = auth };
api.Add(WithAuthExample.TestAuth);
var server = new Server(addresses: new IP(127, 0, 0, 1, 8989)) { Api = api };
//need for correct end of work with Ctrl+C
Console.CancelKeyPress += (_, e) => {
e.Cancel = true;
server.Work = false; //stop the server
};
await server.Listen();
}
}
</code>
</example>
<example>
Example with roles.
<code>
using Webtech3;
using Webtech3.Defaults;
class WithRoleExample {
public static async Task TestRole(Request req, Response res) {
await res.ResponseJson(new {
Status = 200,
Text = "Response if you have correct role only."
});
}
}
class RoleMain {
public static async Task Main() {
var users_repo = new UsersList(
new User(0, "tyson", "punch"),
new User(1, "rabbit", "carrot")
);
//Dynamicly setting the role
var tyson = users_repo.Get(0UL)!;
tyson = tyson with {Role = Roles.Admin};
users_repo.Replace(0UL, tyson);
var auth = new BasicAuth() { Users = users_repo };
var api = new RestAPI() { Authentificator = auth };
api.Route( //You can set APIInfo so
url: "/test",
roles: [Roles.Admin], //if roles is specified, auth implicitly enabled
action: WithRoleExample.TestRole
);
var server = new Server() { Api = api };
//need for correct end of work with Ctrl+C
Console.CancelKeyPress += (_, e) => {
e.Cancel = true;
server.Work = false; //stop the server
};
await server.Listen();
}
}
</code>
</example>
*/
public sealed class Server {
HttpListener http;
List<Task> tasks;
bool work;
/// <summary>
/// Property for check (get) & begin/end (set) server work
/// </summary>
/// <value>True - server works, false otherwise</value>
public bool Work {
get => work;
set {
work = value;
if(!work)
http.Stop();
}
}
/// <summary>
/// API instance.
/// </summary>
public required RestAPI Api { get; init; }
/// <summary>
/// Construct the server.
/// </summary>
/// <param name="use_https">Flag, means use https or not. Default is false.</param>
/// <param name="addresses">IP addresses to listen on.</param>
/// <remarks>
/// For using https you need mannually configure SSL certificate for every address in OS.
/// </remarks>
public Server(bool use_https = false, params IP[] addresses) {
http = new(); tasks = new(); work = true;
if(addresses.Length == 0)
http.Prefixes.Add($"http{(use_https ? "s" : "")}://{new IP(127, 0, 0, 1, 8888)}/");
else
foreach(var ip in addresses)
http.Prefixes.Add($"http{(use_https ? "s" : "")}://{ip}/");
}
/// <summary>
/// Stops the listening.
/// </summary>
public void Stop() => http.Stop();
/// <summary>
/// Close server.
/// </summary>
/// <returns>Task obj.</returns>
public async Task Close() {
await Task.WhenAll(tasks);
http.Close();
}
/// <summary>
/// Main loop.
/// </summary>
/// <returns>Task obj.</returns>
public async Task Listen() {
http.Start();
Context? ctx = null;
while(work) try {
ctx = await http.GetContextAsync();
Request req = new(ctx.Request); Response res = new(ctx.Response);
var endpoint = Api[req.Method, req.Url];
if(endpoint == null)
await res.ResponseError(501, "Method doesn't exists.");
else
if(endpoint.Info.Authentication) {
req.CurrentUser = Api.Authentificator?.Authentificate(req);
if(req.CurrentUser == null)
await res.ResponseError(401, "Not authorized.");
else
if(endpoint.Info.Roles == null)
tasks.Add(endpoint.Action(req, res));
else
if(endpoint.Info.Roles?.Any(r => r == req.CurrentUser.Role) ?? false)
tasks.Add(endpoint.Action(req, res));
else
await res.ResponseError(403, "You doesn't have a sufficient rights for calling this method.");
} else tasks.Add(endpoint.Action(req, res));
if(tasks.Count > 20)
tasks.RemoveAll(t => t.IsCompleted);
} catch(Exception err) {
if(ctx != null)
await new Response(ctx.Response).ResponseError(500, "Internal exception", err.Message);
}
Stop();
await Close();
}
}