public ApiKeyRevokeViewModel(ApiKeyViewModel apiKeyViewModel, string apiKey, string leakedUrl, bool isRevocable)
 {
     ApiKeyViewModel = apiKeyViewModel;
     IsRevocable     = isRevocable;
     ApiKey          = apiKey ?? throw new ArgumentNullException(nameof(apiKeyViewModel));
     LeakedUrl       = leakedUrl ?? throw new ArgumentNullException(nameof(leakedUrl));
 }
        public async Task <IActionResult> Details(int?id)
        {
            var merchantId = await _userService.GetCurrentMerchantId(User);

            var terminal = await _db.Terminal
                           .Include(t => t.ServiceProvider)
                           .Include(t => t.Store)
                           .FirstOrDefaultAsync(t => t.Id == id && t.MerchantId == merchantId);

            if (terminal == null)
            {
                return(NotFound());
            }

            var model = new ApiKeyViewModel()
            {
                Id                  = terminal.Id,
                SerialNumber        = terminal.SerialNumber,
                ApiSecret           = terminal.ApiSecret,
                StoreId             = terminal.StoreId,
                StoreName           = terminal.Store.Name,
                MerchantId          = terminal.MerchantId,
                ServiceProviderId   = terminal.ServiceProviderId,
                ServiceProviderName = terminal.ServiceProvider.Name,
                Name                = terminal.Name,
                Status              = terminal.Status,
                Virtual             = terminal.Virtual
            };

            return(View(model));
        }
Example #3
0
 public async Task <ActionResult <ApiKeyViewModel> > RequestApiKey([FromBody] ApiKeyViewModel apiKeyRequest)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest("Invalid api key model"));
     }
     return(await _generateApiKey(apiKeyRequest));
 }
        public JsonResult Verify(string verifyQuery)
        {
            if (string.IsNullOrWhiteSpace(verifyQuery))
            {
                return(Json(HttpStatusCode.BadRequest, "Invalid empty input!"));
            }

            var queries = verifyQuery.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(q => q.Trim()).ToList();

            var results        = new List <ApiKeyRevokeViewModel>();
            var verifiedApiKey = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var query in queries)
            {
                try
                {
                    var leakedApiKeyInfo = JsonConvert.DeserializeObject <LeakedApiKeyInfo>(query);

                    var apiKey = leakedApiKeyInfo.ApiKey;
                    if (!verifiedApiKey.Add(apiKey))
                    {
                        continue;
                    }
                    var leakedUrl        = leakedApiKeyInfo.LeakedUrl;
                    var revocationSource = leakedApiKeyInfo.RevocationSource;

                    var credential = _authenticationService.GetApiKeyCredential(apiKey);
                    if (credential == null)
                    {
                        results.Add(new ApiKeyRevokeViewModel(apiKeyViewModel: null, apiKey: apiKey, leakedUrl: null, revocationSource: null, isRevocable: false));
                        continue;
                    }

                    var apiKeyViewModel = new ApiKeyViewModel(_authenticationService.DescribeCredential(credential));
                    if (!_authenticationService.IsActiveApiKeyCredential(credential))
                    {
                        results.Add(new ApiKeyRevokeViewModel(apiKeyViewModel, apiKey, leakedUrl: null, revocationSource: apiKeyViewModel.RevocationSource, isRevocable: false));
                        continue;
                    }
                    if (!Enum.TryParse(revocationSource, out CredentialRevocationSource revocationSourceKey))
                    {
                        return(Json(HttpStatusCode.BadRequest, $"Invalid input! {query} is not using the supported Revocation Source: " +
                                    $"{string.Join(",", Enum.GetNames(typeof(CredentialRevocationSource)))}."));
                    }

                    results.Add(new ApiKeyRevokeViewModel(apiKeyViewModel, apiKey, leakedUrl, revocationSource, isRevocable: true));
                }
                catch (JsonException)
                {
                    return(Json(HttpStatusCode.BadRequest, $"Invalid input! {query} is not using the valid JSON format."));
                }
            }

            return(Json(HttpStatusCode.OK, results));
        }
Example #5
0
        public ActionResult ApiKey(ApiKeyViewModel model)
        {
            var result = service.Save(SystemSettingType.ApiKey, model);

            //web reset
            if (result.IsSuccess)
            {
                var applicationHelper = new ApplicationHelper();
                applicationHelper.RemoveAll();
                applicationHelper.Init();
            }

            return(Json(result));
        }
Example #6
0
        public static IList <ApiKeyViewModel> ApiKeys(IList <ApiKey> apiKeysDb)
        {
            var apiKeysViewModel = new List <ApiKeyViewModel>();

            foreach (var apiKey in apiKeysDb)
            {
                var apiKeyUrls      = ApiKeyUrls(apiKey.Urls.ToList());
                var apiKeyViewModel = new ApiKeyViewModel(apiKey.Id, apiKey.Name, apiKey.Base64Secret, apiKey.UserId,
                                                          apiKeyUrls);

                apiKeysViewModel.Add(apiKeyViewModel);
            }

            return(apiKeysViewModel);
        }
