コード例 #1
0
ファイル: IApiKeyService.cs プロジェクト: thecorrado/Warden
        private async Task CreateAsync(User user)
        {
            var apiKeysCount = await _database.ApiKeys().CountAsync(x => x.UserId == user.Id);
            if (apiKeysCount >= _featureSettings.MaxApiKeys)
            {
                throw new ServiceException($"Limit of {_featureSettings.MaxApiKeys} " +
                                           "API keys has been reached.");
            }

            var isValid = false;
            var currentTry = 0;
            var key = string.Empty;
            while (currentTry < RetryTimes)
            {
                key = _encrypter.GetRandomSecureKey();
                isValid = await _database.ApiKeys().ExistsAsync(key) == false;
                if (isValid)
                    break;

                currentTry++;
            }

            if (!isValid)
                throw new ServiceException("Could not create an API key, please try again.");

            var apiKey = new ApiKey(key, user);
            await _database.ApiKeys().InsertOneAsync(apiKey);
            Logger.Info($"New API key with id: '{apiKey.Id}' was created by user: '******'.");
        }
コード例 #2
0
ファイル: ApiKeyTest.cs プロジェクト: NSAKHAN/balanced-csharp
        public void TestApiKeyQueryAll()
        {
            ApiKey key = new ApiKey();
            key.Save();
            Balanced.Balanced.configure(key.secret);
            Marketplace marketplace = new Marketplace();
            marketplace.Save();

            ApiKey key1 = new ApiKey();
            key1.SaveToMarketplace();
        
            ApiKey key2 = new ApiKey();
            key2.SaveToMarketplace();
        
            ApiKey key3 = new ApiKey();
            key3.SaveToMarketplace();
        
            List<ApiKey> keys = ApiKey.Query().All();
            Assert.AreEqual(4, keys.Count);
            List<String> key_guids = new List<String>();
            foreach (ApiKey k in keys) {
                key_guids.Add(k.id);
            }
            Assert.IsTrue(key_guids.Contains(key1.id));
            Assert.IsTrue(key_guids.Contains(key2.id));
            Assert.IsTrue(key_guids.Contains(key3.id));
        }
コード例 #3
0
ファイル: ApiKeyTest.cs プロジェクト: NSAKHAN/balanced-csharp
 public void TestApiKeyDelete()
 {
     ApiKey key = new ApiKey();
     key.Save();
     Balanced.Balanced.configure(key.secret);
     key.Unstore();
 }
コード例 #4
0
        private XmlDocument CreateResponseDocument(ApiKey apiKey, LogonToken token, string operation)
        {
            if (apiKey == null)
                throw new ArgumentNullException("apiKey");
            if (operation == null)
                throw new ArgumentNullException("operation");
            if (operation.Length == 0)
                throw new ArgumentException("'operation' is zero-length.");

            // create...
            XmlDocument doc = new XmlDocument();

            // root...
            XmlElement root = doc.CreateElement(RootKey);
            doc.AppendChild(root);

            // defer...
            PopulateResponse(apiKey, token, operation, root);

            // ok...
            XmlHelper.AddElement(root, HasExceptionKey, false);

            // return...
            return doc;
        }
コード例 #5
0
 public ProjectAccess(OctopusUri octopusUri,ApiKey apiKey)
 {
     _octopusUri = octopusUri;
     _apiKey = apiKey;
     _octopusServerEndpoint = new OctopusServerEndpoint(_octopusUri.ToString(),_apiKey);
     _octopusRepo = new OctopusRepository(_octopusServerEndpoint);
 }
コード例 #6
0
ファイル: UserManagement.cs プロジェクト: janiukjf/CurtAdmin
        public static void generateCustomAPIKey(Guid userID, List<string> selectedModuleIDs)
        {
            CurtDevDataContext db = new CurtDevDataContext();
            // create API Key with custom type
            ApiKey customKey = new ApiKey();
            customKey.id = Guid.NewGuid();
            customKey.api_key = Guid.NewGuid();
            customKey.type_id = db.ApiKeyTypes.Where(x => x.type == "Custom").Select(x => x.id).FirstOrDefault<Guid>();
            customKey.user_id = userID;
            customKey.date_added = DateTime.Now;

            db.ApiKeys.InsertOnSubmit(customKey);
            db.SubmitChanges();

            // create record for each selected module ID in the APIAcess table
            List<ApiAccess> listOfNewAPIAccesses = new List<ApiAccess>();
            foreach (string modID in selectedModuleIDs) {
                ApiAccess apiAccess = new ApiAccess();
                apiAccess.id = Guid.NewGuid();
                apiAccess.key_id = customKey.id;
                apiAccess.module_id = new Guid(modID);
                listOfNewAPIAccesses.Add(apiAccess);
            }
            db.ApiAccesses.InsertAllOnSubmit(listOfNewAPIAccesses);
            db.SubmitChanges();

            // submit changes
        }
