diff --git a/CSETWebApi/CSETWeb_Api/CSETWebCore.Helpers/TokenManager.cs b/CSETWebApi/CSETWeb_Api/CSETWebCore.Helpers/TokenManager.cs index 17e748fa93..58fcee4ab5 100644 --- a/CSETWebApi/CSETWeb_Api/CSETWebCore.Helpers/TokenManager.cs +++ b/CSETWebApi/CSETWeb_Api/CSETWebCore.Helpers/TokenManager.cs @@ -25,6 +25,7 @@ public class TokenManager : ITokenManager private const string _bearerToken = "Bearer "; private JwtSecurityToken _token = null; private string _tokenString = null; + private string _enterpriseTokenString = null; private IHttpContextAccessor _httpContext; private readonly IConfiguration _configuration; @@ -33,6 +34,7 @@ public class TokenManager : ITokenManager private CSETContext _context; private static string _secret = null; private static object _myLockObject = new object(); + /// @@ -71,6 +73,24 @@ public void SetToken(string tokenString) Init(tokenString); } + /// + /// set enterprise token for export + /// + /// + public void SetEnterpriseToken(string tokenString) + { + _enterpriseTokenString = tokenString; + } + + /// + /// retrieve enterprise token for export + /// + /// + public string GetEnterpriseToken() + { + return _enterpriseTokenString; + } + /// /// Initializes the token if it has not been set but there is diff --git a/CSETWebApi/CSETWeb_Api/CSETWebCore.Interfaces/Helpers/ITokenManager.cs b/CSETWebApi/CSETWeb_Api/CSETWebCore.Interfaces/Helpers/ITokenManager.cs index fe386cc330..f3d72c79bb 100644 --- a/CSETWebApi/CSETWeb_Api/CSETWebCore.Interfaces/Helpers/ITokenManager.cs +++ b/CSETWebApi/CSETWeb_Api/CSETWebCore.Interfaces/Helpers/ITokenManager.cs @@ -17,6 +17,8 @@ namespace CSETWebCore.Interfaces.Helpers public interface ITokenManager { void SetToken(String tokenString); + void SetEnterpriseToken(string tokenString); + string GetEnterpriseToken(); void Init(string tokenString); string Payload(string claim); int? PayloadInt(string claim); diff --git a/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/Controllers/AssessmentExportController.cs b/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/Controllers/AssessmentExportController.cs index a75fa765d0..3f3b7babf4 100644 --- a/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/Controllers/AssessmentExportController.cs +++ b/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/Controllers/AssessmentExportController.cs @@ -13,7 +13,14 @@ using Microsoft.AspNetCore.Mvc; using NLog; using System; +using System.IO; using System.Linq; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Mime; +using System.Threading.Tasks; +using DocumentFormat.OpenXml.Office2010.PowerPoint; +using Microsoft.Extensions.Configuration; namespace CSETWebCore.Api.Controllers @@ -23,16 +30,19 @@ public class AssessmentExportController : ControllerBase private ITokenManager _token; private CSETContext _context; private IHttpContextAccessor _http; + private readonly IConfiguration _configuration; /// /// Controller /// - public AssessmentExportController(ITokenManager token, CSETContext context, IHttpContextAccessor http) + public AssessmentExportController(ITokenManager token, CSETContext context, + IHttpContextAccessor http, IConfiguration configuration) { _token = token; _context = context; _http = http; + _configuration = configuration; } @@ -60,6 +70,55 @@ public IActionResult ExportAssessment([FromQuery] string token, [FromQuery] stri return null; } + + /// + /// export assessment and send it to enterprise using enterprise token + /// + /// + /// + [HttpGet] + [Route("api/assessment/exportAndSend")] + public async Task ExportAndSendAssessment([FromQuery] string token) + { + try + { + var assessmentId = _token.AssessmentForUser(); + _token.SetEnterpriseToken(token); + + string url = _configuration["AssessmentUploadUrl"]; + // Export the assessment + if (!string.IsNullOrEmpty(url)) + { + var exportManager = new AssessmentExportManager(_context); + var exportFile = exportManager.ExportAssessment(assessmentId, ".zip", string.Empty, string.Empty); + + string ext = IOHelper.GetExportFileExtension(_token.Payload(Constants.Constants.Token_Scope)); + + AssessmentExportFile result = + new AssessmentExportManager(_context).ExportAssessment(assessmentId, ext, string.Empty, + string.Empty); + byte[] fileContents; + using (var memoryStream = new MemoryStream()) + { + result.FileContents.CopyTo(memoryStream); + fileContents = memoryStream.ToArray(); + } + + bool isSuccess = await SendFileToApi($"{url}/api/assessment/import", fileContents, result.FileName); + if (isSuccess) + { + return Ok("Assessment uploaded successfully"); + } + } + + return BadRequest("There was an error sending the assessment to the target URL"); + } + catch (Exception exc) + { + NLog.LogManager.GetCurrentClassLogger().Error($"... {exc}"); + return StatusCode(500, exc.Message); + } + } /// @@ -91,5 +150,57 @@ public IActionResult ExportAssessmentAsJson([FromQuery] string token, [FromQuery return null; } + + /// + /// Send file to external API + /// + /// + /// + /// + /// + private async Task SendFileToApi(string targetUrl, byte[] fileContents, string fileName) + { + try + { + + using(var client = new HttpClient()) + using(var content = new MultipartFormDataContent()) + using (var byteContent = new ByteArrayContent(fileContents)) + { + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", _token.GetEnterpriseToken()); + byteContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); + + content.Add(byteContent, "file", "assessment.csetw"); + var response = await client.PostAsync(targetUrl, content); + return response.IsSuccessStatusCode; + + } + + ; + /*using (var client = new System.Net.Http.HttpClient()) + { + using(var client = httpClient) + + + var content = new System.Net.Http.ByteArrayContent(fileContents); + client.DefaultRequestHeaders.Authorization = + new AuthenticationHeaderValue("Bearer", _token.GetEnterpriseToken()); + + content.Headers.Add("Content-Type", "multipart/form-data"); + content.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\""); + //content.Headers.Add("Authorization", $"Bearer {_token.GetEnterpriseToken()}"); + + var response = await client.PostAsync(targetUrl, content); + return response.IsSuccessStatusCode; + }*/ + } + catch (Exception exc) + { + NLog.LogManager.GetCurrentClassLogger().Error($"... {exc}"); + } + + return false; + } } } diff --git a/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.Development.json b/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.Development.json index e18a8738d6..028d24f223 100644 --- a/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.Development.json +++ b/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.Development.json @@ -6,6 +6,7 @@ "AppCode": "CSET", "EnterpriseInstallation": "false", "JWTExpiryMinutes": 60, + "AssessmentUploadUrl": "http://localhost:5001", "ApiKey": "", "Logging": { "LogLevel": { diff --git a/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.json b/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.json index adea0af85d..0ffe2b43e8 100644 --- a/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.json +++ b/CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.json @@ -6,6 +6,7 @@ "AppCode": "CSET", "EnterpriseInstallation": "false", "JWTExpiryMinutes": 60, + "AssessmentUploadUrl": "http://localhost:5001", "ApiKey": "", "Logging": { "LogLevel": { diff --git a/CSETWebNg/src/app/assessment/results/analysis/analytics-login/analytics-login.component.ts b/CSETWebNg/src/app/assessment/results/analysis/analytics-login/analytics-login.component.ts index a35ff8c97b..f9f00d21e0 100644 --- a/CSETWebNg/src/app/assessment/results/analysis/analytics-login/analytics-login.component.ts +++ b/CSETWebNg/src/app/assessment/results/analysis/analytics-login/analytics-login.component.ts @@ -67,7 +67,7 @@ export class AnalyticsloginComponent implements OnInit { data => { let token = data.token; console.log(token); - this.analyticsSvc.postAnalyticsWithLogin(this.analytics, token).subscribe( + this.analyticsSvc.postAnalyticsWithLogin(token).subscribe( (data: any) => { this.dialogMat.open(AlertComponent, { data: { diff --git a/CSETWebNg/src/app/services/analytics.service.ts b/CSETWebNg/src/app/services/analytics.service.ts index 69bc7b2661..fdb0c8a306 100644 --- a/CSETWebNg/src/app/services/analytics.service.ts +++ b/CSETWebNg/src/app/services/analytics.service.ts @@ -8,6 +8,7 @@ import { ConfigService } from './config.service'; }) export class AnalyticsService { private apiUrl: string; + private baseUrl: string; private analyticsUrl: string; public headers = { headers: new HttpHeaders().set('Content-Type', 'application/json'), @@ -17,7 +18,8 @@ export class AnalyticsService { constructor(private http: HttpClient, private configSvc: ConfigService) { - this.apiUrl = this.configSvc.apiUrl + "analytics/"; + this.baseUrl = this.configSvc.apiUrl; + this.apiUrl = this.baseUrl + "analytics/"; this.analyticsUrl = this.configSvc.analyticsUrl + "api/"; } @@ -28,20 +30,15 @@ export class AnalyticsService { getAnalyticsToken(username, password): any { return this.http.post( - this.analyticsUrl + 'auth/login', { username, password }, this.headers + this.analyticsUrl + 'auth/login', { "email":username, password }, this.headers ); } - postAnalyticsWithLogin(analytics, token): any { - let header: HttpHeaders = new HttpHeaders(); - header = header.append('Content-Type', 'application/json'); - header = header.append("Authorization", "Bearer " + token); - console.log(token); - console.log(analytics); - let params: HttpParams = new HttpParams(); - return this.http.post( - this.analyticsUrl + 'assessment/saveassessment', analytics, { headers: header, params } + postAnalyticsWithLogin(token): any { + + return this.http.get( + this.baseUrl + 'assessment/exportandsend?token='+token ); } diff --git a/CSETWebNg/src/app/services/config.service.ts b/CSETWebNg/src/app/services/config.service.ts index 099fddb315..07d460a7a4 100644 --- a/CSETWebNg/src/app/services/config.service.ts +++ b/CSETWebNg/src/app/services/config.service.ts @@ -65,7 +65,7 @@ export class ConfigService { onlineUrl: string; - analyticsUrl: string = "http://localhost:5278/"; + analyticsUrl: string = "http://localhost:5001/"; csetGithubApiUrl: string; helpContactEmail: string; @@ -196,7 +196,7 @@ export class ConfigService { } this.appUrl = appProtocol + this.config.app.host + appPort; - this.analyticsUrl = "http://localhost:5278/"; + this.analyticsUrl = "http://localhost:5001/"; this.helpContactEmail = this.config.helpContactEmail; this.helpContactPhone = this.config.helpContactPhone; this.csetGithubApiUrl = this.config.csetGithubApiUrl; diff --git a/CSETWebNg/src/assets/navigation/workflow-omni.xml b/CSETWebNg/src/assets/navigation/workflow-omni.xml index 8a7ff95db9..21eba0ee2a 100644 --- a/CSETWebNg/src/assets/navigation/workflow-omni.xml +++ b/CSETWebNg/src/assets/navigation/workflow-omni.xml @@ -421,7 +421,7 @@ - +