OwinContext.Request multi-part/form-data parsing? - forms

Is there an easy way to parse multi-part/form-data information from an OwinContext.Request instance?
I know how to do this using HttpContext.Current.Request.Form.Get(), but I'm not sure if I really want to be doing that in the Owin pipeline.
I know I can use .ReadFormAsync() to get an IFormCollection, which appears to work fine for standard submits, but with a multi-part/form-data post the boundary value, content type, and variable name are all getting rolled into the key. So I can't just do formVars.Get("VariableName"), because it's not the variable name, it's a composite. Seems like it shouldn't be doing that though... right?
public AppFunc PreAuthMiddleware(AppFunc next) {
AppFunc appFunc = async (IDictionary<string, object> environment) => {
IOwinContext context = new OwinContext(environment);
IFormCollection formVars = await context.Request.ReadFormAsync();
... Now What ...
await next.Invoke(environment);
};
return appFunc;
}
I was hoping that accessing form variables and file data would be as easy as it was with HttpContext, but it seems there may be more work to be done.
If anyone has any insight on this, please let me know. Otherwise I'll probably just end up hacking the key names together if I see the main content-type is multi-part/form-data.

Related

Flutter 1.22 Internationalization with variable as key

I implemented the new (official) localization for Flutter (https://pascalw.me/blog/2020/10/02/flutter-1.22-internationalization.html) and everything is working fine, except that I don't know how to get the translation for a variable key.
The translation is in the ARB file, but how can I access it?
Normally I access translations using Translations.of(context).formsBack, but now I would like to get the translation of value["labels"]["label"].
Something like Translations.of(context).(value["labels"]["label"]) does not work of course.
I don't think this is possible with gen_l10n. The code that is generated by gen_l10n looks like this (somewhat abbreviated):
/// The translations for English (`en`).
class TranslationsEn extends Translations {
TranslationsEn([String locale = 'en']) : super(locale);
#override
String get confirmDialogBtnOk => 'Yes';
#override
String get confirmDialogBtnCancel => 'No';
}
As you can see it doesn't generate any code to perform a dynamic lookup.
For most cases code generation like this is a nice advantage since you get auto completion and type safety, but it does mean it's more difficult to accommodate these kinds of dynamic use cases.
The only thing you can do is manually write a lookup table, or choose another i18n solution that does support dynamic lookups.
A lookup table could look something like this. Just make sure you always pass in the current build context, so the l10n code can lookup the current locale.
class DynamicTranslations {
String get(BuildContext context, String messageId) {
switch(messageId) {
case 'confirmDialogBtnOk':
return Translations.of(context).confirmDialogBtnOk;
case 'confirmDialogBtnCancel':
return Translations.of(context).confirmDialogBtnCancel;
default:
throw Exception('Unknown message: $messageId');
}
}
}
To provide an example for https://stackoverflow.com/users/5638943/kristi-jorgji 's answer (which works fine):
app_en.arb ->
{
"languages": "{\"en\": \"English\", \"ro\": \"Romanian\"}"
}
localization_controller.dart ->
String getLocaleName(BuildContext ctx, String languageCode) {
return jsonDecode(AppLocalizations.of(ctx)!.languages)[languageCode];
}
getLocaleName(context, 'ro') -> "Romanian"
You can store a key in translation as json string.
Then you read it, parse it to Map<string,string> and access dynamically what you need.
Been using this approach with great success

Reading attributes from private key

I'm trying to use Pkcs11Interop to sign a message using the private key from a smart card certificate in a C# application. The smart card we are using contain multiple certificates - usually one is for signing, and one is for authentication. If I were using X509Certificate2, I'd filter certificates based on the X509KeyUsageFlags I'm looking for. I'm struggling to figure out how to approach this using PKCS11.
The code I'm starting with is below. When I call session.FindAllObjects, I'm getting 2 certificates in the result (which is expected, since that is how many certificates are on the smart card.)
I've tried using GetAttributeValue to read various attributes and see if I can use those to identify the correct certificate - strangely, they all return null/0 values. Querying the CKA_SENSITIVE attribute returns True (which is, again, expected), but apparently I cannot read other attributes from the objects.
Am I doing something incorrect in my usage of GetAttributeValue? Or is there some other way I should be approaching this problem?
public byte[] SignMessage(byte[] message, string pin)
{
var factories = new Pkcs11InteropFactories();
using (IPkcs11Library pkcs11Library = factories.Pkcs11LibraryFactory.LoadPkcs11Library(factories, DriverPath, AppType.SingleThreaded))
{
ISlot slot = GetSlot(pkcs11Library);
if (slot == null)
{
return null;
}
using (ISession session = slot.OpenSession(SessionType.ReadWrite))
{
session.Login(CKU.CKU_USER, pin);
var searchTemplate = new List<IObjectAttribute> {
factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY),
factories.ObjectAttributeFactory.Create(CKA.CKA_KEY_TYPE, CKK.CKK_RSA),
factories.ObjectAttributeFactory.Create(CKA.CKA_SIGN, true),
};
List<IObjectHandle> foundObjects = session.FindAllObjects(searchTemplate); // foundObjects.Count = 2!
IObjectHandle privateKey = foundObjects.FirstOrDefault();
var readResult = session.GetAttributeValue(privateKey, new List<CKA>() { CKA.CKA_LABEL });
var label = readResult[0].GetValueAsString(); // label ends up being null!
byte[] result = null;
using (IMechanism signingMechanism = session.Factories.MechanismFactory.Create(CKM.CKM_SHA256_RSA_PKCS))
{
result = session.Sign(signingMechanism, privateKey, message);
}
session.DestroyObject(privateKey);
session.Logout();
return result;
}
}
}
I came up with a solution through trial-and-error that seems to function correctly. I'm not sure if this is the correct approach, since it seems quite convoluted, so any feedback would be appreciated. I discovered that the contents of the card include a variety of objects, and a single key pair consists of three objects: a CKO_CERTIFICATE object (which seems to contain the brunt of the metadata about the certificate/keypair), a CKO_PRIVATE_KEY object and a CKO_PUBLIC_KEY object. Each of these has the CKA_ID property populated, and the objects that are part of the same key pair should have the same CKA_ID.
So I built a CertificateWrapper wrapper class to hold references to each of the three objects. I then looped over all objects on the smart card, and built CertificateWrapper objects for each unique key pair.
Then, I was able to construct an X509Certificate2 object using the CKA_VALUE attribute on the CKO_CERTIFICATE object. From there, I was able to build a X509Certificate2Collection object using an array of all of the X509Certificate2 objects I made. I could then use the .Find method (or any other method I wanted) on X509Certificate2Collection to filter down to the particular certificate I was looking for.
Once I had the X509Certificate2 object I was looking for, I was able to map it back to the CertificateWrapper object by matching the serial number from the X509Certificate2 against the CKA_SERIAL_NUMBER attribute from the CKO_CERTIFICATE object. Finally, I was able to use the CKO_PRIVATE_KEY object associated with that CKO_CERTIFICATE to do the signing operation.
Like I said, this seems very round-about, but seemed to allow me to find the correct certificate/key pair I needed for my specific workflow. Hope this explanation might be useful to someone, and I also welcome any feedback on problems with this approach and/or better ways to handle this.