コード例 #7
0
ファイル: ApiKeyTest.cs プロジェクト: NSAKHAN/balanced-csharp
 public void TestApiKeyCollection()
 {
     ApiKey key = new ApiKey();
     key.Save();
     Balanced.Balanced.configure(key.secret);
     ApiKey.Collection apiKeys = new ApiKey.Collection();
     Assert.AreEqual(1, apiKeys.Total());
 }
コード例 #8
0
ファイル: BaseTest.cs プロジェクト: remear/balanced-csharp
 public void setUp()
 {
     ApiKey key = new ApiKey();
     key.Save();
     Balanced.Balanced.configure(key.secret);
     Marketplace marketplace = new Marketplace();
     marketplace.Save();
     mp = marketplace;
 }
コード例 #9
0
        private void ProcessLogoff(ApiKey api, LogonToken token, XmlElement root)
        {
            if (token != null)
            {
                token.MarkForDeletion();
                token.SaveChanges();
            }

            // return...
            XmlHelper.AddElement(root, ResultKey, LogoffResult.LogoffOk);
        }
コード例 #10
0
ファイル: Designer.aspx.cs プロジェクト: richorama/StateMagic
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["mode"] == "start")
            {
                var newcd = ModelServices.LogIn(Request["username"], new Guid(Request["apikey"]));
                if (newcd != null)
                {
                    Session["Credentials"] = newcd;
                    Response.Redirect(string.Format("Designer.aspx?ModelId={0}", Request["ModelId"]));
                }
                else
                {
                    Response.Redirect("default.htm");
                }
            }

            CredentialData cd = Session["Credentials"] as CredentialData;
            if (null != cd)
            {
                // we are not logged in
                AddParam("username", cd.Username);
                AddParam("apikey", cd.ApiKey.ToString());
                this.SignInLink.Visible = false;
            }
            else
            {
                this.UserDetailsLink.Visible = false;
                this.SignOutLink.Visible = false;
                if (null == Session["ApiKey"] as string)
                {
                    Guid key = Guid.NewGuid();
                    ApiKey apiKey = new ApiKey();
                    apiKey.APIKey = key;
                    apiKey.DateCreated = DateTime.Now;
                    apiKey.Save();
                    Session["ApiKey"] = key.ToString();
                    // TODO: save the apikey to the database
                }
                AddParam("apikey", Session["ApiKey"] as string);
            }

            if (null != Request["ModelId"])
            {
                AddParam("modelid", Request["ModelId"]);
            }

            this.initParams.Controls.Add(new LiteralControl(string.Format(@"<param name=""initParams"" value=""{0}"" />", string.Join(",", paramsList.ToArray()))));
        }
コード例 #11
0
        protected override void PopulateResponse(ApiKey api, LogonToken token, string operation, XmlElement root)
        {
            if(api == null)
	            throw new ArgumentNullException("api");
            if (operation == null)
                throw new ArgumentNullException("operation");
            if (root == null)
                throw new ArgumentNullException("foo");

            // if...
            if (string.Compare(operation, "logon", true, Cultures.System) == 0)
                ProcessLogon(api, token, root);
            else if (string.Compare(operation, "logoff", true, Cultures.System) == 0)
                ProcessLogoff(api, token, root);
            else
                throw new NotSupportedException(string.Format("Cannot handle '{0}'.", operation));
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class
        /// </summary>
        public Configuration(
            IDictionary <string, string> defaultHeader,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "https://prod.api.appcluster01.ca-central-1.ezmax.com/rest") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeader == null)
            {
                throw new ArgumentNullException("defaultHeader");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeader)
            {
                DefaultHeader.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class
        /// </summary>
        public Configuration(
            IDictionary <string, string> defaultHeader,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "http://healthsuite.allocatesoftware.com/api/booking/v1") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeader == null)
            {
                throw new ArgumentNullException("defaultHeader");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeader)
            {
                DefaultHeader.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class
        /// </summary>
        public Configuration(
            IDictionary <string, string> defaultHeader,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "https://api.bigcommerce.com/stores/{$$.env.store_hash}/v3") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeader == null)
            {
                throw new ArgumentNullException("defaultHeader");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeader)
            {
                DefaultHeader.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class
        /// </summary>
        public Configuration(
            IDictionary <string, string> defaultHeader,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "https://stp-dev.epias.com.tr/stp-broadcaster-orchestrator/rest") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeader == null)
            {
                throw new ArgumentNullException("defaultHeader");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeader)
            {
                DefaultHeader.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #16
0
        public Configuration(
            IDictionary <string, string> defaultHeaders,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "https://13d16e9d-d8b1-4ef4-bc4a-ed8156b2b159.mock.pstmn.io") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeaders == null)
            {
                throw new ArgumentNullException("defaultHeaders");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeaders)
            {
                DefaultHeaders.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class
        /// </summary>
        public Configuration(
            IDictionary <string, string> defaultHeader,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "https://api.bag.acceptatie.kadaster.nl/esd/huidigebevragingen/v1") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeader == null)
            {
                throw new ArgumentNullException("defaultHeader");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeader)
            {
                DefaultHeader.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class
        /// </summary>
        public Configuration(
            IDictionary <string, string> defaultHeader,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "https://virtserver.swaggerhub.com/BrambyPerspective/CheckoutPaymentGatewayAPI/V1") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeader == null)
            {
                throw new ArgumentNullException("defaultHeader");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeader)
            {
                DefaultHeader.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #19
0
ファイル: Configuration.cs プロジェクト: diazmartin/net-sdk
        public Configuration(
            IDictionary <string, string> defaultHeaders,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "https://api.mercadolibre.com") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeaders == null)
            {
                throw new ArgumentNullException("defaultHeaders");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeaders)
            {
                DefaultHeaders.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class
        /// </summary>
        public Configuration(
            IDictionary <string, string> defaultHeader,
            IDictionary <string, string> apiKey,
            IDictionary <string, string> apiKeyPrefix,
            string basePath = "http://petstore.swagger.io:80/v2") : this()
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentException("The provided basePath is invalid.", "basePath");
            }
            if (defaultHeader == null)
            {
                throw new ArgumentNullException("defaultHeader");
            }
            if (apiKey == null)
            {
                throw new ArgumentNullException("apiKey");
            }
            if (apiKeyPrefix == null)
            {
                throw new ArgumentNullException("apiKeyPrefix");
            }

            BasePath = basePath;

            foreach (var keyValuePair in defaultHeader)
            {
                DefaultHeader.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKey)
            {
                ApiKey.Add(keyValuePair);
            }

            foreach (var keyValuePair in apiKeyPrefix)
            {
                ApiKeyPrefix.Add(keyValuePair);
            }
        }
