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;
2using System.Collections.Generic;
3using System.Security.Cryptography;
4using System.Text;
5using System.Threading.Tasks;
11using Waher.Security;
13
15{
17 {
18 public CreateApiKey()
19 : base("/CreateApiKey")
20 {
21 }
22
23 public override bool HandlesSubPaths => false;
24 public override bool UserSessions => true;
25 public bool AllowsPOST => true;
26
27 public async Task POST(HttpRequest Request, HttpResponse Response)
28 {
29 Gateway.AssertUserAuthenticated(Request, "Admin.Broker.Keys");
30
31 if (!Request.HasData)
32 throw new BadRequestException();
33
34 object Obj = await Request.DecodeDataAsync();
35 if (!(Obj is Dictionary<string, string> Form))
36 throw new BadRequestException();
37
38 string Owner;
39 string EMail;
40
41 if (!Form.ContainsKey("Owner") || string.IsNullOrEmpty(Owner = Form["Owner"]))
42 throw new BadRequestException();
43
44 if (!Form.ContainsKey("EMail") || string.IsNullOrEmpty(EMail = Form["EMail"]))
45 throw new BadRequestException();
46
47 if (!Form.ContainsKey("MaxAccounts") || !long.TryParse(Form["MaxAccounts"], out long MaxAccounts) || MaxAccounts < 1)
48 throw new BadRequestException();
49
50 await Create(MaxAccounts, Owner, EMail, Request.RemoteEndPoint);
51
52 if (!(Request.Header.Referer is null))
53 throw new SeeOtherException(Request.Header.Referer.Value); // PRG pattern.
54 }
55
56 internal static async Task<ApiKey> Create(long MaxAccounts, string Owner, string EMail, string RemoteEndpoint)
57 {
58 byte[] Data;
59 string Key;
60 string Secret;
61 bool Found;
62
63 do
64 {
65 Data = Gateway.NextBytes(32);
66 Key = Hashes.BinaryToString(Data);
67
68 Found = false;
69 foreach (ApiKey ApiKey in await Database.Find<ApiKey>(new FilterFieldEqualTo("Key", Key)))
70 {
71 Found = true;
72 break;
73 }
74 }
75 while (Found);
76
77 Data = Gateway.NextBytes(32);
78 Secret = Hashes.BinaryToString(Data);
79
80 ApiKey NewKey = new ApiKey()
81 {
82 Key = Key,
83 Secret = Secret,
84 Owner = Owner,
85 EMail = EMail,
86 Created = DateTime.Now,
87 MaxAccounts = MaxAccounts
88 };
89
90 await Database.Insert(NewKey);
91
92 StringBuilder Markdown = new StringBuilder();
93 DateTime Now = DateTime.Now;
94
95 Markdown.AppendLine("API Key created:");
96 Markdown.AppendLine();
97 Markdown.AppendLine("| API Key Information ||");
98 Markdown.AppendLine("|:-----|:------|");
99 Markdown.Append("| Key: | `");
100 Markdown.Append(Key);
101 Markdown.AppendLine("` |");
102 Markdown.Append("| Owner: | `");
103 Markdown.Append(Owner);
104 Markdown.Append("`");
105 Markdown.AppendLine(" |");
106 Markdown.Append("| \\#Accounts: | ");
107 Markdown.Append(MaxAccounts.ToString());
108 Markdown.AppendLine(" |");
109 Markdown.Append("| e-Mail: | <");
110 Markdown.Append(EMail);
111 Markdown.AppendLine("> |");
112
113 await XmppServerModule.AppendRemoteEndpointToTable(Markdown, RemoteEndpoint);
114
115 Markdown.Append("| Date | ");
116 Markdown.Append(MarkdownDocument.Encode(Now.ToShortDateString()));
117 Markdown.AppendLine(" |");
118 Markdown.Append("| Time | ");
119 Markdown.Append(MarkdownDocument.Encode(Now.ToLongTimeString()));
120 Markdown.AppendLine(" |");
121
122 await Gateway.SendNotification(Markdown.ToString());
123
124 return NewKey;
125 }
126 }
127}
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:126
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:3041
static byte[] NextBytes(int NrBytes)
Generates an array of random bytes.
Definition: Gateway.cs:3534
static Task SendNotification(Graph Graph)
Sends a graph as a notification message to configured notification recipients.
Definition: Gateway.cs:3826
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:18
HttpRequestHeader Header
Request header.
Definition: HttpRequest.cs:134
string RemoteEndPoint
Remote end-point.
Definition: HttpRequest.cs:195
bool HasData
If the request has data.
Definition: HttpRequest.cs:74
async Task< object > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:95
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:21
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:19
static Task< IEnumerable< object > > Find(string Collection, params string[] SortOrder)
Finds objects in a given collection.
Definition: Database.cs:247
static async Task Insert(object Object)
Inserts an object into the default collection of the database.
Definition: Database.cs:95
This filter selects objects that have a named field equal to a given value.
Contains methods for simple hash calculations.
Definition: Hashes.cs:59
static string BinaryToString(byte[] Data)
Converts an array of bytes to a string with their hexadecimal representations (in lower case).
Definition: Hashes.cs:65
bool AllowsPOST
If the POST method is allowed.
Definition: CreateApiKey.cs:25
async Task POST(HttpRequest Request, HttpResponse Response)
Executes the POST method on the resource.
Definition: CreateApiKey.cs:27
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.