Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
CreateApiKey.cs
1using System;
3using System.Text;
4using System.Threading.Tasks;
5using Waher.Content;
11using Waher.Security;
14
16{
18 {
19 public CreateApiKey()
20 : base("/CreateApiKey")
21 {
22 }
23
24 public override bool HandlesSubPaths => false;
25 public override bool UserSessions => true;
26 public bool AllowsPOST => true;
27
28 public async Task POST(HttpRequest Request, HttpResponse Response)
29 {
30 Gateway.AssertUserAuthenticated(Request, "Admin.Broker.Keys");
31
32 if (!Request.HasData)
33 {
34 await Response.SendResponse(new BadRequestException());
35 return;
36 }
37
38 ContentResponse Content = await Request.DecodeDataAsync();
39 if (Content.HasError || !(Content.Decoded is Dictionary<string, string> Form))
40 {
41 await Response.SendResponse(new BadRequestException());
42 return;
43 }
44
45 string Owner;
46 string EMail;
47
48 if (!Form.ContainsKey("Owner") || string.IsNullOrEmpty(Owner = Form["Owner"]))
49 {
50 await Response.SendResponse(new BadRequestException());
51 return;
52 }
53
54 if (!Form.ContainsKey("EMail") || string.IsNullOrEmpty(EMail = Form["EMail"]))
55 {
56 await Response.SendResponse(new BadRequestException());
57 return;
58 }
59
60 if (!Form.ContainsKey("MaxAccounts") || !long.TryParse(Form["MaxAccounts"], out long MaxAccounts) || MaxAccounts < 1)
61 {
62 await Response.SendResponse(new BadRequestException());
63 return;
64 }
65
66 await Create(MaxAccounts, Owner, EMail, Request.RemoteEndPoint);
67
68 if (!(Request.Header.Referer is null))
69 await Response.SendResponse(new SeeOtherException(Request.Header.Referer.Value)); // PRG pattern.
70 }
71
72 internal static async Task<ApiKey> Create(long MaxAccounts, string Owner, string EMail, string RemoteEndPoint)
73 {
74 byte[] Data;
75 string Key;
76 string Secret;
77 bool Found;
78
79 do
80 {
81 Data = Gateway.NextBytes(32);
82 Key = Hashes.BinaryToString(Data);
83
84 Found = false;
85 foreach (ApiKey ApiKey in await Database.Find<ApiKey>(new FilterFieldEqualTo("Key", Key)))
86 {
87 Found = true;
88 break;
89 }
90 }
91 while (Found);
92
93 Data = Gateway.NextBytes(32);
94 Secret = Hashes.BinaryToString(Data);
95
96 ApiKey NewKey = new ApiKey()
97 {
98 Key = Key,
99 Secret = Secret,
100 Owner = Owner,
101 EMail = EMail,
102 Created = DateTime.Now,
103 MaxAccounts = MaxAccounts
104 };
105
106 await Database.Insert(NewKey);
107
109 {
110 StringBuilder Markdown = new StringBuilder();
111 DateTime Now = DateTime.Now;
112
113 Markdown.AppendLine("API Key created:");
114 Markdown.AppendLine();
115 Markdown.AppendLine("| API Key Information ||");
116 Markdown.AppendLine("|:-----|:------|");
117 Markdown.Append("| Key: | `");
118 Markdown.Append(Key);
119 Markdown.AppendLine("` |");
120 Markdown.Append("| Owner: | `");
121 Markdown.Append(Owner);
122 Markdown.Append("`");
123 Markdown.AppendLine(" |");
124 Markdown.Append("| \\#Accounts: | ");
125 Markdown.Append(MaxAccounts.ToString());
126 Markdown.AppendLine(" |");
127 Markdown.Append("| e-Mail: | <");
128 Markdown.Append(EMail);
129 Markdown.AppendLine("> |");
130
131 await XmppServerModule.AppendRemoteEndPointToTable(Markdown, RemoteEndPoint);
132
133 Markdown.Append("| Date | ");
134 Markdown.Append(MarkdownDocument.Encode(Now.ToShortDateString()));
135 Markdown.AppendLine(" |");
136 Markdown.Append("| Time | ");
137 Markdown.Append(MarkdownDocument.Encode(Now.ToLongTimeString()));
138 Markdown.AppendLine(" |");
139
140 await Gateway.SendNotification(Markdown.ToString());
141 }
142
143 return NewKey;
144 }
145 }
146}
Contains information about a response to a content request.
bool HasError
If an error occurred.
object Decoded
Decoded object.
Contains a markdown document. This markdown document class supports original markdown,...
static string Encode(string s)
Encodes all special characters in a string so that it can be included in a markdown document without ...
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:147
static IUser AssertUserAuthenticated(HttpRequest Request, string Privilege)
Makes sure a request is being made from a session with a successful user login.
Definition: Gateway.cs:3868
static byte[] NextBytes(int NrBytes)
Generates an array of random bytes.
Definition: Gateway.cs:4335
static Task SendNotification(Graph Graph)
Sends a graph as a notification message to configured notification recipients.
Definition: Gateway.cs:4677
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
HttpFieldReferer Referer
Referer HTTP Field header. (RFC 2616, §14.36)
Represents an HTTP request.
Definition: HttpRequest.cs:22
HttpRequestHeader Header
Request header.
Definition: HttpRequest.cs:182
string RemoteEndPoint
Remote end-point.
Definition: HttpRequest.cs:243
bool HasData
If the request has data.
Definition: HttpRequest.cs:113
async Task< ContentResponse > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:139
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:23
async Task SendResponse()
Sends the response back to the client. If the resource is synchronous, there's no need to call this m...
Base class for all synchronous HTTP resources. A synchronous resource responds within the method hand...
The response to the request can be found under a different URI and SHOULD be retrieved using a GET me...
Static interface for database persistence. In order to work, a database provider has to be assigned t...
Definition: Database.cs:21
static Task< IEnumerable< object > > Find(string Collection, params string[] SortOrder)
Finds objects in a given collection.
Definition: Database.cs:238
static async Task Insert(object Object)
Inserts an object into the default collection of the database.
Definition: Database.cs:97
This filter selects objects that have a named field equal to a given value.
Contains methods for simple hash calculations.
Definition: Hashes.cs:57
static string BinaryToString(byte[] Data)
Converts an array of bytes to a string with their hexadecimal representations (in lower case).
Definition: Hashes.cs:63
Provides the user with options to control notifications from the Broker.
static BrokerNotificationConfiguration Instance
Current instance of configuration.
bool ApiKeyCreated
If a notification should be sent when an API key has been created.
bool AllowsPOST
If the POST method is allowed.
Definition: CreateApiKey.cs:26
async Task POST(HttpRequest Request, HttpResponse Response)
Executes the POST method on the resource.
Definition: CreateApiKey.cs:28
Service Module hosting the XMPP broker and its components.
static async Task AppendRemoteEndPointToTable(StringBuilder Markdown, string RemoteEndPoint)
Appends annotated information about a remote endpoint to a Markdown table.
POST Interface for HTTP resources.