コード例 #21
0
        public void CreateKey_Fail_ExistingKeyShouldReturnNull()
        {
            // Arrange
            newKey = tu.CreateApiKeyObject();
            var expected = newKey;

            using (_db = tu.CreateDataBaseContext())
            {
                // Act
                var response = ApiKeyService.CreateKey(_db, newKey);
                _db.SaveChanges();

                var actual = ApiKeyService.CreateKey(_db, newKey);

                // Assert
                Assert.IsNull(actual);
                Assert.AreNotEqual(expected, actual);

                ApiKeyService.DeleteKey(_db, newKey.Id);
                _db.SaveChanges();
            }
        }
コード例 #22
0
        public async Task <IActionResult> CreateApiKey()
        {
            var user = await GetUser();

            var apiKey       = new ApiKey();
            var generatedKey = GenerateKey();

            // to ensure the key is not already in use.
            while (!await IsKeyUnique(generatedKey))
            {
                generatedKey = GenerateKey();
            }

            apiKey.Key       = generatedKey;
            apiKey.CreatedAt = DateTime.Now;
            apiKey.OwnedById = user.Id;

            await _unitOfWork.ApiKeys.Insert(apiKey);

            _logger.LogInformation($@"api key generated for user-email {user.Email}");
            return(Ok(_mapper.Map <ApiKeyDto>(apiKey)));
        }
コード例 #23
0
        // GET: Employees/Details/5
        public async Task <IActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var customer = await _context.Customers
                           .Include(e => e.Address)
                           .Include(c => c.Weekday)
                           .FirstOrDefaultAsync(m => m.Id == id);

            if (customer == null)
            {
                return(NotFound());
            }
            ApiKey key    = _context.ApiKeys.Where(k => k.Id == 2).Single();
            string apikey = key.Key;

            ViewBag.key = apikey;
            return(View(customer));
        }
