Esempio n. 1
0
        public async Task UpdateApiKeyAsync(ApiKeyModel model)
        {
            _dbContext.ApiKeyEntity.Update(new ApiKeyEntity
            {
                Id     = model.Id,
                ApiKey = GenerateApiKey(model.ApiKey)
            });

            await _dbContext.SaveChangesAsync();
        }
Esempio n. 2
0
        public static ApiKeyModel DataReader_to_ApiKeyModel(SqlDataReader reader)
        {
            ApiKeyModel key = new ApiKeyModel();

            key.ApiKey      = (Guid)reader["ApiKey"];
            key.Name        = (String)reader["Name"];
            key.Description = (String)reader["Description"];
            key.CreatedDate = (DateTime)reader["CreatedDate"];

            return(key);
        }
Esempio n. 3
0
        public static ApiKeyModel GetApiKey()
        {
            if (ApiKey != null)
            {
                return(ApiKey);
            }
            var configPath = "../../AppData/AppConfig.json";

            ApiKey = File.Exists(configPath) ?
                     JObject.Parse(File.ReadAllText(configPath))["apikey"].ToObject <ApiKeyModel>()
                : null;
            return(ApiKey);
        }
Esempio n. 4
0
        public void Setup()
        {
            Model = new ApiKeyModel
            {
                Id     = UserId,
                ApiKey = ApiKey
            };

            _mockApiKeyEntity  = new Mock <DbSet <ApiKeyEntity> >();
            _mockDbContext     = new Mock <IDatabaseContext>();
            _mockApiKeyQueries = new Mock <IApiKeyQueries>();

            _mockDbContext.Setup(a => a.ApiKeyEntity).Returns(_mockApiKeyEntity.Object);
            _mockApiKeyQueries.Setup(x => x.RetrieveApiKey(UserId)).Returns(Model);

            Result = new ApiKeyQueries(_mockDbContext.Object);
        }
Esempio n. 5
0
        public IEnumerable <ApiKeyModel> GetApplicationApiKeys(string applicationName)
        {
            var data = new List <ApiKeyData>();
            List <ApiKeyModel> result = new List <ApiKeyModel>();



            if (!Auth.AllowReadApiKeys(applicationName))
            {
                throw new SettingsAuthorizationException(AuthorizationScope.ApiKey, AuthorizationLevel.Read, applicationName, Auth.CurrentIdentity.Id);
            }
            var registerdKeys = GetApplicationKeysData(applicationName);

            foreach (var item in registerdKeys)
            {
                ApiKeyModel model = new ApiKeyModel();

                model.Active          = item.Active;
                model.AdminKey        = item.AdminKey;
                model.ApplicationName = item.Application.Name;
                model.Key             = item.ApiKey;
                model.LastUsed        = item.LastUsed;

                model.Access = new List <DirectoryAccessModel>();

                foreach (var a in item.Access)
                {
                    if (string.Equals(a.Directory.Application.Name, applicationName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        DirectoryAccessModel access = new DirectoryAccessModel();
                        access.Create    = a.AllowCreate;
                        access.Write     = a.AllowWrite;
                        access.Delete    = a.AllowDelete;
                        access.Directory = a.Directory.Name;
                        model.Access.Add(access);
                    }
                }

                result.Add(model);
            }


            return(result);
        }
Esempio n. 6
0
        public void SetUp()
        {
            httpContext           = new DefaultHttpContext();
            modelState            = new ModelStateDictionary();
            actionContext         = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
            modelMetadataProvider = new EmptyModelMetadataProvider();
            viewData    = new ViewDataDictionary(modelMetadataProvider, modelState);
            tempData    = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>());
            pageContext = new PageContext(actionContext)
            {
                ViewData = viewData
            };

            mockIApiKeyService = new Mock <IApiKeyService>();
            mockConfig         = new Mock <IConfiguration>();
            portFreightUsers   = new List <PortFreightUser>
            {
                new PortFreightUser()
                {
                    Id = "TestUser1", Email = "*****@*****.**", SenderId = "Test1234", UserName = "******"
                },
                new PortFreightUser()
                {
                    Id = "TestUser2", Email = "*****@*****.**", SenderId = "Test5678", UserName = "******"
                }
            };

            mockUserManager = MockUserManager <PortFreightUser>(portFreightUsers);
            mockUserManager.Setup(p => p.GetUserAsync(httpContext.User)).ReturnsAsync(portFreightUsers.FirstOrDefault());

            pageModel = new ApiKeyModel(mockIApiKeyService.Object, mockUserManager.Object, mockConfig.Object)
            {
                PageContext = pageContext,
                TempData    = tempData,
                Url         = new UrlHelper(actionContext)
            };
        }