Example #7
0
        private bool IsRevocable(ApiKeyViewModel apiKeyViewModel)
        {
            if (apiKeyViewModel == null)
            {
                return(false);
            }
            if (apiKeyViewModel.HasExpired)
            {
                return(false);
            }
            if (!CredentialTypes.IsApiKey(apiKeyViewModel.Type))
            {
                return(false);
            }

            return(true);
        }
        public async Task <IActionResult> EditPost(int id, ApiKeyViewModel model)
        {
            if (id <= 0 || id != model.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var terminal = await _db.Terminal.FindAsync(id);

                    if (terminal == null)
                    {
                        return(NotFound());
                    }

                    terminal.Name              = model.Name;
                    terminal.Status            = model.Status;
                    terminal.StoreId           = model.StoreId;
                    terminal.ServiceProviderId = model.ServiceProviderId;

                    _db.Update(terminal);
                    await _db.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TerminalExists(model.Id))
                    {
                        return(NotFound());
                    }
                    throw;
                }
            }

            var merchantId = await _userService.GetCurrentMerchantId(User);

            ViewData["StoreId"]           = new SelectList(_db.Store.Where(t => t.MerchantId == merchantId), "Id", "Name", model.StoreId);
            ViewData["ServiceProviderId"] = new SelectList(_db.ServiceProvider, "Id", "Name", model.ServiceProviderId);
            return(View(model));
        }
Example #9
0
        public JsonResult Start([FromBody] ApiKeyViewModel vm)
        {
            try
            {
                InitParams(vm);

                // Start a new time entry
                var runningTimeentry = TimeEntryService.Start(new TimeEntry()
                {
                    Description = "IFTTT",
                    CreatedWith = "IFTTT Channel",
                    WorkspaceId = DefaultWorkspacedId
                });

                return(Json(runningTimeentry));
            }
            catch (Exception ex)
            {
                Logger.LogError("Failed to start new time entry", ex);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new { ex.Message }));
            }
        }
Example #10
0
        private async Task <ApiKeyViewModel> _generateApiKey(ApiKeyViewModel apiKeyRequest)
        {
            var prefix       = ApiKeyGenerator.GetApiKey(7);
            var plainTextKey = $"{prefix}.{ApiKeyGenerator.GetApiKey(128)}";

            var salt         = _apiKeyAuthSettings.ApiKeySalt;
            var convertedKey = ApiKeyGenerator.GeneratePasswordHash(plainTextKey, salt);

            var issue = new IssuedApiKey(
                _applicationUser,
                apiKeyRequest.Name,
                apiKeyRequest.Scopes,
                prefix,
                convertedKey);

            _issuedApiKeyRepository.AddOrUpdate(issue);
            await _unitOfWork.CompleteAsync();

            var key = _mapper.Map <ApiKeyViewModel>(issue);

            key.PlainTextKey = plainTextKey;
            return(key);
        }
        public async Task <IActionResult> Edit(int?id)
        {
            var terminal = await _db.Terminal.FindAsync(id);

            if (terminal == null)
            {
                return(NotFound());
            }

            var model = new ApiKeyViewModel
            {
                Name              = terminal.Name,
                Status            = terminal.Status,
                StoreId           = terminal.StoreId,
                ServiceProviderId = terminal.ServiceProviderId
            };

            var merchantId = await _userService.GetCurrentMerchantId(User);

            ViewData["StoreId"]           = new SelectList(_db.Store.Where(t => t.MerchantId == merchantId), "Id", "Name", model.StoreId);
            ViewData["ServiceProviderId"] = new SelectList(_db.ServiceProvider, "Id", "Name", model.ServiceProviderId);
            return(View(model));
        }
Example #12
0
        public JsonResult Stop([FromBody] ApiKeyViewModel vm)
        {
            try
            {
                InitParams(vm);
                // Get running time entry
                var runningTimeEntry = TimeEntryService.Current();
                if (runningTimeEntry.Id != null)
                {
                    var stoppedTimeEntry = TimeEntryService.Stop(runningTimeEntry);
                    return(Json(stoppedTimeEntry));
                }

                Logger.LogError("Unable to find a running time entry.");
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new { Message = "Unable to find a running time entry." }));
            }
            catch (Exception ex)
            {
                Logger.LogError("Failed to stop time entry", ex);
                Response.StatusCode = (int)HttpStatusCode.BadRequest;
                return(Json(new { ex.Message }));
            }
        }
Example #13
0
        public async Task <ActionResult <ApiKeyViewModel> > RegenerateApiKey([FromBody] ApiKeyViewModel apiKeyRequest)
        {
            var existingKey = await _issuedApiKeyRepository.GetAsync(apiKeyRequest.Id);

            if (existingKey is null)
            {
                return(NotFound());
            }

            var newKey = await _generateApiKey(apiKeyRequest);

            if (newKey == null)
            {
                return(BadRequest());
            }

            newKey.Name       = existingKey.Name;
            newKey.DateIssued = DateTime.Today;
            await _issuedApiKeyRepository.DeleteAsync(existingKey.Id);

            await _unitOfWork.CompleteAsync();

            return(newKey);
        }
Example #14
0
 private void InitParams(ApiKeyViewModel vm)
 {
     TogglApiKey = vm.TogglApiKey;
     SetDefaultWorkspace();
 }