コード例 #24
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Login != null ? Login.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Password != null ? Password.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (FirstName != null ? FirstName.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (LastName != null ? LastName.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Email != null ? Email.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ AuthenticationModeId.GetHashCode();
         hashCode = (hashCode * 397) ^ CreatedOn.GetHashCode();
         hashCode = (hashCode * 397) ^ LastLoginOn.GetHashCode();
         hashCode = (hashCode * 397) ^ (ApiKey != null ? ApiKey.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (int)Status;
         hashCode = (hashCode * 397) ^ MustChangePassword.GetHashCode();
         hashCode = (hashCode * 397) ^ (CustomFields != null ? CustomFields.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Memberships != null ? Memberships.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Groups != null ? Groups.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (MailNotification != null ? MailNotification.GetHashCode() : 0);
         return(hashCode);
     }
 }
コード例 #25
0
 public HitBtcApiClient() : base("hitbtc.hash", typeof(HMACSHA256))
 {
     if (IsSigned)
     {
         clientAuth.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator(ApiKey.ToManagedString(), ApiSecret.ToManagedString());
         wsTrading.Opened        += (sender, e) =>
         {
             Debug.Print("Trading socket connected.");
             var reqLogin = new HitBtc.WsRequestBase()
             {
                 method = "login", id = "authenticate"
             };
             var nn = nonce.ToString();
             reqLogin.data.Add("algo", HitBtc.AuthAlgo.HS256.ToString());
             reqLogin.data.Add("pKey", ApiKey.ToManagedString());
             reqLogin.data.Add("nonce", nn);
             reqLogin.data.Add("signature", ByteArrayToHexString(SignString(nn)));
             wsTrading.Send(JsonConvert.SerializeObject(reqLogin));
         };
         wsTrading.Open();
     }
 }
コード例 #26
0
        private bool TryGetFromCache(string clientID, out ApiKey key)
        {
            key = null;

            if (_cache.TryGetValue(clientID, out CacheEntry secret))
            {
                if (secret.Expires < DateTime.UtcNow)
                {
                    return(false);
                }

                key = new ApiKey()
                {
                    ClientID = clientID,
                    Secret   = secret.Secret
                };

                return(true);
            }

            return(false);
        }
コード例 #27
0
        public async Task <ApiKey> GetAsync(string key, CancellationToken ct = default)
        {
            ApiKey apikey;

            await using var cmd = this.m_ctx.Connection.CreateCommand();
            if (cmd.Connection.State != ConnectionState.Open)
            {
                await cmd.Connection.OpenAsync(ct).ConfigureAwait(false);
            }

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = NetworkApi_GetApiKeyByKey;

            var param = new NpgsqlParameter("key", NpgsqlDbType.Text)
            {
                Value = key
            };

            cmd.Parameters.Add(param);

            await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);

            if (!reader.HasRows)
            {
                return(null);
            }

            await reader.ReadAsync(ct).ConfigureAwait(false);

            apikey = new ApiKey {
                Key      = key,
                UserId   = reader.GetGuid(0),
                Revoked  = reader.GetBoolean(1),
                Type     = (ApiKeyType)reader.GetInt32(2),
                ReadOnly = reader.GetBoolean(3)
            };

            return(apikey);
        }
コード例 #28
0
        public async Task <ApiKey?> CreateAsync()
        {
            var now = DateTime.Now.ToUniversalTime();

            var toCreate = new ApiKey
            {
                Id       = Guid.NewGuid(),
                Created  = now,
                LastUsed = now
            };

            var created = await repository.CreateAsync(toCreate);

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

            await cache.SetAsync(created.Id.ToString(), created);

            return(created);
        }
コード例 #29
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (aggregationStrategy_ != null)
            {
                hash ^= AggregationStrategy.GetHashCode();
            }
            hash ^= histograms_.GetHashCode();
            if (BaseUri.Length != 0)
            {
                hash ^= BaseUri.GetHashCode();
            }
            if (ApiKey.Length != 0)
            {
                hash ^= ApiKey.GetHashCode();
            }
            if (DefaultFidelityParametersFilename.Length != 0)
            {
                hash ^= DefaultFidelityParametersFilename.GetHashCode();
            }
            if (InitialRequestTimeoutMs != 0)
            {
                hash ^= InitialRequestTimeoutMs.GetHashCode();
            }
            if (UltimateRequestTimeoutMs != 0)
            {
                hash ^= UltimateRequestTimeoutMs.GetHashCode();
            }
            if (LoadingAnnotationIndex != 0)
            {
                hash ^= LoadingAnnotationIndex.GetHashCode();
            }
            if (LevelAnnotationIndex != 0)
            {
                hash ^= LevelAnnotationIndex.GetHashCode();
            }
            return(hash);
        }
コード例 #30
0
        /// <summary>
        /// Determine the user account associated with this API key.
        /// Return null if the user account is invalid.
        /// </summary>
        /// <param name="apiKey">The API key</param>
        /// <returns>The user account, or null if the user account is somehow unavailable or locked.</returns>
        private UserAccount GetValidUserAccount(ApiKey apiKey)
        {
            // Get the user account
            UserAccount userAccount = apiKey.ApiKeyUserAccount;

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

            // Validate the account status
            try
            {
                UserAccountValidator.ValidateAccountStatus(userAccount, true);
            }
            catch (AuthenticationException) // note: there are various types that derive from this
            {
                return(null);
            }

            return(userAccount);
        }
コード例 #31
0
        /// <summary>
        /// Execution Logic
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(CodeActivityContext context)
        {
            MembersCount.Set(context, 0);
            MembersNames.Set(context, new Collection <string>()
            {
            });

            string host     = "https://api.meetup.com/2/members?order=name&sign=true&group_urlname={0}&key={1}";
            string url      = string.Format(host, GroupUrlName.Get(context), ApiKey.Get(context));
            string response = string.Empty;

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            if (null == request)
            {
                throw new ApplicationException("HttpWebRequest failed");
            }
            using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                response = sr.ReadToEnd();
            }

            RawResponse.Set(context, response);

            Collection <string> names = new Collection <string>()
            {
            };

            JObject o = JObject.Parse(response);
            JArray  a = (JArray)o["results"];

            foreach (JToken item in a)
            {
                names.Add(item["name"].ToString());
            }

            MembersCount.Set(context, a.Count);
            MembersNames.Set(context, names);
        }
