Exemplo n.º 1
0
        /// <summary>
        /// Attempts to authenticate a IoT application using an API key.
        /// </summary>
        /// <param name="data">The <see cref="ApiKeyData"/> needed to authentication as a JSON string.</param>
        /// <param name="subject">The subject, which is the API key ID.</param>
        /// <param name="roles">No roles will be set using this authentication method.</param>
        /// <param name="rights">The rights associated to the API key.</param>
        /// <returns>Returns whether authentication was successful.</returns>
        /// <exception cref="MalformedAuthenticationDataException">Thrown if the passed data doesn't match the expected model.</exception>
        public bool TryAuthenticate(string data, out string subject, out IEnumerable <Role> roles, out IEnumerable <Right> rights)
        {
            ApiKeyData apiKeyData = ParseData <ApiKeyData>(data);

            // Initialize out-parameters
            subject = null;
            roles   = new List <Role>();
            rights  = null;

            // Look up key
            ApiKey key = ApiKeyRepository.GetApiKey(apiKeyData.ApiKey);

            if (key == null)
            {
                return(false);
            }
            subject = key.Id.ToString();
            rights  = key.Rights;

            // Check for status
            if (!key.Enabled)
            {
                return(false);
            }

            // All checks passed!
            return(true);
        }
Exemplo n.º 2
0
        public static Configuration Deserialize(byte[] data)
        {
            Configuration result;

            using (var m = new MemoryStream(data))
            {
                using (var reader = new BinaryReader(m))
                {
                    var updateinterval = reader.ReadDouble();

                    var bittrexkeylength = reader.ReadInt32();
                    var bittrexkeybytes  = reader.ReadBytes(bittrexkeylength);

                    var gdaxkeylength = reader.ReadInt32();
                    var gdaxkeybytes  = reader.ReadBytes(gdaxkeylength);

                    var binancekeylength = reader.ReadInt32();
                    var binancekeybytes  = reader.ReadBytes(binancekeylength);

                    var bittrexkey = ApiKeyData.Desserialize(bittrexkeybytes);
                    var gdaxkey    = ApiKeyData.Desserialize(gdaxkeybytes);
                    var binancekey = ApiKeyData.Desserialize(binancekeybytes);

                    result = new Configuration
                    {
                        UpdateInterval    = updateinterval,
                        BittrexApiKeyData = bittrexkey,
                        GdaxApiKeyData    = gdaxkey,
                        BinanceApiKeyData = binancekey
                    };
                }
            }
            return(result);
        }
        public static string[] ConstructRoles(string strKey)
        {
            List <string> roles = new List <string>();

            using (ValidationRepository repository = new ValidationRepository())
            {
                ApiKeyData data = repository.GetApiKey(strKey);

                if (data != null && data.Active)
                {
                    bool allowAdministration = data.AdminKey || data.Id == Constants.SYSTEM_MASTER_KEY_ID;

                    roles.Add(SecurityRoles.RoleReadDirectories(data.Application.Name));
                    roles.Add(SecurityRoles.RoleReadVersions(data.Application.Name));

                    if (data.Id == Constants.SYSTEM_MASTER_KEY_ID)
                    {
                        roles.Add(SecurityRoles.RoleCreateApplication());
                        roles.Add(SecurityRoles.RoleDeleteApplication(data.Application.Name));
                        roles.Add(SecurityRoles.RoleReadApiKeys());
                    }

                    foreach (var item in data.Access)
                    {
                        if (allowAdministration)
                        {
                            AddRoles(SecurityRoles.RoleDeleteDirectory(item.Directory.Application.Name, item.Directory.Name), roles);
                            AddRoles(SecurityRoles.RoleCreateDirectory(item.Directory.Application.Name), roles);
                            AddRoles(SecurityRoles.RoleDeleteDirectories(item.Directory.Application.Name), roles);
                            AddRoles(SecurityRoles.RoleCreateVersion(item.Directory.Application.Name), roles);
                            AddRoles(SecurityRoles.RoleDeleteVersion(item.Directory.Application.Name), roles);
                            AddRoles(SecurityRoles.RoleEditApiKey(item.Directory.Application.Name), roles);
                            AddRoles(SecurityRoles.RoleReadApiKeys(item.Directory.Application.Name), roles);
                        }

                        AddRoles(SecurityRoles.RoleReadDirectory(item.Directory.Application.Name, item.Directory.Name), roles);

                        if (item.AllowCreate)
                        {
                            AddRoles(SecurityRoles.RoleCreateSetting(item.Directory.Application.Name, item.Directory.Name), roles);
                        }

                        if (item.AllowDelete)
                        {
                            AddRoles(SecurityRoles.RoleDeleteSetting(item.Directory.Application.Name, item.Directory.Name), roles);
                        }

                        if (item.AllowWrite)
                        {
                            AddRoles(SecurityRoles.RoleWriteSetting(item.Directory.Application.Name, item.Directory.Name), roles);
                        }
                    }
                }

                return(roles.ToArray());
            }
        }
