示例#1
0
        public async Task <GenericResult <Common.LoadResult, Vault> > Load(
            ISerialiser serialiser,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            bool exists = await Native.Native.FileHandler.Exists(FullPath);

            if (exists)
            {
                Byte[] encrypted = await Native.Native.FileHandler.ReadAsync(FullPath);

                Vault             vault  = (Vault)serialiser.Read(encrypted, masterPassphrase, parameters);
                Common.LoadResult result = vault != null ? Common.LoadResult.Success : Common.LoadResult.UnknownError;
                if (result == Common.LoadResult.Success)
                {
                    vault.SetSaveParams(serialiser,
                                        FullPath,
                                        masterPassphrase,
                                        false);
                    vault.SetLoaded();
                }
                return(new GenericResult <Common.LoadResult, Vault>(result, vault));
            }
            else
            {
                return(new GenericResult <Common.LoadResult, Vault>(Common.LoadResult.FileNotFound, null));
            }
        }
        public object Read(
            object data,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            FormatVersionAttribute formatVersion = FormatVersionAttribute.GetAttributeFromType(this.GetType());

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Writing Credential from JSON using serialiser '{0}'.", formatVersion);

            JObject       dataJSON               = (JObject)data;
            String        id                     = JSONHelpers.ReadString(dataJSON, "ID");
            String        glyphKey               = JSONHelpers.ReadString(dataJSON, "GlyphKey");
            String        glyphColour            = JSONHelpers.ReadString(dataJSON, "GlyphColour");
            String        name                   = JSONHelpers.ReadString(dataJSON, "Name");
            String        description            = JSONHelpers.ReadString(dataJSON, "Description");
            String        website                = JSONHelpers.ReadString(dataJSON, "Website");
            DateTime      createdAt              = JSONHelpers.ReadDateTime(dataJSON, "CreatedAt");
            DateTime      lastUpdatedAt          = JSONHelpers.ReadDateTime(dataJSON, "LastUpdatedAt");
            DateTime      passwordLastModifiedAt = JSONHelpers.ReadDateTime(dataJSON, "PasswordLastModifiedAt", createdAt);
            String        username               = JSONHelpers.ReadString(dataJSON, "Username");
            String        password               = JSONHelpers.ReadString(dataJSON, "Password");
            JArray        tagsArray              = JSONHelpers.ReadJArray(dataJSON, "Tags", true);;
            List <String> tags                   = new List <String>();

            foreach (JValue curValue in tagsArray)
            {
                tags.Add(curValue.Value <String>());
            }
            String notes = JSONHelpers.ReadString(dataJSON, "Notes");
            List <AuditLogEntry> auditLogEntriesList = new List <AuditLogEntry>();

            if (dataJSON.ContainsKey("AuditLogEntries"))
            {
                ISerialiser auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(AuditLogEntry));
                JArray      auditLogEntries         = JSONHelpers.ReadJArray(dataJSON, "AuditLogEntries", true);
                foreach (JObject curEntry in auditLogEntries)
                {
                    AuditLogEntry entry = (AuditLogEntry)auditLogEntrySerialiser.Read(curEntry, String.Empty);
                    auditLogEntriesList.Add(entry);
                }
                if (auditLogEntriesList.Count > 0)
                {
                    auditLogEntriesList = auditLogEntriesList.OrderByDescending(ale => ale.DateTime).ToList();
                }
            }
            return(new Credential(id,
                                  glyphKey,
                                  glyphColour,
                                  name,
                                  description,
                                  website,
                                  createdAt,
                                  lastUpdatedAt,
                                  passwordLastModifiedAt,
                                  username,
                                  password,
                                  tags.ToArray(),
                                  notes,
                                  auditLogEntriesList.ToArray()));
        }