コード例 #32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="x"></param>
        public static string Create(this ApiKey u)
        {
            var secretKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(SECRET_KEY));

            var signinCredentials = new SigningCredentials(
                secretKey, SecurityAlgorithms.HmacSha256);

            var claims = new List <Claim>
            {
                new Claim(ORG, u.OrgId.ToString()),
                new Claim(NAME, u.Name),
                new Claim(ROLE, u.Role.ToString()),
            };

            var tokenOptions = new JwtSecurityToken(
                claims: claims,
                //expires: DateTime.Now.AddYears( 1 ),
                signingCredentials: signinCredentials

                );

            var ttl = ( uint? )u.Bag.SecondsToLive;

            //if( ttl.HasValue && ttl > 0 )
            {
                tokenOptions = new JwtSecurityToken(
                    claims: claims,
                    //expires: DateTime.Now.AddSeconds( ttl.Value ),
                    expires: DateTime.Now.AddYears(1),
                    signingCredentials: signinCredentials);
            }

            //tokenOptions.Header.Clear();

            var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);

            return(tokenString);
        }
コード例 #33
0
 public static Either <Error, WWW> request(
     string url, Request request, ApiKey key,
     Dictionary <string, string> headers__WillBeMutated,
     int tryCount = 20
     )
 {
     if (!request.noBody)
     {
         headers__WillBeMutated["Content-Type"] = "application/json";
     }
     headers__WillBeMutated["Authorization"] = key.asAuthHeader;
     try {
         WWW www = null;
         for (var retry = 0; retry < tryCount; retry++)
         {
             www = request.www(url, headers__WillBeMutated);
             while (!www.isDone)
             {
                 if (EditorUtility.DisplayCancelableProgressBar(
                         $"Fetching WWW (try {retry + 1})", $"{request.method} {url}", www.progress
                         ))
                 {
                     www.Dispose();
                     Log.info($"Request to {url} cancelled.");
                     return(Either <Error, WWW> .Left(CancelledByUser.instance));
                 }
             }
             if (string.IsNullOrEmpty(www.error) || !www.error.ToLower().Contains("timed out"))
             {
                 break;
             }
         }
         return(www.toEither().mapLeft(err => (Error) new NetError(err)));
     }
     finally {
         EditorUtility.ClearProgressBar();
     }
 }
コード例 #34
0
        public ValidationResult Validate()
        {
            if (_validationResult != null)
            {
                return(_validationResult);
            }

            var result = new ValidationResult();

            string key = ApiKey != null?ApiKey.Trim() : null;

            if (String.IsNullOrEmpty(key) || String.Equals(key, "API_KEY_HERE", StringComparison.OrdinalIgnoreCase))
            {
                result.Messages.Add("ApiKey is not set.");
            }

            if (key != null && (key.Length < 10 || key.Contains(" ")))
            {
                result.Messages.Add(String.Format("ApiKey \"{0}\" is not valid.", key));
            }

            if (String.IsNullOrEmpty(ServerUrl))
            {
                result.Messages.Add("ServerUrl is not set.");
            }

            if (String.IsNullOrEmpty(ConfigServerUrl))
            {
                result.Messages.Add("ConfigServerUrl is not set.");
            }

            if (String.IsNullOrEmpty(HeartbeatServerUrl))
            {
                result.Messages.Add("HeartbeatServerUrl is not set.");
            }

            return(result);
        }
コード例 #35
0
        protected override void Execute(NativeActivityContext context)
        {
            string spreadsheetId = SpreadsheetId.Get(context);
            GoogleSheetProperty googleSheetProperty;

            switch (AuthenticationType)
            {
            case GoogleAuthenticationType.ApiKey:
                string apiKey = ApiKey.Get(context);
                googleSheetProperty = GoogleSheetProperty.Create(apiKey, spreadsheetId);
                break;

            case GoogleAuthenticationType.OAuth2User:
                string credentialID     = CredentialID.Get(context);
                string credentialSecret = CredentialSecret.Get(context);
                googleSheetProperty = Task.Run(async() =>
                {
                    return(await GoogleSheetProperty.Create(credentialID, credentialSecret, spreadsheetId));
                }).Result;
                break;

            case GoogleAuthenticationType.OAuth2ServiceAccount:
                string serviceAccountEmail = ServiceAccountEmail.Get(context);
                string keyPath             = KeyPath.Get(context);
                string password            = Password.Get(context);
                googleSheetProperty = GoogleSheetProperty.Create(keyPath, password, serviceAccountEmail, spreadsheetId);
                break;

            default:
                googleSheetProperty = GoogleSheetProperty.Create("wrongkey", spreadsheetId);
                break;
            }

            if (Body != null)
            {
                context.ScheduleAction <GoogleSheetProperty>(Body, googleSheetProperty, OnCompleted, OnFaulted);
            }
        }
コード例 #36
0
        /// <summary>
        /// Add and Get the new api key
        /// </summary>
        /// <returns></returns>
        public static ApiKey GetApiKey()
        {
            Dictionary <string, string> purpose = new Dictionary <string, string>();

            purpose.Add("purpose", "Desktop Session, " + DateTime.Now.ToString());

            var responseTask = client.PostAsJsonAsync("apikey/", purpose);

            responseTask.Wait();

            var    result = responseTask.Result;
            ApiKey apiKey = null;

            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync <ApiKey>();
                readTask.Wait();

                apiKey = readTask.Result;
            }

            return(apiKey);
        }