Exemplo n.º 4
0
 public void UpdateKeyData(ApiKeyData keyData)
 {
     _apiKey        = keyData;
     _authenticator = new Authenticator(
         _apiKey.GetRawApiKey(),
         _apiKey.GetRawApiSecret(),
         _apiKey.GetRawApiPassword());
     _gdaxClient  = new GDAXClient.GDAXClient(_authenticator);
     IsConfigured = true;
 }
Exemplo n.º 5
0
        public void Init(ApiKeyData keyData)
        {
            if (string.IsNullOrWhiteSpace(keyData.GetRawApiKey()))
            {
                IsConfigured = false;
            }

            UpdateKeyData(keyData);
            UpdateMarketSummary();
        }
Exemplo n.º 6
0
        public void UpdateKeyData(ApiKeyData keyData)
        {
            _apiKey = keyData;

            _client = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = _apiKey.GetRawApiKey(),
                SecretKey = _apiKey.GetRawApiSecret()
            });

            IsConfigured = true;
        }
Exemplo n.º 7
0
        public void Init(ApiKeyData keyData)
        {
            if (string.IsNullOrWhiteSpace(keyData.GetRawApiKey()))
            {
                IsConfigured = false;
                return;
            }
            _apiKey      = keyData;
            IsConfigured = true;

            UpdateMarketSummary();
        }
Exemplo n.º 8
0
        public BingTranslateService()
        {
            if (!File.Exists("Secrets/BingAPI.json"))
            {
                MessageBox.Show("No Bing API authentication found. Bing translation will be unavailable.", "Turansuraetu - Bing API", MessageBoxButton.OK,
                                MessageBoxImage.Exclamation);
                return;
            }

            ApiKeyData keyData = JsonConvert.DeserializeObject <ApiKeyData>(File.ReadAllText("Secrets/BingAPI.json"));

            _api = new MicrosoftCognitiveTranslate(keyData.key, keyData.region);
        }
Exemplo n.º 9
0
        public void UpdateKeyData(ApiKeyData keyData)
        {
            if (string.IsNullOrWhiteSpace(keyData.GetRawApiKey()))
            {
                IsConfigured = false;
                return;
            }

            _apiKey = keyData;
            _client = new BittrexClient(
                _apiKey.GetRawApiKey(),
                _apiKey.GetRawApiSecret());
        }
Exemplo n.º 10
0
                public void Good_Url(string url)
                {
                    var data = new ApiKeyData
                    {
                        Ip         = "",
                        UrlPattern = url,
                        AppStatus  = ApiKey.ApplicationStatus.Production
                    };

                    var command = new ValidateAndGetKeyTypeCommand(data);
                    var type    = CommandExecutor.ExecuteCommand(command);

                    Assert.That(type, Is.EqualTo(ApiKey.ApplicationType.Browser));
                    Assert.That(command.ErrorMessage, Is.Null);
                }
Exemplo n.º 11
0
        public void Empty_Parameters_Returns_None_with_Message()
        {
            var data = new ApiKeyData
            {
                Ip         = "",
                UrlPattern = "",
                AppStatus  = ApiKey.ApplicationStatus.Production
            };

            var command = new ValidateAndGetKeyTypeCommand(data);
            var type    = CommandExecutor.ExecuteCommand(command);

            Assert.That(type, Is.EqualTo(ApiKey.ApplicationType.None));
            Assert.That(command.ErrorMessage, Is.Not.Null);
        }
Exemplo n.º 12
0
        public static IList <T> GetList <T>(this JObject jObject, ApiKeyData key = null) where T : class
        {
            var result = key == null ? jObject : (jObject == null ? null : jObject[key.ToString()]);

            if (result == null)
            {
                return(new List <T>());
            }

            if (result is JArray)
            {
                return(result.ToObject <List <T> >());
            }

            return(new List <T>());
        }