Esempio n. 7
0
        public ApiKeyModel GetApiKey(string applicationName, string name)
        {
            if (!Auth.AllowReadApiKeys(applicationName))
            {
                throw new SettingsAuthorizationException(AuthorizationScope.ApiKey, AuthorizationLevel.Read, applicationName, Auth.CurrentIdentity.Id);
            }

            var data = GetKeyData(applicationName, name);

            if (data == null)
            {
                throw new SettingsNotFoundException("ApiKey");
            }

            var model = new ApiKeyModel
            {
                Active          = data.Active,
                AdminKey        = data.AdminKey,
                Key             = data.ApiKey,
                ApplicationName = data.Application.Name,
                Name            = data.Name
            };

            model.Access = new List <DirectoryAccessModel>();
            foreach (var item in data.Access)
            {
                model.Access.Add(new DirectoryAccessModel
                {
                    Directory = item.Directory.Name,
                    Create    = item.AllowCreate,
                    Delete    = item.AllowDelete,
                    Write     = item.AllowWrite
                });
            }

            return(model);
        }
Esempio n. 8
0
        public async Task <ActionResult <ApiKeyCreatedViewModel> > CreateApiKey()
        {
            var apiKey = await GetMyApiKey();

            if (apiKey != null)
            {
                database.Delete(apiKey);
            }

            var key = RandomUtil.GetString(Constants.RandomApiKeyLength, Constants.RandomApiKeyChars);

            var keyModel = new ApiKeyModel()
            {
                User    = AuthorizedUser,
                KeyHash = await hasher.GetEncodedHash(key),
            };

            database.Create(keyModel);
            await database.Commit();

            return(Created(
                       $"/api/apikey/{keyModel.Guid}",
                       new ApiKeyCreatedViewModel(keyModel, key)));
        }
Esempio n. 9
0
        public ActionResult GenerateApiKey(int id)
        {
            List <ApiKeyModel> CompanywithKeys = new List <ApiKeyModel>();

            CompanywithKeys = _context.ApiKey.ToList();

            var CompanyValidation = _context.ApiKey.Where(x => x.Company_Id == id).ToList();

            if (ModelState.IsValid && CompanyValidation == null || CompanyValidation.Count() == 0)
            {
                string      guid    = System.Guid.NewGuid().ToString();
                ApiKeyModel keyList = new ApiKeyModel();

                keyList.Company_Id = id;
                keyList.ApiKey     = guid;

                _context.ApiKey.Add(keyList);
                _context.SaveChanges();

                return(RedirectToAction("Index"));
            }

            return(RedirectToAction("Index"));
        }