コード例 #37
0
        private static void AppendApiKey(OpenApiSecurityScheme scheme, ApiKey apiKey)
        {
            Debug.Assert(scheme != null);
            Debug.Assert(apiKey != null);

            scheme.Name = apiKey.KeyName;

            Debug.Assert(apiKey.Location != null);
            switch (apiKey.Location.Value)
            {
            case KeyLocation.Cookie:
                scheme.In = ParameterLocation.Cookie;
                break;

            case KeyLocation.Header:
                scheme.In = ParameterLocation.Header;
                break;

            case KeyLocation.QueryOption:
                scheme.In = ParameterLocation.Query;
                break;
            }
        }
コード例 #38
0
        public void TestApiKeyCreation()
        {
            Assert.Empty(Repository.GetAllApiKeys());

            // Test creation
            string name = "Test Key";
            ApiKey key  = Repository.CreateApiKey(name);

            Assert.Equal(name, key.Name);
            Assert.Empty(key.Rights);
            Assert.False(key.Enabled);

            // Test getting the key from the repo again
            Assert.Single(Repository.GetAllApiKeys());
            key = Repository.GetApiKey(key.Id);
            Assert.Equal(name, key.Name);
            Assert.Empty(key.Rights);
            Assert.False(key.Enabled);

            // Create another key
            Repository.CreateApiKey("RandomName");
            Assert.Equal(2, Repository.GetAllApiKeys().Count());
        }
コード例 #39
0
ファイル: ApiKeyServiceUT.cs プロジェクト: cf2080/SSO
        public void CreateKey_Pass_ReturnKey()
        {
            // Arrange
            newKey = tu.CreateApiKeyObject();
            var expected = newKey;

            using (_db = tu.CreateDataBaseContext())
            {
                IApiKeyService      _apiKeyService      = new ApiKeyService(_db);
                IApplicationService _applicationService = new ApplicationService(_db);

                // Act
                var response = _apiKeyService.CreateKey(newKey);
                _db.SaveChanges();

                // Assert
                Assert.IsNotNull(response);
                Assert.AreEqual(response.Id, expected.Id);

                _applicationService.DeleteApplication(newKey.ApplicationId);
                _db.SaveChanges();
            }
        }
コード例 #40
0
        /// <summary>
        /// Gets an API key list, maybe filtered by an ID.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="id">Optional key ID to filter with.</param>
        /// <returns>Returns a list of keys.</returns>
        private IEnumerable <ApiKey> GetApiKeys(IDbConnection connection, Guid?id = null)
        {
            Dictionary <Guid, ApiKey> keys = new Dictionary <Guid, ApiKey>();
            string sql = id != null ? SQL_GET_API_KEY : SQL_GET_API_KEYS;

            return(connection.Query <ApiKey, ApiKeyRights, ApiKey>(sql,
                                                                   map: (apiKey, keyRights) =>
            {
                ApiKey key = null;
                if (!keys.TryGetValue(apiKey.Id, out key))
                {
                    key = apiKey;
                    keys.Add(key.Id, key);
                }
                if (keyRights != null)
                {
                    key.Rights.Add(new Right(keyRights.RightId));
                }
                return key;
            },
                                                                   splitOn: "api_key_id",
                                                                   param: id != null ? new { id } : null).Distinct());
        }
コード例 #41
0
ファイル: ApiKeyServiceUT.cs プロジェクト: cf2080/SSO
        public void GetApiKeyByKey_Pass_ReturnKey()
        {
            // Arrange
            newKey = tu.CreateApiKeyObject();
            var expected = newKey;

            // Act
            using (_db = tu.CreateDataBaseContext())
            {
                IApiKeyService _apiKeyService = new ApiKeyService(_db);

                newKey = _apiKeyService.CreateKey(newKey);
                _db.SaveChanges();
                var result = _apiKeyService.GetKey(newKey.Key);

                // Assert
                Assert.IsNotNull(result);
                Assert.AreEqual(expected.Key, result.Key);

                _apiKeyService.DeleteKey(newKey.Id);
                _db.SaveChanges();
            }
        }
コード例 #42
0
        private void ProcessLogon(ApiKey api, LogonToken token, XmlElement root)
        {
            if (api == null)
                throw new ArgumentNullException("api");
            if (root == null)
                throw new ArgumentNullException("root");

            // get the password...
            string password = this.Request.Params["password"];
            if (password == null)
                throw new InvalidOperationException("'password' is null.");
            if (password.Length == 0)
                throw new InvalidOperationException("'password' is zero-length.");

            // check...
            string hashed = EncryptionHelper.HashPasswordToBase64String(password, api.PasswordSalt);
            if (hashed == api.PasswordHash)
            {
                // create a new token...
                token = new LogonToken();
                token.ApiKey = api;
                token.GenerateToken();
                token.UpdateExpiry(false);

                // save...
                token.SaveChanges();

                // set...
                XmlHelper.AddElement(root, ResultKey, LogonResult.LogonOk);
                XmlHelper.AddElement(root, TokenKey, token.Token.ToString());
            }
            else
            {
                XmlHelper.AddElement(root, ResultKey, LogonResult.InvalidPassword);
                XmlHelper.AddElement(root, MessageKey, "The password is invalid.");
            }
        }
