Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
ProposeTemplate.cs
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Threading.Tasks;
5using System.Xml;
6using Waher.Content;
8using Waher.Events;
12using Waher.Script;
18
20{
25 {
30 : base("Legal/ProposeTemplate",
31 new KeyValuePair<Type, Expression>(typeof(Dictionary<string, object>), new Expression(jsonPattern)),
32 new KeyValuePair<Type, Expression>(typeof(XmlDocument), new Expression(xmlPattern)))
33 {
34 }
35
36 private static readonly string jsonPattern = Resources.LoadResourceAsText(typeof(ProposeTemplate).Namespace + ".JSON.ProposeTemplate.req");
37 private static readonly string xmlPattern = Resources.LoadResourceAsText(typeof(ProposeTemplate).Namespace + ".XML.ProposeTemplate.req");
38
47 public override async Task POST(HttpRequest Request, HttpResponse Response, Dictionary<string, IElement> Parameters)
48 {
50
51 string TemplateBase64 = (string)Parameters["PTemplateBase64"].AssociatedObjectValue;
52 byte[] TemplateBin;
53 string TemplateXmlString;
54 XmlDocument TemplateXml;
55 ParsedContract Parsed;
56 Contract Template;
57
58 try
59 {
60 TemplateBin = Convert.FromBase64String(TemplateBase64);
61 }
62 catch (Exception)
63 {
64 throw new BadRequestException("Invalid BASE64-encoding of template.");
65 }
66
67 try
68 {
69 TemplateXmlString = CommonTypes.GetString(TemplateBin, Encoding.UTF8);
70
71 TemplateXml = new XmlDocument()
72 {
73 PreserveWhitespace = true
74 };
75
76 TemplateXml.LoadXml(TemplateXmlString);
77 }
78 catch (Exception ex)
79 {
80 throw new BadRequestException("Invalid template XML, or encoding of template XML: " + ex.Message);
81 }
82
83 try
84 {
85 Parsed = await Contract.Parse(TemplateXml.DocumentElement, XmppServerModule.Legal);
86 }
87 catch (Exception ex)
88 {
89 throw new BadRequestException("Unable to parse contract XML: " + ex.Message);
90 }
91
92 Template = Parsed.Contract
93 ?? throw new BadRequestException("Unable to parse contract XML.");
94
95 if (Parsed.HasStatus)
96 throw new BadRequestException("Status element not permitted when creating new contract.");
97
99 throw new BadRequestException("id attribute must not be set by client.");
100
101 if (!(Template.ClientSignatures is null) && Template.ClientSignatures.Length > 0)
102 throw new BadRequestException("Predefined signatures not permitted.");
103
104 if (!(Template.ServerSignature is null))
105 throw new BadRequestException("Server signature cannot be provided by client.");
106
107 if (Template.PartsMode == ContractParts.ExplicitlyDefined && (Template.Parts is null || Template.Parts.Length == 0))
108 throw new BadRequestException("No explicit parts defined.");
109
110 if (Template.PartsMode != ContractParts.TemplateOnly)
111 throw new BadRequestException("Contract is not a template.");
112
113 if (Template.Duration <= Duration.Zero)
114 throw new BadRequestException("Contract duration must be positive.");
115
116 CaseInsensitiveString LegalDomain;
117
118 if (XmppServerModule.Legal is null)
119 LegalDomain = "legal.example.com";
120 else
121 {
122 string Errors = await XmppServerModule.Legal?.CheckContentIntegrity(Template);
123 if (!string.IsNullOrEmpty(Errors))
124 throw new BadRequestException(Errors);
125
126 LegalIdentity Identity = await XmppServerModule.Legal.GetCurrentApprovedLegalIdentityAsync(User.UserName)
127 ?? throw new ForbiddenException("No current approved legal identity found for account.");
128
129 Errors = await XmppServerModule.Legal.ValidateContent(Template);
130 if (!string.IsNullOrEmpty(Errors))
131 throw new BadRequestException(Errors);
132
133 LegalDomain = Identity.Provider;
134 }
135
136 Template.State = ContractState.Proposed;
137 Template.Provider = LegalDomain;
138 Template.Account = User.UserName;
139 Template.Created = LegalComponent.NowSecond;
140 Template.Updated = DateTime.MinValue;
141
142 await Database.Insert(Template);
143
144 Template.ContractId = Template.ObjectId + "@" + Template.Provider;
145 Template.Sign(XmppServerModule.Legal);
146
147 await Database.Update(Template);
148
149 KeyValuePair<string, object>[] Tags = Template.GetTags();
150 string FromJid = User.UserName + "@" + Request.Host;
151
152 Log.Informational("Contract proposal registered.",
153 Template.ContractId.Value, FromJid, "ContractRegistered", Tags);
154
155 StringBuilder Markdown = new StringBuilder();
156
157 Markdown.Append("Contract proposal received: [");
158 Markdown.Append(MarkdownDocument.Encode(Template.ContractId));
159 Markdown.Append("](");
160 Markdown.Append(Gateway.GetUrl("/Contract.md?ID=" + Template.ContractId));
161 Markdown.AppendLine(")");
162 Markdown.AppendLine();
163 LegalComponent.Output(Markdown, Tags);
164
165 await Gateway.SendNotification(Markdown.ToString());
166
167 XmppServerModule.Legal?.ContractAuthorization(FromJid, FromJid, Template.ContractId, true);
168
169 if (!(XmppServerModule.Legal is null))
170 await XmppServerModule.Legal.SendContractUpdatedEvent(Template, true);
171
172 StringBuilder Xml = new StringBuilder();
173 Template.Serialize(Xml, true, true, true, true, true, true, true, null, XmppServerModule.Legal);
174 TemplateXmlString = Xml.ToString();
175
176 TemplateXml = new XmlDocument()
177 {
178 PreserveWhitespace = true
179 };
180 TemplateXml.LoadXml(TemplateXmlString);
181
182 await Response.Return(new NamedDictionary<string, object>("TemplateResponse", AgentNamespace)
183 {
184 { "Template", TemplateXml },
185 });
186 }
187
188 }
189}
Helps with parsing of commong data types.
Definition: CommonTypes.cs:13
static string GetString(byte[] Data, Encoding DefaultEncoding)
Gets a string from its binary representation, taking any Byte Order Mark (BOM) into account.
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 ...
A Named dictionary is a dictionary, with a local name and a namespace. Use it to return content that ...
Static class managing loading of resources stored as embedded resources or in content files.
Definition: Resources.cs:15
static string LoadResourceAsText(string ResourceName)
Loads a text resource from an embedded resource.
Definition: Resources.cs:96
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:13
static void Informational(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an informational event.
Definition: Log.cs:334
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:126
static Task SendNotification(Graph Graph)
Sends a graph as a notification message to configured notification recipients.
Definition: Gateway.cs:3826
static string GetUrl(string LocalResource)
Gets a URL for a resource.
Definition: Gateway.cs:4167
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
The server understood the request, but is refusing to fulfill it. Authorization will not help and the...
Represents an HTTP request.
Definition: HttpRequest.cs:18
string Host
Host reference. (Value of Host header, without the port number)
Definition: HttpRequest.cs:215
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:21
async Task Return(object Object)
Returns an object to the client. This method can only be called once per response,...
Represents a case-insensitive string.
string Value
String-representation of the case-insensitive string. (Representation is case sensitive....
static bool IsNullOrEmpty(CaseInsensitiveString value)
Indicates whether the specified string is null or an CaseInsensitiveString.Empty string.
Static interface for database persistence. In order to work, a database provider has to be assigned t...
Definition: Database.cs:19
static async Task Update(object Object)
Updates an object in the database.
Definition: Database.cs:626
static async Task Insert(object Object)
Inserts an object into the default collection of the database.
Definition: Database.cs:95
Class managing a script expression.
Definition: Expression.cs:39
Abstract base class for agent resources supporting the POST method.
static AccountUser AssertUserAuthenticated(HttpRequest Request)
Makes sure the request is made by an authenticated API user.
const string AgentNamespace
https://waher.se/Schema/BrokerAgent.xsd
Service Module hosting the XMPP broker and its components.
Represents a duration value, as defined by the xsd:duration data type: http://www....
Definition: Duration.cs:13
static readonly Duration Zero
Zero value
Definition: Duration.cs:532