Exemplo n.º 13
0
        public static T Get <T>(this JObject jObject, ApiKeyData key = null) where T : class
        {
            var result = key == null ? jObject : jObject[key.ToString()];

            if (result == null)
            {
                return(null);
            }

            if (result is JObject)
            {
                return(result.ToObject <T>());
            }
            if (result is JArray)
            {
                return(result.ToObject <List <T> >().FirstOrDefault());
            }
            return(null);
        }
Exemplo n.º 14
0
        public bool IsValid(string key, out int keyId)
        {
            keyId = 0;

            try
            {
                using (var context = new SettingsDbContext())
                {
                    ApiKeyData data = context.ApiKeys.SingleOrDefault(a => a.ApiKey == key);
                    if (data != null)
                    {
                        keyId = data.Id;
                        return(data.Active);
                    }
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
                throw new SettingsStoreException(Constants.ERROR_STORE_UNAVAILABLE, ex);
            }
        }
Exemplo n.º 15
0
 protected bool Equals(ApiKeyData other)
 {
     return(string.Equals(_key, other._key));
 }
Exemplo n.º 16
0
        private ApiKeyData GetKeyData(string applicationName, string name)
        {
            ApiKeyData data = Store.Context.ApiKeys.SingleOrDefault(a => a.Name == name && a.Application.Name == applicationName);

            return(data);
        }
Exemplo n.º 17
0
        public ApiKeyModel CreateApiKey(string applicationName, SaveApiKeyModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("No Data");
            }

            if (!Auth.AllowEditApiKeys(applicationName))
            {
                throw new SettingsAuthorizationException(AuthorizationScope.ApiKey, AuthorizationLevel.Create, applicationName, Auth.CurrentIdentity.Id);
            }

            if (string.IsNullOrWhiteSpace(model.Name))
            {
                throw new SettingsStoreException("Key has no Name");
            }

            var application = GetApplicationData(applicationName);

            if (application == null)
            {
                throw new SettingsNotFoundException(applicationName);
            }

            var existingKey = GetKeyData(applicationName, model.Name);

            if (existingKey != null)
            {
                throw new SettingsDuplicateException("Key with name already exist");
            }

            var apiKeyData = new ApiKeyData();

            using (TransactionScope scope = TransactionScopeFactory.CreateReaduncommited())
            {
                apiKeyData.ApiKey        = ApiKeyGenerator.Create();
                apiKeyData.ApplicationId = application.Id;
                apiKeyData.Active        = true;
                apiKeyData.AdminKey      = model.AdminKey;
                apiKeyData.Created       = DateTime.Now;
                apiKeyData.Name          = model.Name;
                Store.Context.ApiKeys.Add(apiKeyData);
                Store.Save();

                if (model.Access != null && model.Access.Count > 0)
                {
                    foreach (var item in model.Access)
                    {
                        var directiry = application.Directories.SingleOrDefault(d => d.Name == item.Directory);

                        if (directiry == null)
                        {
                            throw new SettingsNotFoundException(item.Directory);
                        }

                        DirectoryAccessData access = new DirectoryAccessData();

                        access.DirectoryId = directiry.Id;
                        access.ApiKeyId    = apiKeyData.Id;
                        access.AllowWrite  = item.Write;
                        access.AllowDelete = item.Delete;
                        access.AllowCreate = item.Create;

                        apiKeyData.Access.Add(access);
                    }

                    Store.Save();
                }

                scope.Complete();
            }

            return(GetApiKey(applicationName, apiKeyData.Name));
        }
Exemplo n.º 18
0
 public ValidateAndGetKeyTypeCommand(ApiKeyData data)
 {
     Data = data;
 }