コード例 #43
0
        private void ProcessLogon(ApiKey api, LogonToken token, XmlElement root)
        {
            if (api == null)
                throw new ArgumentNullException("api");
            if (token == null)
                throw new ArgumentNullException("token");
            if (root == null)
                throw new ArgumentNullException("root");

            // reset...
            token.User = null;
            token.SaveChanges();

            // get...
            string username = this.Request.Params["username"];
            if (username == null)
                throw new InvalidOperationException("'username' is null.");
            if (username.Length == 0)
                throw new InvalidOperationException("'username' is zero-length.");
            string password = this.Request.Params["password"];
            if (password == null)
                throw new InvalidOperationException("'password' is null.");
            if (password.Length == 0)
                throw new InvalidOperationException("'password' is zero-length.");

            // find a user...
            UserItem user = UserItem.GetByUsernameAndApiKeyId(username, api.ApiKeyId);
            if (user != null)
            {
                // active?
                if (user.IsActive)
                {
                    // check...
                    string hash = EncryptionHelper.HashPasswordToBase64String(password, user.PasswordSalt);
                    if (user.PasswordHash == hash)
                    {
                        // save...
                        token.User = user;
                        token.SaveChanges();

                        // ok...
                        XmlHelper.AddElement(root, ResultKey, LogonResult.LogonOk);
                        XmlHelper.AddElement(root, TokenKey, token.Token);
                    }
                    else
                    {
                        XmlHelper.AddElement(root, ResultKey, LogonResult.InvalidPassword);
                        XmlHelper.AddElement(root, MessageKey, "The password is invalid.");
                    }
                }
                else
                {
                    XmlHelper.AddElement(root, ResultKey, LogonResult.AccountDisabled);
                    XmlHelper.AddElement(root, MessageKey, "The account is not active.");
                }
            }
            else
            {
                XmlHelper.AddElement(root, ResultKey, LogonResult.InvalidUsername);
                XmlHelper.AddElement(root, MessageKey, "The username is invalid.");
            }
        }