Esempio n. 10
0
        internal static DataAccessResponseType InsertApiKey(string sqlPartition, string schemaId, ApiKeyModel key)
        {
            DataAccessResponseType response = new DataAccessResponseType();

            StringBuilder SqlStatement = new StringBuilder();

            //SQL Statements =============================================================


            //INSERT =============================================================
            SqlStatement.Append("INSERT INTO  ");
            SqlStatement.Append(schemaId);
            SqlStatement.Append(".ApiKeys (");

            SqlStatement.Append("ApiKey,");
            SqlStatement.Append("Name,");
            SqlStatement.Append("Description,");
            SqlStatement.Append("CreatedDate");

            SqlStatement.Append(") VALUES (");

            //Using parameterized queries to protect against injection
            SqlStatement.Append("@ApiKey, ");
            SqlStatement.Append("@Name, ");
            SqlStatement.Append("@Description, ");
            SqlStatement.Append("@CreatedDate");

            SqlStatement.Append(")");

            //CLOSE: Check Row Count ===========================================================
            //SqlStatement.Append(" END");

            //SqlCommand sqlCommand = new SqlCommand(SqlStatement.ToString(), Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(sqlPartition));
            SqlCommand sqlCommand = Sahara.Core.Settings.Azure.Databases.DatabaseConnections.DatabasePartitionSqlConnection(sqlPartition).CreateCommand();

            sqlCommand.CommandText = SqlStatement.ToString();



            //Using parameterized queries to protect against injection
            sqlCommand.Parameters.Add("@ApiKey", SqlDbType.UniqueIdentifier);
            sqlCommand.Parameters.Add("@Name", SqlDbType.Text);
            sqlCommand.Parameters.Add("@Description", SqlDbType.Text);
            sqlCommand.Parameters.Add("@CreatedDate", SqlDbType.DateTime);

            //Assign values
            sqlCommand.Parameters["@ApiKey"].Value      = key.ApiKey;
            sqlCommand.Parameters["@Name"].Value        = key.Name;
            sqlCommand.Parameters["@Description"].Value = key.Description;
            sqlCommand.Parameters["@CreatedDate"].Value = DateTime.UtcNow;


            // Add output parameters
            //SqlParameter objectCount = sqlCommand.Parameters.Add("@ObjectCount", SqlDbType.Int);
            //objectCount.Direction = ParameterDirection.Output;

            int insertResult = 0;

            sqlCommand.Connection.OpenWithRetry();

            try
            {
                insertResult = sqlCommand.ExecuteNonQueryWithRetry(); // returns Int indicating number of rows affected
                if (insertResult > 0)
                {
                    response.isSuccess = true;
                }
                else
                {
                    /*
                     * if ((int)objectCount.Value >= maxAllowed)
                     * {
                     *  return new DataAccessResponseType
                     *  {
                     *      isSuccess = false,
                     *      ErrorMessage = "Your plan does not allow for more than " + maxAllowed + " image groups. Please upgrade to increase your limits."
                     *      //ErrorMessage = "You have reached the maximum amount of categories for your account. Please upgrade your plan or contact support to increase your limits."
                     *  };
                     * }*/
                }
            }
            catch (Exception e)
            {
                //Log exception and email platform admins
                PlatformExceptionsHelper.LogExceptionAndAlertAdmins(
                    e,
                    "attempting to insert a new api key into SQL",
                    System.Reflection.MethodBase.GetCurrentMethod()
                    );

                response.isSuccess    = false;
                response.ErrorMessage = e.Message;
                return(response);
            }

            sqlCommand.Connection.Close();

            return(response);
        }
Esempio n. 11
0
        public static string GenerateApiKey(Account account, string name, string description)
        {
            var key = new ApiKeyModel {
                Name = name, Description = description
            };

            key.ApiKey = Guid.NewGuid();

            #region validate character lengths

            if (key.Name.Length > 80)
            {
                return(null);
            }
            if (key.Description.Length > 360)
            {
                return(null);
            }

            #endregion

            #region Validate unique name/label & key count

            var keys = GetApiKeys(account);

            if (keys.Count >= 25) //<-- Limit of 25 API Keys
            {
                return(null);
            }

            foreach (var existingKey in keys)
            {
                if (existingKey.Name == name)
                {
                    return(null);
                }
            }



            #endregion


            var response = Sql.Statements.InsertStatements.InsertApiKey(account.SqlPartition, account.SchemaName, key);

            if (response.isSuccess)
            {
                #region Clear Redis Cache

                Internal.Caching.InvalidateApiKeysCache(account.AccountNameKey);

                #endregion

                #region Invalidate Account API Caching Layer

                Sahara.Core.Common.Redis.ApiRedisLayer.InvalidateAccountApiCacheLayer(account.AccountNameKey);

                #endregion

                return(key.ApiKey.ToString());
            }
            else
            {
                return(null);
            }
        }
Esempio n. 12
0
 public ApiKeyCreatedViewModel(ApiKeyModel model, string key) : base(model)
 {
     Key = key;
 }
Esempio n. 13
0
 public ApiKeyViewModel(ApiKeyModel model) : base(model)
 {
     LastAccess  = model.LastAccess;
     AccessCount = model.AccessCount;
 }