What does `namespaceMappings` mean in Word.CustomXMLPart API

I have created a small snippet in Script Lab which basically:
Creates a custom XML:
<AP xmlns="accordproject.org">
<template xmlns="acceptance-of-delivery">
<shipper>Aman Sharma</shipper>
</template>
</AP>
Tries to query this xml by using the xPath /AP/template. I run this block of code:
await Word.run(async context => {
const customXmlParts = context.document.customXmlParts;
const AP = customXmlParts.getByNamespace("accordproject.org").getOnlyItemOrNullObject();
await context.sync();
const nodes = AP.query('/AP/template', {}); // how does this work?
await context.sync();
console.log(nodes);
})
Deletes the customXML.
The second argument of query API is namespaceMappings. I think I am passing that incorrectly and that's why I get this as ouput (empty object).
But when I pass * instead of /AP/template, I get the whole XML (while the second argument, namespaceMappings remain the same).
Where am I going wrong? Can anyone share some snippets to help me query customXML.
The short answer is that you can use
const nodes = AP.query("/n1:AP/n2:template", {n1:"accordproject.org", n2:"acceptance-of-delivery"});
I don't know JS/TS at all but I assume these are basically key-value pairs of some kind. You can also use
const nodes = AP.query("/n1:AP/n2:template", {"n1":"accordproject.org", "n2":"acceptance-of-delivery"});
if you prefer to think of the Namespace prefixes as strings.
(For anyoneunfamiliar, the "n1" and "n2" are just prefixes that you invent so you can reference the full Namespace URIs. They don't have anything to do with any prefixes you might have used in the piece of XML you are querying.)
I couldn't find documentation on this either and originally assumed you might need something more like { Prefix:"ns1", namespaceURI:"the namespace URI" }, but that's just because those are the property names used in the VBA model.

Recommended data flow (import/export)

I have a flutter application which (simply put) list some data on various screens and can be modified. My current data approach works, but I feel it is not a best practice or optimal.
Currently, when a object is saved, it is converted to JSON (using dart:convert) and stored in a file on the device (using dart.io), overriding the file if it exist. Every screen that needs to display these objects reads the file to get the objects. Every time there is a change that needs to be saved, it exports everything (overwrites) again then imports it again to display it.
The reason I chose JSON over S is because I want to add a web portion later. Does this approach of reading/writing a best practice? I feel this much reading/writing of all the data for most screens could cause some performance issues.
Any advice is appreciated!
This is a possible way to keep data in-memory and write to disk when changes are made to your datamodel/settings.
I use RxDart myself. You don't need it per se, although it does make life easier. I'll be simplifying the examples below, so you get to know the concept and apply it to your own needs.
Let say you keep track of data in your settings class:
#JsonSerializable()
class Settings {
String someData1;
String someData2;
// json seriazable functions
}
You need a "handler"1 or something similar that manages changes made to your Settings and also to read/write data:
class SettingsHandler {
Settings _settings;
StreamController<Settings> _settingsController = BehaviorSubject<Settings>();
StreamController<String> _data1Controller = BehaviorSubject<String>();
StreamSink<String> get data1Input => _data1Controller.sink;
Observable<String> get data1Output => Observable(_data1Controller.stream);
Future<Settings> _readFromDisk() async {
// do your thing
}
Future<Settings> _writeToDisk(Settings settings) async {
// do your thing
}
Future<void> init() async {
// read from disk
_settings = await _readFromDisk();
_settingsController.sink.add(_settings);
// initialize data
data1Input.add(_settings.someData1);
data1Output
.skip(1) // we skip because we just added our initialization data above.
.listen((value) =>
// we must propagate through the update function
// otherwise nothing gets written to disk
update((settings) => settings.someData1 = value)
);
// when changes are made, it needs to notify this stream
// so everything can be written to disk
_settingsSaver.output
// save settings every 2.5 seconds when changes occur.
.debounceTime(const Duration(milliseconds: 2500))
// get the changes and write to disk
.listen((settings) => _writeToDisk(settings));
}
// this function is crucial as it allows changes to be made via the [adjustFunc]
// and then propagates this into the _settingsSaver stream.
void update(void Function(Settings input) adjustFunc) {
adjustFunc(_settings);
_settingsSaver.sink.add(_settings);
}
}
So now you can do something like
var handler = SettingsHandler();
await handler.init();
// this
handler.data1Input.add('NewData');
// or this
handler.update((settings) {
settings.someData1 = 'NewData';
});
Remember, this code only shows how the concept can work. You need to change it for your situation. You could also decide to not expose data1Input or the update(...) function, this is up to your own design.
1 I personally use BloC, your situation might require a different way.

How to PUT (save) object to REST endpoint using Restangular

Given I have resource id and data as plain JSON, how do I save that JSON to /cars/123/ ???
There seem to be no clear explanation. I don't have restangular element.
restangularizeElement might be the option, but it lacks any meaningful documentation.
All I know is that I want to save {make: 'honda', color: 'now blue, was red'} for car_id == 123.
Thanks.
If you have plain object you cannot use Restangular save function to update (it will make put request as object has id) object.
Easiest way to achieve it construct your end point url then call put function...
Restangular.one('cars', 123).customPUT(carObject).then(function(response){
TO-DO
})
If you want to restangularized your plain object you can use this one...
Restangular.restangularizeElement(null,carObject, 'cars').put().then(function (response) {
TO-DO
})
The comman way should be like this. Whenever you get object from backend with get or getList your object will be Restangularized unless you do not choose to turn them plain object by calling .plain() method of Restangular response. Then you can safely call .save() and it will automatically will be put or post accordingly...
Here is what worked for me. Thanks to #wickY26:
updateGroup: function (group, id_optional) {
if (!group.hasOwnProperty('restangularCollection')) {
// safe to assume it is NOT restangular element; sadly instanceof won't work here
// since there is no element class
// need to restangularize
group = Restangular.restangularizeElement(null, group, ENDPOINT);
group.id = id_optional;
}
return group.put();
},