public static string Parse(HttpContext httpContext) { try { TPaaSJWT jwt = null; if (httpContext.Request.Headers.TryGetValue("X-JWT-Assertion", out StringValues headerValues)) { jwt = new TPaaSJWT(headerValues); } string userIdString = null; if (jwt != null && jwt.IsApplicationUserToken) { userIdString = jwt.UserUid.ToString(); } else if (httpContext.Request.Headers.TryGetValue("X-VisionLink-UserUid", out StringValues values)) { userIdString = values.FirstOrDefault(); } return(string.IsNullOrEmpty(userIdString)?"NoUserDataAvailable": userIdString); } catch { return("Could not parse X-VisionLink-UserUid or X-JWT-Assertion Headers in Request"); } }
public override void OnActionExecuting(ActionExecutingContext actionContext) { try { string userIdString = null; TPaaSJWT jwt = null; if (actionContext.HttpContext.Request.Headers.TryGetValue("X-JWT-Assertion", out StringValues headerValues)) { jwt = new TPaaSJWT(headerValues); } if (jwt != null) { userIdString = jwt.UserUid.ToString(); } else if (actionContext.HttpContext.Request.Headers.TryGetValue("X-VisionLink-UserUid", out headerValues)) { userIdString = headerValues.First(); } actionContext.ActionArguments[_parameterName] = string.IsNullOrEmpty(userIdString) ? (Guid?)null : new Guid(userIdString); } catch { actionContext.Result = new BadRequestObjectResult("Could not validate X-VisionLink-UserUid or X-JWT-Assertion Headers in Request"); } }
/// <summary> /// Action filter method for UserUidParserAttribute /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(ActionExecutingContext actionContext) { try { StringValues headerValues = new StringValues(); string userIdString = null; //UserType userType; var jwt = new TPaaSJWT(actionContext.HttpContext.Request.Headers["X-JWT-Assertion"].ToString()); //Enum.TryParse(jwt.UserType, out userType); if (jwt != null && jwt.IsApplicationUserToken) { userIdString = jwt.UserUid.ToString(); } else if (actionContext.HttpContext.Request.Headers.TryGetValue("X-VisionLink-UserUid", out headerValues)) { userIdString = headerValues.First(); } actionContext.HttpContext.Request.Headers.Add("UserUID_IdentityAPI", userIdString); } catch { throw; } }
private Guid?GetUserContext() { string userIdString = null; TPaaSJWT jwt = null; if (Request.Headers.TryGetValue("X-JWT-Assertion", out StringValues headerValues)) { try { jwt = new TPaaSJWT(headerValues); } catch (Exception esx) { jwt = null; } } if (jwt != null && jwt.IsApplicationUserToken) { userIdString = jwt.UserUid.ToString(); } else if (Request.Headers.TryGetValue("X-VisionLink-UserUid", out headerValues)) { userIdString = headerValues.First(); } return(string.IsNullOrEmpty(userIdString) ? (Guid?)null : new Guid(userIdString)); }
/// <summary> /// /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(ActionExecutingContext actionContext) { try { string userIdString = null; if (!string.IsNullOrEmpty(actionContext.HttpContext.Request.Headers["X-VisionLink-UserUid"].ToString())) { userIdString = actionContext.HttpContext.Request.Headers["X-VisionLink-UserUid"].ToString(); } else if (actionContext.HttpContext.Request.Headers.ContainsKey("X-JWT-Assertion")) { var jwt = new TPaaSJWT(actionContext.HttpContext.Request.Headers["X-JWT-Assertion"]); if (jwt != null) { userIdString = jwt.UserUid.ToString(); } } else { actionContext.Result = new BadRequestObjectResult("Could not find X-VisionLink-UserUid or X-JWT-Assertion Headers in Request"); } if (!actionContext.ActionArguments.ContainsKey(_parameterName)) { actionContext.ActionArguments.Add(_parameterName, string.IsNullOrEmpty(userIdString) ? (Guid?)null : new Guid(userIdString)); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Action filter method for UserUidParserAttribute /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(ActionExecutingContext actionContext) { try { TPaaSJWT jwt = null; if (actionContext.HttpContext.Request.Headers.TryGetValue("X-JWT-Assertion", out StringValues headerValues)) { jwt = new TPaaSJWT(headerValues); } string userIdString = null; if (jwt != null && jwt.IsApplicationUserToken) { userIdString = jwt.UserUid.ToString(); } else if (actionContext.HttpContext.Request.Headers.TryGetValue("X-VisionLink-UserUid", out StringValues values)) { userIdString = values.FirstOrDefault(); } actionContext.HttpContext.Request.Headers.Add(Constants.USERUID_APIRequest, userIdString); } catch { actionContext.Result = new BadRequestObjectResult("Could not validate X-VisionLink-UserUid or X-JWT-Assertion Headers in Request"); } }
public void GetDeviceDetailsByAssetUID_ApplicationToken_OtherThanKiewit_NoAccess() { var deviceUid = Guid.NewGuid(); List <AssetDevicePropertiesV2> retList = new List <AssetDevicePropertiesV2>(); retList.Add(new AssetDevicePropertiesV2 { DeviceUID = deviceUid, DeviceType = "PL641", DeviceState = 1 }); _deviceService.GetDevicePropertiesV2ByAssetGuid(Arg.Any <Guid>()).Returns(retList); _deviceService.GetCustomersForApplication(Arg.Any <string>()).Returns(new List <Guid> { Guid.NewGuid() });; _target.ControllerContext.HttpContext.Request.Headers["UserUID_APIRequest"] = Guid.NewGuid().ToString(); var aa = TPaaSJWT.GenerateFakeApplicationJWT("MasterDataManagement"); var result = _target.GetDeviceDetailsByAssetUID(deviceUid, aa.EncodedJWT); //Assert Assert.Equal(typeof(BadRequestObjectResult), result.GetType()); _deviceService.Received(0).GetDevicePropertiesV2ByAssetGuid(Arg.Any <Guid>()); Assert.Equal("Application does not have Access. Please contact your API administrator.", ((BadRequestObjectResult)result).Value); }
public void GetDeviceDetailsByAssetUID_ApplicationToken_Kiewit_Success() { var assetUID = Guid.NewGuid(); List <AssetDevicePropertiesV2> retList = new List <AssetDevicePropertiesV2>(); retList.Add(new AssetDevicePropertiesV2 { DeviceUID = assetUID, DeviceType = "PL641", DeviceState = 1 }); _deviceService.GetDevicePropertiesV2ByAssetGuid(Arg.Any <Guid>()).Returns(retList); _deviceService.GetCustomersForApplication(Arg.Any <string>()).Returns(new List <Guid> { new Guid("E6E2F851-44C5-E311-AA77-00505688274D") }); _target.ControllerContext.HttpContext.Request.Headers["UserUID_APIRequest"] = Guid.NewGuid().ToString(); var aa = TPaaSJWT.GenerateFakeApplicationJWT("MasterDataManagement"); var result = _target.GetDeviceDetailsByAssetUID(assetUID, aa.EncodedJWT); //Assert Assert.Equal(typeof(OkObjectResult), result.GetType()); Assert.IsType <OkObjectResult>(result); _deviceService.Received(1).GetDevicePropertiesV2ByAssetGuid(Arg.Any <Guid>()); }
public override void OnActionExecuting(ActionExecutingContext actionContext) { try { IEnumerable <string> headerValues = new List <string>(); string userIdString = null; TPaaSJWT jwt = null; userIdString = actionContext.HttpContext.Request.Headers.ContainsKey("X-VisionLink-UserUid") ? actionContext.HttpContext.Request.Headers["X-VisionLink-UserUid"].FirstOrDefault() : null; if (userIdString == null) { string encodedJwt = actionContext.HttpContext.Request.Headers.ContainsKey("X-JWT-Assertion") ? actionContext.HttpContext.Request.Headers["X-JWT-Assertion"].FirstOrDefault() : null; if (encodedJwt != null) { jwt = new TPaaSJWT(encodedJwt); } } if (jwt != null) { userIdString = jwt.UserUid.ToString(); } if (!actionContext.ActionArguments.ContainsKey(_parameterName)) { actionContext.ActionArguments[_parameterName] = string.IsNullOrEmpty(userIdString) ? (Guid?)null : new Guid(userIdString); } } catch { actionContext.Result = new BadRequestObjectResult("Could not validate X-VisionLink-UserUid or X-JWT-Assertion Headers in Request"); } }
public IActionResult GetAssociatedDealersCustomer([FromHeader(Name = "X-JWT-Assertion")] string JWTAssertion) { try { if (!string.IsNullOrEmpty(JWTAssertion)) { var jwt = new TPaaSJWT(JWTAssertion); logger.LogInformation($"Started getting associated customers for user: {jwt.UserUid}"); List <DbCustomer> customersList = customerService.GetAssociatedCustomersbyUserUid(jwt.UserUid); if (customersList.Count(customer => customer.fk_CustomerTypeID == (long)CustomerType.Dealer) == 1) { //Selecting the first dealer var selectedDealer = customersList.First(d => d.fk_CustomerTypeID == (long)CustomerType.Dealer); logger.LogInformation($"Selecting Associated Customers for the dealer" + $" {selectedDealer.CustomerUID}"); List <DbCustomer> dealersAssetBasedCustomers = customerService.GetAssociatedCustomersForDealer(selectedDealer.CustomerUID); if (dealersAssetBasedCustomers?.Count > 0) { logger.LogDebug($"Found {dealersAssetBasedCustomers.Count}" + $" customers under this dealer {selectedDealer.CustomerUID}"); List <ClientModel.Customer> customersListResult = dealersAssetBasedCustomers .ConvertAll(c => new ClientModel.Customer() { CustomerName = c.CustomerName, CustomerUID = c.CustomerUID, CustomerType = Enum.Parse <CustomerType>(c.fk_CustomerTypeID.ToString()) .ToString().ToUpper() }); return(new JsonResult(customersListResult) { StatusCode = (int)HttpStatusCode.OK }); } logger.LogInformation($"No Customers found under this dealer {selectedDealer.CustomerUID}"); } else { logger.LogInformation($"No Dealers found under this user {jwt.UserUid}"); } return(new JsonResult(new List <ClientModel.Customer>()) { StatusCode = (int)HttpStatusCode.OK }); } logger.LogInformation(Messages.JWTTokenEmpty); return(BadRequest(Messages.JWTTokenEmpty)); } catch (Exception ex) { logger.LogError(string.Format(Messages.ExceptionOccured, ex.Message, ex.StackTrace)); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } }
public void CanGenerateFakeApplicationJWTFromAcceptanceTests() { var jwt = TPaaSJWT.GenerateFakeApplicationJWT("MyApplication"); Assert.Equal("MyApplication", jwt.ApplicationName); Assert.False(jwt.IsApplicationUserToken); Assert.True(jwt.IsApplicationToken); }
public void CanValidateAndDecodeLegitimateTPaaSUserJWT() { var jwt = new TPaaSJWT(ValidTPaaSUserJWT2); Assert.Equal(_validTPaaSUserJWT2UserUid, jwt.UserUid); Assert.True(jwt.IsApplicationUserToken); Assert.False(jwt.IsApplicationToken); }
public void ToString_WithClaims_ReturnsString() { var jwt = new TPaaSJWT(ValidTPaaSApplicationJWT); var jwtToString = jwt.ToString(); Assert.NotNull(jwtToString); Assert.Contains("[http://wso2.org/claims/applicationname, MasterDataManagement]", jwtToString); }
public void CanGenerateFakeUserJWTFromAcceptanceTests() { var userUid = Guid.NewGuid(); var jwt = TPaaSJWT.GenerateFakeApplicationUserJWT(userUid); Assert.Equal(userUid, jwt.UserUid); Assert.Equal("VL2.0", jwt.ApplicationName); Assert.True(jwt.IsApplicationUserToken); Assert.False(jwt.IsApplicationToken); }
public void CanDecodeLegitimateTPaaSUserJWTWithoutValidating() { var jwt = new TPaaSJWT(ValidTPaaSUserJWT); Assert.Equal(ValidTPaaSUserJWT, jwt.EncodedJWT); Assert.Equal(_validTPaaSUserJWTUserUid, jwt.UserUid); Assert.Equal("Alpha-VLUnifiedFleet", jwt.ApplicationName); Assert.True(jwt.IsApplicationUserToken); Assert.False(jwt.IsApplicationToken); Assert.Equal("*****@*****.**", jwt.EmailAddress); Assert.Equal("Clay", jwt.Claims["http://wso2.org/claims/firstname"]); }
public void CanDecodeJWTFromHTTPHeaders() { var headers = new HttpClient().DefaultRequestHeaders; headers.Add("X-JWT-Assertion", ValidTPaaSUserJWT); var jwt = new TPaaSJWT(headers); Assert.Equal(_validTPaaSUserJWTUserUid, jwt.UserUid); Assert.True(jwt.IsApplicationUserToken); Assert.False(jwt.IsApplicationToken); }
public static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Please pass in a user id as a command line parameter (e.g. dotnet run cb0ebe8a-b960-4f5d-8552-0439f5f0dfe6)"); Environment.Exit(1); } var jwt = TPaaSJWT.GenerateFakeApplicationUserJWT(Guid.Parse(args[0])); Console.WriteLine($"X-JWT-Assertion: {jwt.EncodedJWT}"); }
public void CanDecodeLegitimateTPaaSApplicationJWTWithoutValidating() { var jwt = new TPaaSJWT(ValidTPaaSApplicationJWT); Assert.Equal(ValidTPaaSApplicationJWT, jwt.EncodedJWT); Assert.Equal(_validTPaaSApplicationJWTUserUid, jwt.UserUid); Assert.Equal(_validTPaaSApplicationJWTApplicationName, jwt.ApplicationName); Assert.Equal(_validTPaaSApplicationJWTApplicationId, jwt.ApplicationId); Assert.Equal(_validTPaaSApplicationJWTApplicationContext, jwt.ApiContext); Assert.Equal(_validTPaaSApplicationJWTVersion, jwt.Version); Assert.False(jwt.IsApplicationUserToken); Assert.True(jwt.IsApplicationToken); }
public async Task Invoke(HttpContext context) { if (!context.Request.Path.Value.Contains("swagger")) { bool requiresCustomerUid = true; //context.Request.Method.ToUpper() == "GET"; Actually we do need to have customerUId regardless request string authorization = context.Request.Headers["X-Jwt-Assertion"]; string customerUID = context.Request.Headers["X-VisionLink-CustomerUid"]; // If no authorization header found, nothing to process further if (string.IsNullOrEmpty(authorization) || (requiresCustomerUid && string.IsNullOrEmpty(customerUID))) { await SetResult("No account selected", context); return; } // If no token found, no further work possible if (string.IsNullOrEmpty(authorization)) { await SetResult("No authentication token", context); return; } try { var jwtToken = new TPaaSJWT(token); var identity = string.IsNullOrEmpty(customerUID) ? new GenericIdentity(jwtToken.UserUid.ToString()) : new GenericIdentity(jwtToken.UserUid.ToString(), customerUID); context.User = new GenericPrincipal(identity, new string[] { }); } catch (Exception e) { await SetResult("Invalid authentication", context); return; } } await _next.Invoke(context); }
public IActionResult GetAssociatedCustomers([FromHeader(Name = "X-JWT-Assertion")] string JWTAssertion) { try { if (!string.IsNullOrEmpty(JWTAssertion)) { var jwt = new TPaaSJWT(JWTAssertion); logger.LogInformation($"Started getting associated customers for user: {jwt.UserUid}"); List <DbCustomer> customersList = customerService.GetAssociatedCustomersbyUserUid(jwt.UserUid); List <AssociatedCustomer> associatedCustomers = customersList.Select(c => new AssociatedCustomer() { CustomerUID = c.CustomerUID, CustomerName = c.CustomerName, CustomerType = Enum.Parse <CustomerType>(c.fk_CustomerTypeID.ToString()) })?.ToList(); logger.LogInformation($"Retrieved {associatedCustomers.Count} associated customers " + $"for user: {jwt.UserUid}"); return(Ok(new CustomerListSuccessResponse() { Status = HttpStatusCode.OK, Metadata = new Metadata { Message = "Customers retrieved successfully" }, Customers = associatedCustomers })); } return(BadRequest()); } catch (Exception ex) { logger.LogError(string.Format(Messages.ExceptionOccured, ex.Message, ex.StackTrace)); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } }
public async Task Invoke(HttpContext context) { string authorization = context.Request.Headers[HeaderConstants.X_JWT_ASSERTION]; try { var jwtToken = new TPaaSJWT(authorization); var isApplicationContext = jwtToken.IsApplicationToken; var applicationName = jwtToken.ApplicationName; var userEmail = isApplicationContext ? applicationName : jwtToken.EmailAddress; var userUid = isApplicationContext ? jwtToken.ApplicationId : jwtToken.UserUid.ToString(); context.User = new EntitlementUserClaim(new GenericIdentity(userUid), userEmail, applicationName, isApplicationContext); } catch (Exception e) { log.LogWarning(e, "Invalid authentication with exception"); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; await context.Response.WriteAsync("Failed Authentication"); } await _next.Invoke(context); }
public IActionResult GetAccountHierarchy([FromHeader(Name = "X-JWT-Assertion")] string JWTAssertion, string targetCustomerUid = "", bool topLevelsOnly = false) { try { if (string.IsNullOrEmpty(JWTAssertion)) { logger.LogError(Messages.JWTTokenEmpty); return(BadRequest(Messages.JWTTokenEmpty)); } var jwt = new TPaaSJWT(JWTAssertion); var targetUserUid = jwt.UserUid; var sw = new Stopwatch(); sw.Start(); var customerHierarchyInformation = customerService.GetHierarchyInformationForUser( targetUserUid.ToString(), targetCustomerUid, topLevelsOnly); sw.Stop(); logger.LogDebug("TIME TAKEN GetAccountHierarchy took {0} ms.", sw.ElapsedMilliseconds); return(new JsonResult(customerHierarchyInformation, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }) { StatusCode = (int)HttpStatusCode.OK }); } catch (Exception ex) { logger.LogError(string.Format(Messages.ExceptionOccured, ex.Message, ex.StackTrace)); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } }
/// <summary> /// Invokes the specified context. /// </summary> public async Task Invoke(HttpContext context) { if (IgnoredPaths.Select(s => context.Request.Path.Value.Contains(s)).Contains(true)) { await _next(context); return; } if (!InternalConnection(context)) { bool isApplicationContext; string applicationName; string userUid; string userEmail; var customerUid = string.Empty; string customerName; // todo temporary to look into user info while we test. log.LogDebug($"{nameof(Invoke)}: TIDAuth context Headers {JsonConvert.SerializeObject(context.Request.Headers, Formatting.None)}"); string authorization = context.Request.Headers["X-Jwt-Assertion"]; log.LogDebug($"{nameof(Invoke)}: TIDAuth authorization {JsonConvert.SerializeObject(authorization)}"); // If no authorization header found, nothing to process further // note keep these result messages vague (but distinct): https://www.gnucitizen.org/blog/username-enumeration-vulnerabilities/ if (string.IsNullOrEmpty(authorization)) { log.LogWarning("No account selected for the request"); await SetResult("No account selected", context); return; } try { var jwtToken = new TPaaSJWT(authorization); isApplicationContext = jwtToken.IsApplicationToken; applicationName = jwtToken.ApplicationName; userEmail = isApplicationContext ? applicationName : jwtToken.EmailAddress; userUid = isApplicationContext ? jwtToken.ApplicationId : jwtToken.UserUid.ToString(); if (isApplicationContext) { // Applications can override the User ID, so we can fetch 'per user' information // E.g Scheduled reports needs to get the Preferences for the user they are running on behalf of, not the Report Server settings. var overrideUserUid = context.Request.Headers[HeaderConstants.X_VISION_LINK_USER_UID]; if (!string.IsNullOrEmpty(overrideUserUid)) { log.LogInformation($"Overriding User ID via {HeaderConstants.X_VISION_LINK_USER_UID} header with {overrideUserUid}, for application request from {applicationName}."); userUid = overrideUserUid; } } } catch (Exception e) { log.LogWarning(e, "Invalid authentication with exception"); await SetResult("Invalid authentication", context); return; } var requireCustomerUid = RequireCustomerUid(context); if (requireCustomerUid) { customerUid = context.Request.Headers["X-VisionLink-CustomerUID"]; } // If required customer not provided, nothing to process further if (string.IsNullOrEmpty(customerUid) && requireCustomerUid) { log.LogWarning("No account found for the request"); await SetResult("No account found", context); return; } var customHeaders = context.Request.Headers.GetCustomHeaders(); //If this is an application context do not validate user-customer if (isApplicationContext) { log.LogInformation( $"Authorization: Calling context is 'Application' for Customer: {customerUid} Application: {userUid} ApplicationName: {applicationName}"); customerName = "Application"; } // User must have be authenticated against this customer else if (requireCustomerUid) { try { // the TID userId is the guid portion of the TRN var customer = await accountClient.GetMyAccount(new Guid(userUid), new Guid(customerUid), customHeaders); if (customer == null) { var error = $"User {userUid} is not authorized to configure this customer {customerUid}"; log.LogWarning(error); await SetResult(error, context); return; } // do we need to check entitlements? If so, this will call out to an another service to check. if (RequireEntitlementValidation(context)) { var entitlementRequest = new EntitlementRequestModel { Feature = EntitlementFeature, Sku = EntitlementSku, OrganizationIdentifier = customerUid, UserUid = userUid, UserEmail = userEmail }; var result = await _entitlementProxy.IsEntitled(entitlementRequest, customHeaders); if (result == null || !result.IsEntitled) { log.LogWarning($"No entitlement for the request"); await SetResult($"User is not entitled to use feature `{EntitlementFeature}` for product `{EntitlementSku}`", context); return; } log.LogInformation($"User is entitled to use feature `{EntitlementFeature}` for product `{EntitlementSku}`"); } customerName = customer.Name; } catch (Exception e) { log.LogWarning( $"Unable to access the 'accountClient.GetMyAccount' Message: {e.Message}."); await SetResult("Failed authentication", context); return; } } else { customerName = "Unknown"; } log.LogInformation($"Authorization: for Customer: {customerUid} userUid: {userUid} userEmail: {userEmail} allowed"); //Set calling context Principal context.User = CreatePrincipal(userUid, customerUid, customerName, userEmail, isApplicationContext, customHeaders, applicationName); } await _next.Invoke(context); }
public void CanDecodeJWTWithArrayValue() { var jwt = new TPaaSJWT(JWTWithArrayValue); Assert.Equal("qxCCyfRLZRWuIuk9hbUsA1uty0ca", ((Newtonsoft.Json.Linq.JArray)jwt.Claims["aud"])[0]); }
public ActionResult UpdateAssetInfo([FromBody] UpdateAssetEvent assetEvent) { try { if (HasNoDataToUpdate(assetEvent)) { return(BadRequest("Update Request should have atleast one data to update")); } if (!Request.Headers.TryGetValue("X-JWT-Assertion", out StringValues headerValues)) { return(BadRequest("Could not validate X-VisionLink-UserUid or X-JWT-Assertion Headers in Request")); } TPaaSJWT jwt; try { jwt = new TPaaSJWT(headerValues); } catch { jwt = null; } if (jwt != null) { _logger.LogInformation("Creating asset for user: {0}", jwt.UserUid); } else { return(BadRequest("Could not validate X-VisionLink-UserUid or X-JWT-Assertion Headers in Request")); } _logger.LogDebug($"UpdateAsset - Calling Application Name: {jwt.ApplicationName}, UserType: {jwt.UserType}"); ClientModel.Asset assetDetails = _assetService.GetAsset(assetEvent.AssetUID.Value); if (assetDetails == null || assetDetails.StatusInd == 0) { return(BadRequest("Asset does not exist")); } bool isCGIntegrator = jwt.UserType == "APPLICATION" && jwt.ApplicationName == _configuration["CGIntegratorAppName"]; if (isCGIntegrator) { if (assetEvent.OwningCustomerUID == null || assetEvent.OwningCustomerUID == Guid.Empty) { if (!string.IsNullOrEmpty(assetDetails.OwningCustomerUID) && Guid.Parse(assetDetails.OwningCustomerUID) == kiewitAMPCustomerUID) { // get current AssetId from DB and update assetEvent.AssetName = assetDetails.AssetName; } } else if (assetEvent.OwningCustomerUID == kiewitAMPCustomerUID) { // get current AssetId from DB and update assetEvent.AssetName = assetDetails.AssetName; } } if (assetEvent.LegacyAssetID == 0) // retain it { assetEvent.LegacyAssetID = assetDetails.LegacyAssetID; } assetEvent.ReceivedUTC = DateTime.UtcNow; if (_assetService.UpdateAsset(assetEvent)) { return(Ok(assetEvent.AssetUID.ToString())); } return(BadRequest("Unable to save to db. Make sure request is not duplicated and all keys exist")); } catch (Exception ex) { _logger.LogError("Update Asset Exception: " + ex.Message); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } }
public ActionResult CreateAsset([FromBody] CreateAssetEvent asset) { try { //var jwt = GetSampleJwt(); //use this for testing locally if (!Request.Headers.TryGetValue("X-JWT-Assertion", out StringValues headerValues)) { return(BadRequest("Could not validate X-VisionLink-UserUid or X-JWT-Assertion Headers in Request")); } TPaaSJWT jwt; try { jwt = new TPaaSJWT(headerValues); } catch (Exception ex) { jwt = null; } if (jwt != null) { _logger.LogInformation("Creating asset for user: {0}", jwt.UserUid); } else { return(BadRequest("no jwt token")); } asset.ReceivedUTC = DateTime.UtcNow; _logger.LogDebug($"CreateAsset - Calling Application Name: {jwt.ApplicationName}, UserType: {jwt.UserType}"); bool isCGIntegrator = jwt.UserType == "APPLICATION" && jwt.ApplicationName == _configuration["CGIntegratorAppName"]; if (isCGIntegrator) { if (asset.AssetUID == null || asset.AssetUID.Equals(Guid.Empty) || !Guid.TryParse(asset.AssetUID.ToString(), out Guid g)) { return(BadRequest("AssetUID must be given for VisionLink integrator")); } if (asset.OwningCustomerUID == null) { asset.OwningCustomerUID = new Guid(); } } else if (!string.IsNullOrEmpty(jwt.ApplicationName)) { asset.AssetUID = Guid.NewGuid(); var customers = _assetService.GetCustomersForApplication(jwt.ApplicationName); if (customers?.Count > 0) { if (asset.OwningCustomerUID == null) { asset.OwningCustomerUID = customers.First(); } } else { return(BadRequest("Application does not have any customers mapped. Please contact your API administrator.")); } Guid?existingAssetGuid = _assetService.GetAssetUid(asset.AssetUID.Value, asset.MakeCode, asset.SerialNumber); if (existingAssetGuid.HasValue) { return(StatusCode((int)HttpStatusCode.Conflict, (existingAssetGuid.Value.ToString()))); } } else { return(BadRequest("jwt application name is empty")); } Guid?existingAsset = _assetService.GetAssetUid(asset.AssetUID.Value, asset.MakeCode, asset.SerialNumber); if (existingAsset.HasValue) { if (isCGIntegrator) { var updatePayload = new UpdateAssetEvent { AssetUID = existingAsset.Value, OwningCustomerUID = asset.OwningCustomerUID, LegacyAssetID = asset.LegacyAssetID, AssetName = asset.AssetName, Model = asset.Model, AssetType = asset.AssetType, IconKey = asset.IconKey, EquipmentVIN = asset.EquipmentVIN, ModelYear = asset.ModelYear, ActionUTC = DateTime.UtcNow, ObjectType = asset.ObjectType, Category = asset.Category, ProjectStatus = asset.ProjectStatus, SortField = asset.SortField, Source = asset.Source, UserEnteredRuntimeHours = asset.UserEnteredRuntimeHours, Classification = asset.Classification, PlanningGroup = asset.PlanningGroup }; var updateResult = UpdateAssetInfo(updatePayload); return(updateResult.GetType().Name == "OkObjectResult" ? StatusCode((int)HttpStatusCode.Conflict, (existingAsset.Value.ToString())) : updateResult); } return(Conflict(new { message = $"Asset already exists" })); } if (!_assetService.IsValidMakeCode(asset.MakeCode.ToUpper())) { return(BadRequest($"Asset make code '{asset.MakeCode.ToUpper()}' is not valid.")); } if (_assetService.CreateAsset(asset)) { return(Ok(asset.AssetUID.ToString())); } return(BadRequest("Unable to save to db. Make sure request is not duplicated and all keys exist")); } catch (Exception ex) { _logger.LogError("Create Asset Exception: " + ex.ToString()); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } }
public ActionResult GetAssets( [FromQuery] string[] assetUIDs = null, [FromQuery] string customerUid = null, [FromQuery] string[] assetType = null, [FromQuery] string[] status = null, [FromQuery] string[] manufacturer = null, [FromQuery] string[] model = null, [FromQuery] string snContains = null, [FromQuery] string pageSize = "10", [FromQuery] string pageNumber = "1", Guid?userGuid = null, Guid?accountSelectionGuid = null) { bool isIntegrator = false; try { int pageSizeInt; int pageNumberInt; Guid? customerGuid; List <Guid> customerGuids = new List <Guid>() { }; _logger.LogDebug("Before JWT Call.Requestheaders:" + String.Join(",", Request.Headers.Select(x => x.Key + ":" + x.Value))); if (!Request.Headers.TryGetValue("X-JWT-Assertion", out StringValues headerValues)) { return(BadRequest("Could not validate X-VisionLink-UserUid or X-JWT-Assertion Headers in Request")); } TPaaSJWT jwt; try { jwt = new TPaaSJWT(headerValues); } catch { jwt = null; } if (jwt != null) { if (userGuid == null || !userGuid.HasValue) { userGuid = jwt.UserUid; } _logger.LogDebug(string.Format("ApplicationName:{0},uuid:{1},encodedjwt:{2}", jwt.ApplicationName, jwt.UserUid, jwt.EncodedJWT)); if (!string.IsNullOrEmpty(jwt.ApplicationName)) { _logger.LogInformation("JWT has an appname " + jwt.ApplicationName); var customers = _assetService.GetCustomersForApplication(jwt.ApplicationName); // new List<Guid>() { new Guid("07D4A55244C5E311AA7700505688274D") };// if (customers != null && customers.Count > 0) { _logger.LogInformation("CustomerCount>0" + new Guid(customers[0].ToString())); customerGuid = !string.IsNullOrEmpty(customerUid) ? new Guid(customerUid) : (Guid?)null; if (customerGuid.HasValue) { if (customers.Contains((Guid)customerGuid)) { customerGuids.Add((Guid)customerGuid); isIntegrator = true; } else { return(BadRequest("Application does not have this customer mapped. Please contact your API administrator.")); } } else { customerGuids = customers; isIntegrator = true; } } if (isIntegrator) { try { _controllerUtilities.ValidatePageParameters(pageSize, pageNumber, out pageSizeInt, out pageNumberInt); } catch (Exception ex) { _logger.LogError("Get Assets parameter validation threw an exception", ex); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); //BadRequest("Assets parameter validation failed."); } if (customerGuids != null && customerGuids.Any()) { CustomerAssetsListData assets = _assetService.GetAssetsForCustomer(customerGuids, pageNumberInt, pageSizeInt); return(Ok(assets)); } } else { if (!userGuid.HasValue) { return(BadRequest("UserUID has not been provided")); } Guid[] assetGuids; WildcardMatches wildcardMatches; try { assetGuids = _controllerUtilities.ValidateAssetUIDParameters(assetUIDs); wildcardMatches = ValidateWildcardMatches(null, snContains); _controllerUtilities.ValidatePageParameters(pageSize, pageNumber, out pageSizeInt, out pageNumberInt); customerGuid = !string.IsNullOrEmpty(customerUid) ? new Guid(customerUid) : (Guid?)null; } catch (Exception ex) { _logger.LogError("Get Assets parameter validation threw an exception", ex); return(BadRequest(" Assets parameter validation " + ex.Message)); //StatusCode((int)HttpStatusCode.InternalServerError, ex.Message);// } if (!assetGuids.Any()) { assetGuids = GetAssetUIDsFromFilters( userGuid.Value, accountSelectionGuid, customerGuid, assetType, status, manufacturer, model, wildcardMatches, pageSizeInt, pageNumberInt); } if (assetGuids != null && assetGuids.Any()) { var assets = GetAssetsFromAssetGuids(assetGuids, userGuid.Value); return(Ok(assets)); } } } } } catch (Exception ex) { _logger.LogError("Get AssetLists encountered an error", ex); return(StatusCode((int)HttpStatusCode.InternalServerError, ex.Message)); } return(Ok(isIntegrator ? (object)new List <DataModels.CustomerAsset>() : (object)new List <DataModels.Asset>())); }
public IActionResult GetDeviceDetailsByAssetUID([FromQuery] Guid assetUID, [FromHeader(Name = "X-JWT-Assertion")] string encodedJwt) { try { _logger.LogInformation($"Get DeviceDetails called for {assetUID}"); var jwt = new TPaaSJWT(encodedJwt); if (jwt != null) { if (jwt.IsApplicationUserToken) { var userGuid = Utils.GetUserContext(Request); if (userGuid == null || _deviceService.ValidateAuthorizedCustomerByAsset(userGuid.Value, assetUID)) { _logger.LogInformation(string.Format("Unauthorized User Access-Get DeviceDetails called for {0}", assetUID)); return(BadRequest("Unauthorized User Access")); } } else // validate for kiewit customer { var customers = _deviceService.GetCustomersForApplication(jwt.ApplicationName); if (!customers.Any(x => x == kiewitAMPCustomerUID)) { _logger.LogInformation($"Application {jwt.ApplicationName} does not have mapped with {kiewitAMPCustomerUID}. Please contact your API administrator."); return(BadRequest($"Application does not have Access. Please contact your API administrator.")); } } } else { return(BadRequest("JWT is invalid")); } var assetDeviceDataList = _deviceService.GetDevicePropertiesV2ByAssetGuid(assetUID); if (assetDeviceDataList != null && assetDeviceDataList.Any()) { var assetDevice = assetDeviceDataList.FirstOrDefault(); if (assetDevice != null) { var assetDevicePayload = new { AssetUID = assetDevice.AssetUID, Devices = new List <DevicePropertiesPayLoad>() }; var prevDeviceUid = Guid.Empty; var deviceIndex = -1; foreach (var assetDeviceData in assetDeviceDataList) { var deviceGuid = assetDeviceData.DeviceUID; if (prevDeviceUid != deviceGuid) { assetDevicePayload.Devices.Add(new DevicePropertiesPayLoad { DeviceUID = deviceGuid, DeviceType = assetDeviceData.DeviceType, DeviceSerialNumber = assetDeviceData.DeviceSerialNumber, DeviceState = ((DeviceStateEnum)assetDeviceData.DeviceState).ToString(), DataLinkType = assetDeviceData.DataLinkType, DeregisteredUTC = assetDeviceData.DeregisteredUTC, ModuleType = assetDeviceData.ModuleType, Personalities = new List <DevicePersonalityPayload>() }); prevDeviceUid = deviceGuid; deviceIndex++; } assetDevicePayload.Devices[deviceIndex].Personalities.Add(new DevicePersonalityPayload { Name = ((DevicePersonalityTypeEnum)assetDeviceData.PersonalityTypeId).ToString(), Description = assetDeviceData.PersonalityDescription, Value = assetDeviceData.PersonalityValue }); } return(Ok(assetDevicePayload)); } } } catch (Exception ex) { _logger.LogError("Get DeviceDetails threw an exception", ex); return(StatusCode((int)HttpStatusCode.InternalServerError, ex)); } return(BadRequest("Device Doesn't Exist")); }