Exemplo n.º 19
0
        public ApplicationModel CreateApplication(string applicationName, string applicationDescription, string directoryName, string directoryDescription)
        {
            if (!Auth.AllowCreateApplication(applicationName))
            {
                throw new SettingsAuthorizationException(AuthorizationScope.Application, AuthorizationLevel.Create, applicationName, Auth.CurrentIdentity.Id);
            }

            if (string.IsNullOrWhiteSpace(applicationName))
            {
                throw new SettingsStoreException(Constants.ERROR_APPLICATION_NO_NAME);
            }

            var application = Store.Context.Applications.FirstOrDefault(app => app.Name == applicationName);

            if (application != null)
            {
                throw new SettingsStoreException(Constants.ERROR_APPLICATION_ALREADY_EXISTS);
            }

            if (!NameValidator.ValidateName(applicationName))
            {
                throw new SettingsNotFoundException(Constants.ERROR_APPLICATION_NAME_INVALID);
            }

            application = new ApplicationData();
            DirectoryData cust_directory = null;
            DirectoryData def_directory  = null;

            using (TransactionScope scope = new TransactionScope())
            {
                application.Name = applicationName;

                if (string.IsNullOrWhiteSpace(applicationDescription))
                {
                    applicationDescription = Constants.DEAULT_APPLICATION_DESCRIPTION;
                }

                //Create application
                application.Description = applicationDescription.Trim().Replace("  ", " ");
                application.Created     = DateTime.UtcNow;

                Store.Context.Applications.Add(application);
                Store.Context.SaveChanges();

                //Create version 1
                VersionData version = new VersionData {
                    Version = 1, Created = DateTime.UtcNow, ApplicationId = application.Id
                };
                Store.Context.Versions.Add(version);
                Store.Context.SaveChanges();

                //Create application default directory
                def_directory               = new DirectoryData();
                def_directory.Name          = Constants.DEAULT_DIRECTORY_NAME;
                def_directory.Description   = Constants.DEAULT_DIRECTORY_DESCRIPTION;
                def_directory.ApplicationId = application.Id;
                def_directory.Created       = DateTime.UtcNow;
                Store.Context.Directories.Add(def_directory);

                //Create custom first directory, if provided.
                if (!string.IsNullOrWhiteSpace(directoryName))
                {
                    cust_directory      = new DirectoryData();
                    cust_directory.Name = directoryName.Trim();
                    if (directoryDescription != null)
                    {
                        cust_directory.Description = directoryDescription.Trim();
                    }
                    cust_directory.ApplicationId = application.Id;
                    cust_directory.Created       = DateTime.UtcNow;
                    Store.Context.Directories.Add(cust_directory);
                }

                Store.Context.SaveChanges();

                //Create default api key for applicaiton, a trigger maintains access for the master apikey to the application directories.
                ApiKeyData apiKey = new ApiKeyData {
                    ApiKey = ApiKeyGenerator.Create(), Name = application.Name, Application = application, Active = true, AdminKey = true, Created = DateTime.UtcNow
                };

                Store.Context.ApiKeys.Add(apiKey);
                Store.Context.SaveChanges();

                //Set access right to default directory.
                DirectoryAccessData access = new DirectoryAccessData();
                access.AllowWrite  = true;
                access.AllowDelete = true;
                access.AllowCreate = true;
                access.ApiKey      = apiKey;
                access.Directory   = def_directory;
                Store.Context.Access.Add(access);

                //Set access right to custom directory.
                if (cust_directory != null)
                {
                    access             = new DirectoryAccessData();
                    access.AllowWrite  = true;
                    access.AllowDelete = true;
                    access.AllowCreate = true;
                    access.ApiKey      = apiKey;
                    access.Directory   = cust_directory;
                    Store.Context.Access.Add(access);
                }

                Store.Save();
                scope.Complete();
            }

            Auth.Invalidate();

            Store.Context.Entry <ApplicationData>(application).Reload();

            //reload the enities the reflect the master key access created by the trigger.
            if (cust_directory != null)
            {
                Store.Context.Entry <DirectoryData>(cust_directory).Collection("Access").Load();
            }

            if (def_directory != null)
            {
                Store.Context.Entry <DirectoryData>(def_directory).Collection("Access").Load();
            }

            return(GetApplication(applicationName));
        }
        public ActionResult Generate(ApiKeyData data)
        {
            var account = Account;

            if (account.KeyQuota.KeysAllowed - account.KeyQuota.KeysUsed <= 0)
            {
                ErrorMessage =
                    "You have reached the API key quota. Please delete or deactivate keys that aren't in use or contact UGRC to increase your quota.";

                return(RedirectToAction("Index", "KeyManagement"));
            }

            ApiKey.ApplicationType type;
            var command = new ValidateAndGetKeyTypeCommand(data);

            try
            {
                type = CommandExecutor.ExecuteCommand(command);
            }
            catch (CommandValidationException e)
            {
                ErrorMessage = e.Message;

                return(RedirectToAction("Index", "KeyManagement"));
            }

            if (type == ApiKey.ApplicationType.None)
            {
                ErrorMessage = command.ErrorMessage;

                if (!string.IsNullOrEmpty(data.Ip))
                {
                    TempData["ip"] = data.Ip;
                }
                else
                {
                    TempData["url"] = data.UrlPattern;
                }

                return(RedirectToAction("Index", "GenerateKey"));
            }

            if (type == ApiKey.ApplicationType.Server)
            {
                if (LocalIp.IsMatch(data.Ip))
                {
                    Message = "The key you created looks like an internal IP address and will most likely not authenticate. " +
                              "Please visit <a href='http://whatismyip.com' target='_blank'>whatismyip.com</a> and use your public " +
                              "IP address. If you receive a 400 status code, be sure to read the response body as it will detail " +
                              "the reasons. ";
                }
            }

            var key     = CommandExecutor.ExecuteCommand(new GenerateUniqueApiKeyCommand(Session));
            var pattern = CommandExecutor.ExecuteCommand(new FormatKeyPatternCommand(type, data));
            var apiKey  = new ApiKey(key)
            {
                AccountId      = account.Id,
                ApiKeyStatus   = ApiKey.KeyStatus.Active,
                Type           = type,
                AppStatus      = data.AppStatus,
                Pattern        = data.UrlPattern ?? data.Ip,
                RegexPattern   = pattern,
                CreatedAtTicks = DateTime.UtcNow.Ticks,
                Deleted        = false,
                Key            = key
            };

            Session.Store(apiKey);

            Session.SaveChanges();

            Account.KeyQuota.KeysUsed = CommandExecutor.ExecuteCommand(new CountApiInfosForUserQuery(Session, account));

            Task.Factory.StartNew(() => CommandExecutor.ExecuteCommand(new KeyCreatedEmailCommand(account, apiKey)));

            Message += "Key created successfully.";

            return(RedirectToAction("Index", "KeyManagement"));
        }
            public int ProductionKey_IsValid(string pattern, string url)
            {
                //arrange
                const ApiKey.ApplicationType applicationType = ApiKey.ApplicationType.Browser;
                var data = new ApiKeyData
                {
                    AppStatus  = ApiKey.ApplicationStatus.Production,
                    UrlPattern = pattern
                };

                using (var s = DocumentStore.OpenSession())
                {
                    s.Store(new ApiKey("key")
                    {
                        AccountId      = "testaccount",
                        CreatedAtTicks = 634940675825121039,
                        ApiKeyStatus   = ApiKey.KeyStatus.Active,
                        Type           = applicationType,
                        AppStatus      = ApiKey.ApplicationStatus.Production,
                        RegexPattern   =
                            CommandExecutor.ExecuteCommand(new FormatKeyPatternCommand(applicationType, data)),
                        Pattern       = null,
                        IsMachineName = false,
                        Deleted       = false
                    }, "testkey");

                    s.SaveChanges();
                }

                var content =
                    new ObjectContent <ResultContainer <GeocodeAddressResult> >(new ResultContainer <GeocodeAddressResult>
                {
                    Result = new GeocodeAddressResult
                    {
                        InputAddress = "tESTING",
                        Score        = 100
                    }
                }, new JsonMediaTypeFormatter());

                content.Headers.Add("X-Type", typeof(ResultContainer <GeocodeAddressResult>).ToString());

                var contentMoq = new Mock <HttpContentProvider>();

                contentMoq.Setup(x => x.GetResponseContent(It.IsAny <HttpResponseMessage>()))
                .Returns(content);

                var handler = new AuthorizeRequestHandler
                {
                    DocumentStore  = DocumentStore,
                    InnerHandler   = new TestHandler((r, c) => TestHandler.Return200()),
                    ApiKeyProvider = new ApiKeyProvider()
                };

                var client = new HttpClient(handler);

                client.DefaultRequestHeaders.Add("Referrer", new[] { url });
                client.DefaultRequestHeaders.Add("Referer", new[] { url });

                var result =
                    client.GetAsync("http://webapi/v1/Geocode/326 east south temple/84111?apiKey=key")
                    .Result;

                return((int)result.StatusCode);
            }
Exemplo n.º 22
0
 public FormatKeyPatternCommand(ApiKey.ApplicationType type, ApiKeyData data)
 {
     Type     = type;
     Data     = data;
     _hasHttp = new Regex(Https, RegexOptions.IgnoreCase);
 }