Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hyapi #4223

Merged
merged 2 commits into from
Nov 13, 2024
Merged

Hyapi #4223

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CSETWebApi/CSETWeb_Api/CSETWebCore.Helpers/TokenManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -33,6 +34,7 @@ public class TokenManager : ITokenManager
private CSETContext _context;
private static string _secret = null;
private static object _myLockObject = new object();



/// <summary>
Expand Down Expand Up @@ -71,6 +73,24 @@ public void SetToken(string tokenString)
Init(tokenString);
}

/// <summary>
/// set enterprise token for export
/// </summary>
/// <param name="tokenString"></param>
public void SetEnterpriseToken(string tokenString)
{
_enterpriseTokenString = tokenString;
}

/// <summary>
/// retrieve enterprise token for export
/// </summary>
/// <returns></returns>
public string GetEnterpriseToken()
{
return _enterpriseTokenString;
}


/// <summary>
/// Initializes the token if it has not been set but there is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -23,16 +30,19 @@ public class AssessmentExportController : ControllerBase
private ITokenManager _token;
private CSETContext _context;
private IHttpContextAccessor _http;
private readonly IConfiguration _configuration;


/// <summary>
/// Controller
/// </summary>
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;
}


Expand Down Expand Up @@ -60,6 +70,55 @@ public IActionResult ExportAssessment([FromQuery] string token, [FromQuery] stri

return null;
}

/// <summary>
/// export assessment and send it to enterprise using enterprise token
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
[HttpGet]
[Route("api/assessment/exportAndSend")]
public async Task<IActionResult> 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);
}
}


/// <summary>
Expand Down Expand Up @@ -91,5 +150,57 @@ public IActionResult ExportAssessmentAsJson([FromQuery] string token, [FromQuery

return null;
}

/// <summary>
/// Send file to external API
/// </summary>
/// <param name="targetUrl"></param>
/// <param name="fileContents"></param>
/// <param name="fileName"></param>
/// <returns></returns>
private async Task<bool> 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;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"AppCode": "CSET",
"EnterpriseInstallation": "false",
"JWTExpiryMinutes": 60,
"AssessmentUploadUrl": "http://localhost:5001",
"ApiKey": "",
"Logging": {
"LogLevel": {
Expand Down
1 change: 1 addition & 0 deletions CSETWebApi/CSETWeb_Api/CSETWeb_ApiCore/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"AppCode": "CSET",
"EnterpriseInstallation": "false",
"JWTExpiryMinutes": 60,
"AssessmentUploadUrl": "http://localhost:5001",
"ApiKey": "",
"Logging": {
"LogLevel": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
19 changes: 8 additions & 11 deletions CSETWebNg/src/app/services/analytics.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand All @@ -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/";

}
Expand All @@ -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
);
}

Expand Down
4 changes: 2 additions & 2 deletions CSETWebNg/src/app/services/config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class ConfigService {


onlineUrl: string;
analyticsUrl: string = "http://localhost:5278/";
analyticsUrl: string = "http://localhost:5001/";

csetGithubApiUrl: string;
helpContactEmail: string;
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion CSETWebNg/src/assets/navigation/workflow-omni.xml
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@
<!--node displaytext="Assessment Comparison" id="analytics-compare" path="assessment/{:id}/results/analytics-compare" visible="ORIGIN:CF" /-->

<node d="feedback" id="feedback" path="assessment/{:id}/results/feedback" visible="INSTALL-MODE-ANY(CSET,IOD,CIE) SHOW-FEEDBACK" />
<node d="analytics" id="analytics" path="assessment/{:id}/results/analytics" visible="HIDE" />
<node d="analytics" id="analytics" path="assessment/{:id}/results/analytics" visible="SHOW" />

<node d="assessment complete" id="tsa-assessment-complete" path="assessment/{:id}/results/tsa-assessment-complete" visible="INSTALL-MODE:TSA" />

Expand Down
Loading