示例#3
0
        public void SequentialUpgradeTest()
        {
            Vault testVault = VaultTests.CreateRandomVault(_rng);
            IEnumerable <FormatVersionAttribute> vaultSerialisers = FormatVersions.Instance.VersionSerialisers.Keys.Where(fva => fva.ObjectType == typeof(Vault)).OrderBy(fva => double.Parse(fva.Version));

            FormatVersionAttribute[] filteredOrderedSerialisers = vaultSerialisers.ToArray();
            object curSerialised = null;
            Vault  curVault      = null;
            string lastVersion   = String.Empty;

            for (int curVersion = 0; curVersion < filteredOrderedSerialisers.Length; curVersion++)
            {
                if (curSerialised != null)
                {
                    FormatVersionAttribute prevSerialiserAttrib = filteredOrderedSerialisers[curVersion - 1];
                    ISerialiser            prevSerialiser       = FormatVersions.Instance.GetSerialiser(prevSerialiserAttrib.Version, typeof(Vault));
                    curVault = (Vault)prevSerialiser.Read(curSerialised, String.Empty);
                }
                else
                {
                    curVault = testVault;
                }
                FormatVersionAttribute nextSerialiserAttrib = filteredOrderedSerialisers[curVersion];
                lastVersion = nextSerialiserAttrib.Version;
                ISerialiser nextSerialiser = FormatVersions.Instance.GetSerialiser(nextSerialiserAttrib.Version, typeof(Vault));
                curSerialised = nextSerialiser.Write(curVault, String.Empty);
            }
            Assert.IsTrue(lastVersion == Framework.Serialisers.JSON.Common.LATEST_VAULT_VERSION);
            ISerialiser latestSerialiser = FormatVersions.GetLatestSerialiser(typeof(Vault));

            curVault = (Vault)latestSerialiser.Read(curSerialised, String.Empty);
            Assert.IsTrue(curVault.CompareTo(testVault) == 0);
        }
        public object Read(
            object data,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            FormatVersionAttribute formatVersion = FormatVersionAttribute.GetAttributeFromType(this.GetType());

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Reading Vault from JSON using serialiser '{0}'.", formatVersion);

            JObject dataJSON = (JObject)data;

            String            id             = JSONHelpers.ReadString(dataJSON, "ID");
            String            name           = JSONHelpers.ReadString(dataJSON, "Name");
            String            description    = JSONHelpers.ReadString(dataJSON, "Description");
            DateTime          createdAt      = JSONHelpers.ReadDateTime(dataJSON, "CreatedAt");
            DateTime          lastUpdatedAt  = JSONHelpers.ReadDateTime(dataJSON, "LastUpdatedAt");
            List <Credential> credentialList = new List <Credential>();

            ISerialiser credentialSerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(Credential));
            JArray      credentials          = JSONHelpers.ReadJArray(dataJSON, "Credentials", true);

            foreach (JObject curCredential in credentials)
            {
                Credential credential = (Credential)credentialSerialiser.Read(curCredential, String.Empty);
                credentialList.Add(credential);
            }
            List <AuditLogEntry> auditLogEntriesList = new List <AuditLogEntry>();

            if (dataJSON.ContainsKey("AuditLogEntries"))
            {
                ISerialiser auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(AuditLogEntry));
                JArray      auditLogEntries         = JSONHelpers.ReadJArray(dataJSON, "AuditLogEntries", true);
                foreach (JObject curEntry in auditLogEntries)
                {
                    AuditLogEntry entry = (AuditLogEntry)auditLogEntrySerialiser.Read(curEntry, String.Empty);
                    auditLogEntriesList.Add(entry);
                }
                if (auditLogEntriesList.Count > 0)
                {
                    auditLogEntriesList = auditLogEntriesList.OrderByDescending(ale => ale.DateTime).ToList();
                }
            }
            return(new Vault(id,
                             name,
                             description,
                             createdAt,
                             lastUpdatedAt,
                             credentialList.ToArray(),
                             auditLogEntriesList.ToArray()));
        }
示例#5
0
        public object Read(
            object data,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Reading Vault from JObject.");

            JObject dataJSON      = (JObject)data;
            JObject header        = JSONHelpers.ReadJObject(dataJSON, "Header", true);
            string  formatVersion = header["FormatVersion"].Value <String>();

            ISerialiser serialiser = FormatVersions.Instance.GetSerialiser(formatVersion, typeof(Vault));

            return(serialiser.Read(
                       data,
                       masterPassphrase, parameters));
        }