コード例 #44
0
        /// <summary>
        /// Handles the logoff operation.
        /// </summary>
        /// <param name="api"></param>
        /// <param name="token"></param>
        /// <param name="root"></param>
        private void ProcessLogoff(ApiKey api, LogonToken token, XmlElement root)
        {
            if (token != null)
            {
                token.User = null;
                token.SaveChanges();
            }

            // send...
            XmlHelper.AddElement(root, ResultKey, LogoffResult.LogoffOk);
        }
 public Services.Packages.Log.ApplicationExceptionCollection GetApplicationExceptionsLogged(ApiKey _ApiKey, string SessionToken)
 {
     object[] results = this.Invoke("GetApplicationExceptionsLogged", new object[] {_ApiKey,SessionToken});
     return ((Services.Packages.Log.ApplicationExceptionCollection)(results[0]));
 }
 public void SetApplicationExceptionsLogged(ApiKey _ApiKey, Services.Packages.Log.ApplicationExceptionCollection _ApplicationExceptionsLogged, string SessionToken)
 {
     this.Invoke("GetApplicationExceptionsLogged", new object[] {_ApiKey,SessionToken});
     return;
 }
 public void SetOrders(ApiKey _ApiKey, Services.Packages.PurchaseCollection _Orders, string SessionToken)
 {
     this.Invoke("GetOrders", new object[] {_ApiKey,SessionToken});
     return;
 }
        public Services.Packages.Security.ApiKeyAccessControlListCollection GetACLs(ApiKey _ApiKey, string SessionToken)
        {
            _ApiKey.Reload();

            //*
            if (!Services.Packages.Security.ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            /*
            if (!Services.Packages.Security.Security.ApiKeyAccessControlListSecureService.CheckAccessImp(_ApiKey.ACLs, SessionToken, "Read"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            return _ApiKey.ACLs;
        }
        public void Delete(System.Guid __Id, string SessionToken)
        {
            ApiKey _ApiKey = new ApiKey(__Id);

            if (!ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Delete"))
                throw new UnauthorizedAccessException("Access Denied");

            ApiKey.DeleteApiKey(__Id);
        }
        public void CreateObjectFromOwner(ApiKey _ApiKey, Services.Packages.Security.ModelUser _Owner, string SessionToken)
        {
            ModelSession session = ApiKeySecureService.CheckSessionImp(SessionToken);

            //if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_Owner, SessionToken, "Create ApiKeyOwning"))
            //	throw new UnauthorizedAccessException("Access Denied");

            _ApiKey.Reload();

            if (!_ApiKey.Exists && !Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_Owner, SessionToken, "Create ApiKeyOwning"))
                throw new UnauthorizedAccessException("Access Denied");
            else if (_ApiKey.Exists && !ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Update"))
                throw new UnauthorizedAccessException("Access Denied");

            _ApiKey.Owner = session.User;
            _ApiKey.Owner = _Owner;
            _ApiKey.Create();
        }
        public Services.Packages.Security.ModelUser GetOwner(ApiKey _ApiKey, string SessionToken)
        {
            _ApiKey.Reload();

            //*
            if (!Services.Packages.Security.ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            //*
            if (!Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_ApiKey.Owner, SessionToken, "Read"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            return _ApiKey.Owner;
        }
 public Services.Packages.PurchaseCollection GetOrders(ApiKey _ApiKey, string SessionToken)
 {
     object[] results = this.Invoke("GetOrders", new object[] {_ApiKey,SessionToken});
     return ((Services.Packages.PurchaseCollection)(results[0]));
 }
コード例 #53
0
ファイル: UserManagement.cs プロジェクト: janiukjf/CurtAdmin
        public static void generateGenericKey(Guid userID, string keyType)
        {
            CurtDevDataContext db = new CurtDevDataContext();

            // before creating a new genericKey (private or public), check to see if one already exists, if one does, dont create a new one.
            ApiKey keyCheck = db.ApiKeys.Where(x => x.user_id == userID && x.ApiKeyType.type == keyType).FirstOrDefault<ApiKey>();
            if (keyCheck != null) {
                // one already exists so throw exception stating one already exists
                throw new Exception("A " + keyType + " Key already exists. Each user should only have one of these types of keys.");
            } else {
                // create API Key
                ApiKey customKey = new ApiKey();
                customKey.id = Guid.NewGuid();
                customKey.api_key = Guid.NewGuid();
                customKey.type_id = db.ApiKeyTypes.Where(x => x.type == keyType).Select(x => x.id).FirstOrDefault<Guid>();
                customKey.user_id = userID;
                customKey.date_added = DateTime.Now;

                db.ApiKeys.InsertOnSubmit(customKey);
                db.SubmitChanges();
            }
        }
 public void SetACLs(ApiKey _ApiKey, Services.Packages.Security.ApiKeyAccessControlListCollection _ACLs, string SessionToken)
 {
     this.Invoke("GetACLs", new object[] {_ApiKey,SessionToken});
     return;
 }
        public void CreateObject(ApiKey _ApiKey, string SessionToken)
        {
            ModelSession session = ApiKeySecureService.CheckSessionImp(SessionToken);

            if (!ApiKeySecureService.CheckUserRightsImp(session.User.Name, "Create " + typeof(ApiKey).FullName))
                throw new UnauthorizedAccessException("Access Denied");

            _ApiKey.Owner = session.User;
            _ApiKey.Create();
        }
        public bool Exists(ApiKey _ApiKey, string SessionToken)
        {
            if (!ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");

            return _ApiKey.Exists;
        }
 public Services.Packages.Security.ApiKeyAccessControlListCollection GetACLs(ApiKey _ApiKey, string SessionToken)
 {
     object[] results = this.Invoke("GetACLs", new object[] {_ApiKey,SessionToken});
     return ((Services.Packages.Security.ApiKeyAccessControlListCollection)(results[0]));
 }
        public Services.Packages.PackageCollection GetPackagesUploaded(ApiKey _ApiKey, string SessionToken)
        {
            _ApiKey.Reload();

            //*
            if (!Services.Packages.Security.ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Traverse"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            /*
            if (!Services.Packages.Security.PackageSecureService.CheckAccessImp(_ApiKey.PackagesUploaded, SessionToken, "Read"))
                throw new UnauthorizedAccessException("Access Denied");
            //*/

            return _ApiKey.PackagesUploaded;
        }
        public void DeleteObject(ApiKey _ApiKey, string SessionToken)
        {
            if (!ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Delete"))
                throw new UnauthorizedAccessException("Access Denied");

            _ApiKey.Delete();
        }
        public ApiKey CreateFromOwner(System.Guid __Id, Services.Packages.Security.ModelUser _Owner, string SessionToken)
        {
            ModelSession session = ApiKeySecureService.CheckSessionImp(SessionToken);

            ApiKey _ApiKey = new ApiKey(__Id);

            if (!_ApiKey.Exists && !Services.Packages.Security.Security.ModelUserSecureService.CheckAccessImp(_Owner, SessionToken, "Create ApiKeyOwning"))
                throw new UnauthorizedAccessException("Access Denied");
            else if (_ApiKey.Exists && !ApiKeySecureService.CheckAccessImp(_ApiKey, SessionToken, "Update"))
                throw new UnauthorizedAccessException("Access Denied");

            // ApiKey _ApiKey = ApiKey.CreateApiKey(__Id);
            _ApiKey.Owner = session.User;
            _ApiKey.Owner = _Owner;
            _ApiKey.Update();
            return _ApiKey;
        }