示例#6
0
        public void ToAndFromJSON()
        {
            String name = String.Empty;
            String type = String.Empty;

            AuditLogEntry.EntryType entryType = AuditLogEntry.EntryType.None;

            AuditLogEntry random = CreateRandomAuditLogEntry(_rng,
                                                             out name,
                                                             out type,
                                                             out entryType);

            DateTime dateTime = random.DateTime;

            ISerialiser   auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(devoctomy.cachy.Framework.Serialisers.JSON.Common.LATEST_VAULT_VERSION, typeof(AuditLogEntry));
            JObject       json     = (JObject)auditLogEntrySerialiser.Write(random, String.Empty);
            AuditLogEntry fromJSON = (AuditLogEntry)auditLogEntrySerialiser.Read(json, String.Empty);

            Assert.IsTrue(random.CompareTo(fromJSON) == 0);
        }
示例#7
0
        public void JSONSerialiser()
        {
            string   id                     = String.Empty;
            string   glyphKey               = String.Empty;
            string   glyphColour            = String.Empty;
            string   name                   = String.Empty;
            string   description            = String.Empty;
            string   website                = String.Empty;
            DateTime createdAt              = DateTime.MinValue;
            DateTime lastUpdatedAt          = DateTime.MinValue;
            DateTime passwordLastModifiedAt = DateTime.MinValue;
            string   username               = String.Empty;
            string   password               = String.Empty;

            string[] tags  = null;
            string   notes = String.Empty;

            AuditLogEntry[] auditLogEntries = null;

            Credential credential = CreateRandomCredential(_rng,
                                                           out id,
                                                           out glyphKey,
                                                           out glyphColour,
                                                           out name,
                                                           out description,
                                                           out website,
                                                           out createdAt,
                                                           out lastUpdatedAt,
                                                           out passwordLastModifiedAt,
                                                           out username,
                                                           out password,
                                                           out tags,
                                                           out notes,
                                                           out auditLogEntries);

            ISerialiser serialiser         = FormatVersions.GetLatestSerialiser(typeof(Credential));
            JObject     json               = (JObject)serialiser.Write(credential, String.Empty);
            Credential  credentialReloaded = (Credential)serialiser.Read(json, String.Empty);

            Assert.IsTrue(credential.CompareTo(credentialReloaded) == 0);
        }
示例#8
0
        /// <summary>
        /// Read an object from a target stream using a certain serialiser.
        /// All related objects along the object graph are properly restored using the <see cref="ISerialisationNotifier"/> contract.
        /// </summary>
        /// <param name="target">The target stream.</param>
        /// <param name="serialiser">The serialiser.</param>
        /// <param name="verbose">Optionally indicate where the log messages should written to (verbose = Info, otherwise Debug).</param>
        /// <returns>The read object of the requested type.</returns>
        public static T Read <T>(Stream target, ISerialiser serialiser, bool verbose = true)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (serialiser == null)
            {
                throw new ArgumentNullException(nameof(serialiser));
            }

            LoggingUtils.Log(verbose ? Level.Info : Level.Debug, $"Reading {typeof(T).Name} from target stream {target} using serialiser {serialiser}...", ClazzLogger);

            Stopwatch stopwatch      = Stopwatch.StartNew();
            long      beforePosition = target.Position;

            object read = serialiser.Read(target);

            if (!(read is T))
            {
                throw new SerializationException($"Unable to read {typeof(T).Name} from target {target} using serialiser {serialiser}, read object {read} was not of the requested type.");
            }

            TraverseObjectGraph(read, new HashSet <object>(), (parent, field, obj) =>
            {
                // automatically restore all logger instances
                if (field.FieldType == typeof(ILog))
                {
                    field.SetValue(parent, LogManager.GetLogger(Assembly.GetCallingAssembly(), parent.GetType().Namespace + "." + parent.GetType().Name));
                }

                (obj as ISerialisationNotifier)?.OnDeserialised();
            });

            LoggingUtils.Log(verbose ? Level.Info : Level.Debug, $"Done reading {typeof(T).Name} {read} from target stream {target} using serialiser {serialiser}, " +
                             $"read {((target.Position - beforePosition) / 1024.0):#.#}kB, took {stopwatch.ElapsedMilliseconds}ms.", ClazzLogger);

            return((T)read);
        }