/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> //public string FunctionHandler(string input, ILambdaContext context) //{ // return input?.ToUpper(); //} //public string FunctionHandler(Stream stream, ILambdaContext context) //{ // List<byte> bytes = new List<byte>(); // while (stream.CanRead) // { // int readByte = stream.ReadByte(); // if (readByte != -1) // bytes.Add((byte)readByte); // else // break; // } // string text = Encoding.UTF8.GetString(bytes.ToArray()); // return text; //} public Stream FunctionHandler(Stream stream, ILambdaContext context) { List<byte> bytes = new List<byte>(); while (stream.CanRead) { int readByte = stream.ReadByte(); if (readByte != -1) bytes.Add((byte)readByte); else break; } string text = Encoding.UTF8.GetString(bytes.ToArray()); var json = JObject.Parse(text); json["name"] = "LunaSter"; text = json.ToString(); MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(text)); return stream1; }
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(NewUser input, ILambdaContext context) { LambdaLogger.Log($"Calling Function Named {context.FunctionName}"); return($"Welcome new user, {input.FirstName} {input.LastName}"); }
public async Task <string> Handler(JToken @event, ILambdaContext context) { var resourceManager = AwsEnvironment.GetAwsV4ResourceManager(); try { var jobData = new JobBase { Status = "RUNNING", Progress = 54 }; await resourceManager.SendNotificationAsync(jobData, @event["notificationEndpoint"].ToMcmaObject <NotificationEndpoint>()); } catch (Exception error) { Logger.Error("Failed to send notification: {0}", error); } var stepFunction = new AmazonStepFunctionsClient(); var data = await stepFunction.GetActivityTaskAsync(new GetActivityTaskRequest { ActivityArn = ACTIVITY_ARN }); var taskToken = data.TaskToken; if (taskToken == null) { throw new Exception("Failed to obtain activity task"); } @event = JToken.Parse(data.Input); var jobProfiles = await resourceManager.GetAsync <JobProfile>(("name", JOB_PROFILE_NAME)); var jobProfileId = jobProfiles?.FirstOrDefault()?.Id; if (jobProfileId == null) { throw new Exception($"JobProfile '{JOB_PROFILE_NAME}' not found"); } var createProxyJob = new TransformJob { JobProfile = jobProfileId, JobInput = new JobParameterBag { ["inputFile"] = @event["data"]["repositoryFile"], ["outputLocation"] = new S3Locator { AwsS3Bucket = REPOSITORY_BUCKET, AwsS3KeyPrefix = "TransformJobResults/" } }, NotificationEndpoint = new NotificationEndpoint { HttpEndpoint = ACTIVITY_CALLBACK_URL + "?taskToken=" + Uri.EscapeDataString(taskToken) } }; createProxyJob = await resourceManager.CreateAsync(createProxyJob); return(createProxyJob.Id); }
/// <summary> /// Flushes Concurrent Lists (defined in HWC.DataModel). This Lambda function function is typically invoked with scheduled calls. /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public async Task <APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext context) { APIGatewayProxyResponse response = new APIGatewayProxyResponse(); if (context != null) { this.Context = context; try { // Reset data members of the Function class; // It needs to be done because AWS Lambda uses the same old instance to invoke the FunctionHandler on concurrent calls ResetDataMembers(); // Initialize DataClient Config.DataClientConfig dataClientConfig = new Config.DataClientConfig(Config.DataClientConfig.RdsDbInfrastructure.Aws); using (_dataClient = new DataClient(dataClientConfig)) { await FlushZoneConcurrentListAsync(); await FlushDisplayConcurrentListAsync(); } // Respond OK response.StatusCode = (int)HttpStatusCode.OK; response.Headers = new Dictionary <string, string>() { { "Access-Control-Allow-Origin", "'*'" } }; response.Body = JsonConvert.SerializeObject(new Empty()); } catch (Exception ex) { // Respond error Error error = new Error((int)HttpStatusCode.Forbidden) { Description = "Forbidden", ReasonPharse = "Forbidden" }; response.StatusCode = error.Code; response.Body = JsonConvert.SerializeObject(error); Context.Logger.LogLine("TransientData ERROR: " + ex.Message); } } else { throw new Exception("Lambda context is not initialized"); } return(response); }
public tResult FunctionHandler(tInput oInput, ILambdaContext context) { string strQuery = ""; SqlDataAdapter daCheck = new SqlDataAdapter(); DataSet dsCheck = new DataSet(); SqlConnection oSqlConnection = null; tResult oResult = new tResult(); int intIdx; try { context.Logger.LogLine("FunctionHandler 1 " + oInput.ToString()); try { oSqlConnection = new SqlConnection(ecoCommon.GetSecret("CloudEcoPlus", context)); oSqlConnection.Open(); context.Logger.LogLine("FunctionHandler 2"); } catch (Exception ex) { context.Logger.LogLine("WriteRecord Ex 1" + ex.Message); } try { oSqlConnection.Open(); } catch (Exception) { } strQuery = "SELECT EhiuSiteConfig.EhiuSiteConfigID, EhiuSiteConfig.SiteID, EhiuSiteConfig.Name, EhiuSiteConfig.Descr, " + " EhiuSiteConfig.Retired, EhiuSiteConfig.DateCreated, EhiuSiteConfig.CreatedBy, Site.SiteName " + " FROM EhiuSiteConfig INNER JOIN " + " Site ON EhiuSiteConfig.SiteID = Site.SiteID " + " WHERE (Site.SiteName LIKE @SiteName) " + " ORDER BY EhiuSiteConfig.Name "; daCheck = new SqlDataAdapter(strQuery, oSqlConnection); SqlParameter sqlParamSiteName = new SqlParameter("@SiteName", SqlDbType.NVarChar); sqlParamSiteName.Value = oInput.Search; daCheck.SelectCommand.Parameters.Add(sqlParamSiteName); daCheck.Fill(dsCheck); for (intIdx = 0; intIdx <= dsCheck.Tables[0].Rows.Count - 1; intIdx++) { tResult.tConfig oConfig = new tResult.tConfig(); oConfig.SiteID = (int)dsCheck.Tables[0].Rows[intIdx]["SiteID"]; oConfig.Descr = (string)dsCheck.Tables[0].Rows[intIdx]["Descr"]; oConfig.Name = (string)dsCheck.Tables[0].Rows[intIdx]["Name"]; oConfig.Retired = (bool)dsCheck.Tables[0].Rows[intIdx]["Retired"]; oConfig.DateCreated = (DateTime)dsCheck.Tables[0].Rows[intIdx]["DateCreated"]; oConfig.CreatedBy = (string)dsCheck.Tables[0].Rows[intIdx]["CreatedBy"]; oConfig.SiteName = (string)dsCheck.Tables[0].Rows[intIdx]["SiteName"]; oConfig.EhiuSiteConfigID = (int)dsCheck.Tables[0].Rows[intIdx]["EhiuSiteConfigID"]; oResult.Configs.Add(oConfig); } } catch (Exception ex) { context.Logger.LogLine("Ex in FunctionHandler " + ex.Message); oResult.Ok = false; oResult.Info = ex.Message; } return(oResult); }
/// <summary> /// Convert the JSON document received from API Gateway into the InvokeFeatures object. /// InvokeFeatures is then passed into IHttpApplication to create the ASP.NET Core request objects. /// </summary> /// <param name="features"></param> /// <param name="apiGatewayRequest"></param> /// <param name="lambdaContext"></param> protected override void MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext) { { var authFeatures = (IHttpAuthenticationFeature)features; var authorizer = apiGatewayRequest?.RequestContext?.Authorizer; if (authorizer != null) { // handling claims output from cognito user pool authorizer if (authorizer.Claims != null && authorizer.Claims.Count != 0) { var identity = new ClaimsIdentity(authorizer.Claims.Select( entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); _logger.LogDebug( $"Configuring HttpContext.User with {authorizer.Claims.Count} claims coming from API Gateway's Request Context"); authFeatures.User = new ClaimsPrincipal(identity); } else { // handling claims output from custom lambda authorizer var identity = new ClaimsIdentity( authorizer.Where(x => x.Value != null && !string.Equals(x.Key, "claims", StringComparison.OrdinalIgnoreCase)) .Select(entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); _logger.LogDebug( $"Configuring HttpContext.User with {authorizer.Count} claims coming from API Gateway's Request Context"); authFeatures.User = new ClaimsPrincipal(identity); } } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallHttpAuthenticationFeature(authFeatures, apiGatewayRequest, lambdaContext); } { var requestFeatures = (IHttpRequestFeature)features; requestFeatures.Scheme = "https"; requestFeatures.Method = apiGatewayRequest.HttpMethod; if (string.IsNullOrWhiteSpace(apiGatewayRequest?.RequestContext?.DomainName)) { _logger.LogWarning($"Request does not contain domain name information but is derived from {nameof(APIGatewayProxyFunction)}."); } string path = null; if (apiGatewayRequest.PathParameters != null && apiGatewayRequest.PathParameters.ContainsKey("proxy") && !string.IsNullOrEmpty(apiGatewayRequest.Resource)) { var proxyPath = apiGatewayRequest.PathParameters["proxy"]; path = apiGatewayRequest.Resource.Replace("{proxy+}", proxyPath); } if (string.IsNullOrEmpty(path)) { path = apiGatewayRequest.Path; } if (!path.StartsWith("/")) { path = "/" + path; } requestFeatures.Path = path; requestFeatures.PathBase = string.Empty; if (!string.IsNullOrEmpty(apiGatewayRequest?.RequestContext?.Path)) { // This is to cover the case where the request coming in is https://myapigatewayid.execute-api.us-west-2.amazonaws.com/Prod where // Prod is the stage name and there is no ending '/'. Path will be set to '/' so to make sure we detect the correct base path // append '/' on the end to make the later EndsWith and substring work correctly. var requestContextPath = apiGatewayRequest.RequestContext.Path; if (path.EndsWith("/") && !requestContextPath.EndsWith("/")) { requestContextPath += "/"; } else if (!path.EndsWith("/") && requestContextPath.EndsWith("/")) { // Handle a trailing slash in the request path: e.g. https://myapigatewayid.execute-api.us-west-2.amazonaws.com/Prod/foo/ requestFeatures.Path = path += "/"; } if (requestContextPath.EndsWith(path)) { requestFeatures.PathBase = requestContextPath.Substring(0, requestContextPath.Length - requestFeatures.Path.Length); } } requestFeatures.Path = Utilities.DecodeResourcePath(requestFeatures.Path); requestFeatures.QueryString = Utilities.CreateQueryStringParameters( apiGatewayRequest.QueryStringParameters, apiGatewayRequest.MultiValueQueryStringParameters, true); Utilities.SetHeadersCollection(requestFeatures.Headers, apiGatewayRequest.Headers, apiGatewayRequest.MultiValueHeaders); if (!requestFeatures.Headers.ContainsKey("Host")) { var apiId = apiGatewayRequest?.RequestContext?.ApiId ?? ""; var stage = apiGatewayRequest?.RequestContext?.Stage ?? ""; requestFeatures.Headers["Host"] = $"apigateway-{apiId}-{stage}"; } if (!string.IsNullOrEmpty(apiGatewayRequest.Body)) { requestFeatures.Body = Utilities.ConvertLambdaRequestBodyToAspNetCoreBody(apiGatewayRequest.Body, apiGatewayRequest.IsBase64Encoded); } // Make sure the content-length header is set if header was not present. const string contentLengthHeaderName = "Content-Length"; if (!requestFeatures.Headers.ContainsKey(contentLengthHeaderName)) { requestFeatures.Headers[contentLengthHeaderName] = requestFeatures.Body == null ? "0" : requestFeatures.Body.Length.ToString(CultureInfo.InvariantCulture); } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallRequestFeature(requestFeatures, apiGatewayRequest, lambdaContext); } { // set up connection features var connectionFeatures = (IHttpConnectionFeature)features; if (!string.IsNullOrEmpty(apiGatewayRequest?.RequestContext?.Identity?.SourceIp) && IPAddress.TryParse(apiGatewayRequest.RequestContext.Identity.SourceIp, out var remoteIpAddress)) { connectionFeatures.RemoteIpAddress = remoteIpAddress; } if (apiGatewayRequest?.Headers?.ContainsKey("X-Forwarded-Port") == true) { connectionFeatures.RemotePort = int.Parse(apiGatewayRequest.Headers["X-Forwarded-Port"]); } // Call consumers customize method in case they want to change how API Gateway's request // was marshalled into ASP.NET Core request. PostMarshallConnectionFeature(connectionFeatures, apiGatewayRequest, lambdaContext); } }
/// <summary> /// Convert the response coming from ASP.NET Core into APIGatewayProxyResponse which is /// serialized into the JSON object that API Gateway expects. /// </summary> /// <param name="responseFeatures"></param> /// <param name="statusCodeIfNotSet">Sometimes the ASP.NET server doesn't set the status code correctly when successful, so this parameter will be used when the value is 0.</param> /// <param name="lambdaContext"></param> /// <returns><see cref="APIGatewayProxyResponse"/></returns> protected override APIGatewayProxyResponse MarshallResponse(IHttpResponseFeature responseFeatures, ILambdaContext lambdaContext, int statusCodeIfNotSet = 200) { var response = new APIGatewayProxyResponse { StatusCode = responseFeatures.StatusCode != 0 ? responseFeatures.StatusCode : statusCodeIfNotSet }; string contentType = null; string contentEncoding = null; if (responseFeatures.Headers != null) { response.MultiValueHeaders = new Dictionary <string, IList <string> >(); response.Headers = new Dictionary <string, string>(); foreach (var kvp in responseFeatures.Headers) { response.MultiValueHeaders[kvp.Key] = kvp.Value.ToList(); // Remember the Content-Type for possible later use if (kvp.Key.Equals("Content-Type", StringComparison.CurrentCultureIgnoreCase) && response.MultiValueHeaders[kvp.Key].Count > 0) { contentType = response.MultiValueHeaders[kvp.Key][0]; } else if (kvp.Key.Equals("Content-Encoding", StringComparison.CurrentCultureIgnoreCase) && response.MultiValueHeaders[kvp.Key].Count > 0) { contentEncoding = response.MultiValueHeaders[kvp.Key][0]; } } } if (contentType == null) { response.MultiValueHeaders["Content-Type"] = new List <string>() { null }; } if (responseFeatures.Body != null) { // Figure out how we should treat the response content, check encoding first to see if body is compressed, then check content type var rcEncoding = GetResponseContentEncodingForContentEncoding(contentEncoding); if (rcEncoding != ResponseContentEncoding.Base64) { rcEncoding = GetResponseContentEncodingForContentType(contentType); } (response.Body, response.IsBase64Encoded) = Utilities.ConvertAspNetCoreBodyToLambdaBody(responseFeatures.Body, rcEncoding); } PostMarshallResponseFeature(responseFeatures, response, lambdaContext); _logger.LogDebug($"Response Base 64 Encoded: {response.IsBase64Encoded}"); return(response); }
public async Task <APIGatewayProxyResponse> PutFunctionHandlerAsync(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var table = Environment.GetEnvironmentVariable("TABLE_NAME"); var entity = JsonConvert.DeserializeObject <Entity>(apigProxyEvent.Body); entity.Id = apigProxyEvent.PathParameters["entityid"]; entity.UserId = apigProxyEvent.PathParameters["userid"]; var entitiesRepo = RepositoryFactory.CreateEntityRepository(table); var result = await entitiesRepo.PutItemAsync(entity); return(APIGatewayProxyHelper.JsonAPIGatewayProxyResponse(result)); }
public Stream Handler(Stream inputStream, ILambdaContext context) { StreamReader reader = new StreamReader(inputStream); string request = reader.ReadToEnd(); Console.Out.WriteLine("Request:"); Console.Out.WriteLine(request); if (context != null) { context.Logger.Log("Request:"); context.Logger.Log(request); } AlexaResponse ar; JObject jsonRequest = JObject.Parse(request); string nameSpace = jsonRequest["directive"]["header"]["namespace"].Value <string>(); switch (nameSpace) { case "Alexa.Authorization": if (context != null) { context.Logger.Log("Alexa.Authorization Request"); } ar = new AlexaResponse("Alexa.Authorization", "AcceptGrant.Response"); break; case "Alexa.Discovery": if (context != null) { context.Logger.Log("Alexa.Discovery Request"); } ar = new AlexaResponse("Alexa.Discovery", "Discover.Response", "endpoint-001"); JObject capabilityAlexa = JObject.Parse(ar.CreatePayloadEndpointCapability()); JObject propertyPowerstate = new JObject(); propertyPowerstate.Add("name", "powerState"); JObject capabilityAlexaPowerController = JObject.Parse(ar.CreatePayloadEndpointCapability("AlexaInterface", "Alexa.PowerController", "3", propertyPowerstate.ToString())); JArray capabilities = new JArray(); capabilities.Add(capabilityAlexa); capabilities.Add(capabilityAlexaPowerController); ar.AddPayloadEndpoint("endpoint-001", capabilities.ToString()); break; case "Alexa.PowerController": if (context != null) { context.Logger.Log("Alexa.PowerController Request"); } string correlationToken = jsonRequest["directive"]["header"]["correlationToken"].Value <string>(); string endpointId = jsonRequest["directive"]["endpoint"]["endpointId"].Value <string>(); string name = jsonRequest["directive"]["header"]["name"].Value <string>(); string state = (name == "TurnOff") ? "OFF" : "ON"; bool result = SendDeviceState(endpointId, "powerState", state); if (result) { ar = new AlexaResponse("Alexa", "Response", endpointId, "INVALID", correlationToken); ar.AddContextProperty("Alexa.PowerController", "powerState", state, 200); } else { JObject payloadError = new JObject(); payloadError.Add("type", "ENDPOINT_UNREACHABLE"); payloadError.Add("message", "There wa an error setting the device state."); ar = new AlexaResponse("Alexa", "ErrorResponse"); ar.SetPayload(payloadError.ToString()); } break; default: if (context != null) { context.Logger.Log("INVALID Namespace"); } ar = new AlexaResponse(); break; } string response = ar.ToString(); if (context != null) { context.Logger.Log("Response:"); context.Logger.Log(response); } return(new MemoryStream(Encoding.UTF8.GetBytes(response))); }
public async Task <StartDatabaseResponse> Handle(StartDatabaseRequest request, ILambdaContext context = default !) { logger.LogInformation("Recieved request: ", request); var status = await GetDBClusterStatus(request.DatabaseName); if (status == StartedStatus) { await NotifyIfNotificationTopicProvided(status, request.NotificationTopic, request.TaskToken); return(new StartDatabaseResponse { Message = $"Database cluster {request.DatabaseName} started." }); } try { if (status == StoppedStatus) { await rdsClient.StartDBClusterAsync(new StartDBClusterRequest { DBClusterIdentifier = request.DatabaseName }); } if (request.NotificationTopic != null) { await DisableNotifyDatabaseAvailabilityEventSourceMapping(); await sqsClient.SendMessageAsync(new SendMessageRequest { QueueUrl = configuration.NotificationQueueUrl, MessageBody = Serialize(new QueueMessage { NotificationTopic = request.NotificationTopic, TaskToken = request.TaskToken ! }) }); await eventsClient.EnableRuleAsync(new EnableRuleRequest { Name = configuration.WaitForDatabaseAvailabilityRuleName }); }
public async Task <JToken> Handler(JToken @event, ILambdaContext context) { if (@event == null) { throw new Exception("Missing workflow input"); } var resourceManager = AwsEnvironment.GetAwsV4ResourceManager(); try { var jobData = new JobBase { Status = "RUNNING", ParallelProgress = { ["detect-celebrities-aws"] = 20 } }; await resourceManager.SendNotificationAsync(jobData, @event["notificationEndpoint"].ToMcmaObject <NotificationEndpoint>()); } catch (Exception error) { Logger.Error("Failed to send notification: {0}", error); } var stepFunction = new AmazonStepFunctionsClient(); var data = await stepFunction.GetActivityTaskAsync(new GetActivityTaskRequest { ActivityArn = ACTIVITY_ARN }); var taskToken = data.TaskToken; if (taskToken == null) { throw new Exception("Failed to obtain activity task"); } @event = JToken.Parse(data.Input); var jobProfiles = await resourceManager.GetAsync <JobProfile>(("name", JOB_PROFILE_NAME)); var jobProfileId = jobProfiles?.FirstOrDefault()?.Id; if (jobProfileId == null) { throw new Exception($"JobProfile '{JOB_PROFILE_NAME}' not found"); } var job = new AIJob { JobProfile = jobProfileId, JobInput = new JobParameterBag { ["inputFile"] = @event["data"]["mediaFileLocator"], ["outputLocation"] = new S3Locator { AwsS3Bucket = TEMP_BUCKET, AwsS3Key = JOB_RESULTS_PREFIX } }, NotificationEndpoint = new NotificationEndpoint { HttpEndpoint = ACTIVITY_CALLBACK_URL + "?taskToken=" + Uri.EscapeDataString(taskToken) } }; job = await resourceManager.CreateAsync(job); return(job.Id); }
public async Task <APIGatewayProxyResponse> OnDisconnect(APIGatewayProxyRequest request, ILambdaContext context) { context.Logger.LogLine($"Logoff with connection id: {request.RequestContext.ConnectionId}"); await _manager.LogoffAsync(request.RequestContext.ConnectionId); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK }; return(response); }
/// <summary> /// Verify JWT token in Authorization header and if valid allow connection. /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <APIGatewayProxyResponse> OnConnect(APIGatewayProxyRequest request, ILambdaContext context) { if (_jwtValidationParameters == null) { _jwtValidationParameters = await CreateTokenValidationParameters(context); } try { var username = ValidateAndGetUsername(request, context); var domainName = request.RequestContext.DomainName; var stage = request.RequestContext.Stage; var endpoint = $"https://{domainName}/{stage}"; if (string.IsNullOrEmpty(username)) { context.Logger.LogLine("Error, no username claim found in JWT token"); return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.Unauthorized }); } context.Logger.LogLine( $"Login with connection id: {request.RequestContext.ConnectionId}, Endpoint: {endpoint}, Username: {username}"); await _manager.LoginAsync(request.RequestContext.ConnectionId, endpoint, username); return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK }); } catch { return(new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.Unauthorized }); } }
private async Task <TokenValidationParameters> CreateTokenValidationParameters(ILambdaContext context) { context.Logger.LogLine("Loading user pool configuration from SSM Parameter Store."); var configuration = new ConfigurationBuilder() .AddSystemsManager("/ImageRecognition") .Build(); var region = configuration["AWS:Region"]; if (string.IsNullOrEmpty(region)) { region = FallbackRegionFactory.GetRegionEndpoint().SystemName; } var userPoolId = configuration["AWS:UserPoolId"]; var userPoolClientId = configuration["AWS:UserPoolClientId"]; context.Logger.LogLine("Configuring JWT Validation parameters"); var openIdConfigurationUrl = $"https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/openid-configuration"; var configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(openIdConfigurationUrl, new OpenIdConnectConfigurationRetriever()); context.Logger.LogLine($"Loading open id configuration from {openIdConfigurationUrl}"); var openIdConfig = await configurationManager.GetConfigurationAsync(); var validIssuer = $"https://cognito-idp.{region}.amazonaws.com/{userPoolId}"; context.Logger.LogLine($"Valid Issuer: {validIssuer}"); context.Logger.LogLine($"Valid Audiences: {userPoolClientId}"); return(new TokenValidationParameters { ValidIssuer = validIssuer, ValidAudiences = new[] { userPoolClientId }, IssuerSigningKeys = openIdConfig.SigningKeys }); }
public async Task <RhinoComputeExampleOutputs> Handler(RhinoComputeExampleInputs args, ILambdaContext context) { if (this.store == null) { // Preload the dependencies (if they exist), // so that they are available during model deserialization. var asmLocation = this.GetType().Assembly.Location; var asmDir = Path.GetDirectoryName(asmLocation); var asmName = Path.GetFileNameWithoutExtension(asmLocation); var depPath = Path.Combine(asmDir, $"{asmName}.Dependencies.dll"); if (File.Exists(depPath)) { Console.WriteLine($"Loading dependencies from assembly: {depPath}..."); Assembly.LoadFrom(depPath); Console.WriteLine("Dependencies assembly loaded."); } this.store = new S3ModelStore <RhinoComputeExampleInputs>(RegionEndpoint.USWest1); } var l = new InvocationWrapper <RhinoComputeExampleInputs, RhinoComputeExampleOutputs>(store, RhinoComputeExample.Execute); var output = await l.InvokeAsync(args); return(output); }
public async Task <APIGatewayProxyResponse> GetItemFunctionHandlerAsync(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var table = Environment.GetEnvironmentVariable("TABLE_NAME"); var userid = apigProxyEvent.PathParameters["userid"]; var entityid = apigProxyEvent.PathParameters["entityid"]; var entitiesRepo = RepositoryFactory.CreateEntityRepository(table); var item = await entitiesRepo.GetItemAsync(userid, entityid); if (item == null) { return(APIGatewayProxyHelper.JsonAPIGatewayProxyResponse(null, 404)); } return(APIGatewayProxyHelper.JsonAPIGatewayProxyResponse(item)); }
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest input, ILambdaContext context) { var inputToken = input.AuthorizationToken; var ok = false; var subject = "<< NOT FOUND >>"; context.Logger.Log($"Token: {inputToken}"); if (!string.IsNullOrWhiteSpace(inputToken)) { try { inputToken = inputToken.Replace("Bearer", string.Empty).Trim(); var token = new JwtSecurityToken(inputToken); ok = token.Issuer == "https://sts.windows.net/6ab8b79b-42b6-40fd-a177-4540c8f1b365/"; context.Logger.Log($"Issuer: {token.Issuer}"); context.Logger.Log($"Issuer Valid: {ok}"); context.Logger.Log($"Subject: {token.Subject}"); subject = token.Subject; } catch (Exception e) { context.Logger.Log($"Exception: {e.Message}"); context.Logger.Log(e.StackTrace); } } return(new APIGatewayCustomAuthorizerResponse { PrincipalID = subject, //principal info here... UsageIdentifierKey = "API", //usage identifier here (optional) PolicyDocument = new APIGatewayCustomAuthorizerPolicy { Version = "2012-10-17", Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>() { new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement { Action = new HashSet <string>() { "execute-api:Invoke" }, Effect = ok ? "Allow" : "Deny", Resource = new HashSet <string>() { input.MethodArn } // resource arn here } }, } }); }
public async Task <APIGatewayProxyResponse> DeleteFunctionHandlerAsync(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var table = Environment.GetEnvironmentVariable("TABLE_NAME"); var entity = new Entity(); entity.Id = apigProxyEvent.PathParameters["entityid"]; entity.UserId = apigProxyEvent.PathParameters["userid"]; var entitiesRepo = RepositoryFactory.CreateEntityRepository(table); await entitiesRepo.DeleteItemAsync(entity); return(APIGatewayProxyHelper.JsonAPIGatewayProxyResponse()); }
public async Task <APIGatewayProxyResponse> Create(APIGatewayProxyRequest request, ILambdaContext lambdaContext) { var command = request.DeserializeBody <CreateEntity1Command>(); if (command is null) { return(new APIGatewayProxyResponse().SetBadRequest()); } else { string newEntityId = await this._mediator.Send(command).ConfigureAwait(false); return(new APIGatewayProxyResponse().SetSuccess(newEntityId)); } }
private protected override void InternalCustomResponseExceptionHandling(APIGatewayProxyResponse apiGatewayResponse, ILambdaContext lambdaContext, Exception ex) { apiGatewayResponse.MultiValueHeaders["ErrorType"] = new List <string> { ex.GetType().Name }; }
public async Task <APIGatewayProxyResponse> Get(APIGatewayProxyRequest request, ILambdaContext lambdaContext) { object result; if (request.PathParameters.ContainsKey("id")) { string id = request.PathParameters["id"]; result = await this._entity1Query.GetAsync(id).ConfigureAwait(false); } else { result = await this._entity1Query.GetAllAsync().ConfigureAwait(false); } return(result is null ? new APIGatewayProxyResponse().SetNotfound() : new APIGatewayProxyResponse().SetSuccess(result)); }
/// <summary> /// A Lambda function that adds a blog post. /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <APIGatewayProxyResponse> AddBlog(APIGatewayProxyRequest request, ILambdaContext context) { var blog = JsonConvert.DeserializeObject <Blog>(request?.Body); blog.Id = Guid.NewGuid().ToString(); blog.CreatedTimestamp = DateTime.Now; context.Logger.LogLine($"Saving blog with id {blog.Id}"); await DDBContext.SaveAsync(blog); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK, Body = blog.Id.ToString(), Headers = new Dictionary <string, string> { { "Content-Type", "text/plain" } } }; return(response); }
public override async Task <MacroResponse> ProcessMessageAsync(MacroRequest request, ILambdaContext context) { LogInfo($"AwsRegion = {request.region}"); LogInfo($"AccountID = {request.accountId}"); LogInfo($"Fragment = {SerializeToJson(request.fragment)}"); LogInfo($"TransformID = {request.transformId}"); LogInfo($"Params = {SerializeToJson(request.@params)}"); LogInfo($"RequestID = {request.requestId}"); LogInfo($"TemplateParameterValues = {SerializeToJson(request.templateParameterValues)}"); // macro for string operations try { if ([email protected]("Value", out object value)) { throw new ArgumentException("missing parameter: 'Value"); } if (!(value is string text)) { throw new ArgumentException("parameter 'Value' must be a string"); } string result; switch (request.transformId) { case "StringToUpper": result = text.ToUpper(); break; case "StringToLower": result = text.ToLower(); break; default: throw new NotSupportedException($"requested operation is not supported: '{request.transformId}'"); } // return successful response return(new MacroResponse { requestId = request.requestId, status = "SUCCESS", fragment = result }); } catch (Exception e) { // an error occurred return(new MacroResponse { requestId = request.requestId, status = $"ERROR: {e.Message}" }); } }
/// <summary> /// Performs dialog management and fulfillment for booking a car. /// /// Beyond fulfillment, the implementation for this intent demonstrates the following: /// 1) Use of elicitSlot in slot validation and re-prompting /// 2) Use of sessionAttributes to pass information that can be used to guide the conversation /// </summary> /// <param name="lexEvent"></param> /// <returns></returns> public override LexResponse Process(LexEvent lexEvent, ILambdaContext context) { var slots = lexEvent.CurrentIntent.Slots; var sessionAttributes = lexEvent.SessionAttributes ?? new Dictionary <string, string>(); Reservation reservation = new Reservation { ReservationType = "Car", PickUpCity = slots.ContainsKey(PICK_UP_CITY_SLOT) ? slots[PICK_UP_CITY_SLOT] : null, PickUpDate = slots.ContainsKey(PICK_UP_DATE_SLOT) ? slots[PICK_UP_DATE_SLOT] : null, ReturnDate = slots.ContainsKey(RETURN_DATE_SLOT) ? slots[RETURN_DATE_SLOT] : null, DriverAge = slots.ContainsKey(DRIVER_AGE_SLOT) ? slots[DRIVER_AGE_SLOT] : null, CarType = slots.ContainsKey(CAR_TYPE_SLOT) ? slots[CAR_TYPE_SLOT] : null, }; string confirmationStaus = lexEvent.CurrentIntent.ConfirmationStatus; Reservation lastConfirmedReservation = null; if (slots.ContainsKey(LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE)) { lastConfirmedReservation = DeserializeReservation(slots[LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE]); } string confirmationContext = sessionAttributes.ContainsKey("confirmationContext") ? sessionAttributes["confirmationContext"] : null; sessionAttributes[CURRENT_RESERVATION_SESSION_ATTRIBUTE] = SerializeReservation(reservation); var validateResult = Validate(reservation); context.Logger.LogLine($"Has required fields: {reservation.HasRequiredCarFields}, Has valid values {validateResult.IsValid}"); if (!validateResult.IsValid) { context.Logger.LogLine($"Slot {validateResult.ViolationSlot} is invalid: {validateResult.Message?.Content}"); } if (reservation.HasRequiredCarFields && validateResult.IsValid) { var price = GeneratePrice(reservation); context.Logger.LogLine($"Generated price: {price}"); sessionAttributes[CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE] = price.ToString(CultureInfo.InvariantCulture); } else { sessionAttributes.Remove(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE); } if (string.Equals(lexEvent.InvocationSource, "DialogCodeHook", StringComparison.Ordinal)) { // If any slots are invalid, re-elicit for their value if (!validateResult.IsValid) { slots[validateResult.ViolationSlot] = null; return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, validateResult.ViolationSlot, validateResult.Message)); } // Determine if the intent (and current slot settings) have been denied. The messaging will be different // if the user is denying a reservation they initiated or an auto-populated suggestion. if (string.Equals(lexEvent.CurrentIntent.ConfirmationStatus, "Denied", StringComparison.Ordinal)) { sessionAttributes.Remove("confirmationContext"); sessionAttributes.Remove(CURRENT_RESERVATION_SESSION_ATTRIBUTE); if (string.Equals(confirmationContext, "AutoPopulate", StringComparison.Ordinal)) { return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, new Dictionary <string, string> { { PICK_UP_CITY_SLOT, null }, { PICK_UP_DATE_SLOT, null }, { RETURN_DATE_SLOT, null }, { DRIVER_AGE_SLOT, null }, { CAR_TYPE_SLOT, null } }, PICK_UP_CITY_SLOT, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "Where would you like to make your car reservation?" } )); } return(Delegate(sessionAttributes, slots)); } if (string.Equals(lexEvent.CurrentIntent.ConfirmationStatus, "None", StringComparison.Ordinal)) { // If we are currently auto-populating but have not gotten confirmation, keep requesting for confirmation. if ((!string.IsNullOrEmpty(reservation.PickUpCity) && !string.IsNullOrEmpty(reservation.PickUpDate) && !string.IsNullOrEmpty(reservation.ReturnDate) && !string.IsNullOrEmpty(reservation.DriverAge) && !string.IsNullOrEmpty(reservation.CarType)) || string.Equals(confirmationContext, "AutoPopulate", StringComparison.Ordinal)) { if (lastConfirmedReservation != null && string.Equals(lastConfirmedReservation.ReservationType, "Hotel", StringComparison.Ordinal)) { // If the user's previous reservation was a hotel - prompt for a rental with // auto-populated values to match this reservation. sessionAttributes["confirmationContext"] = "AutoPopulate"; return(ConfirmIntent( sessionAttributes, lexEvent.CurrentIntent.Name, new Dictionary <string, string> { { PICK_UP_CITY_SLOT, lastConfirmedReservation.PickUpCity }, { PICK_UP_DATE_SLOT, lastConfirmedReservation.CheckInDate }, { RETURN_DATE_SLOT, DateTime.Parse(lastConfirmedReservation.CheckInDate).AddDays(int.Parse(lastConfirmedReservation.Nights)).ToUniversalTime().ToString(CultureInfo.InvariantCulture) }, { CAR_TYPE_SLOT, null }, { DRIVER_AGE_SLOT, null }, }, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = $"Is this car rental for your {lastConfirmedReservation.Nights} night stay in {lastConfirmedReservation.Location} on {lastConfirmedReservation.CheckInDate}?" } )); } } // Otherwise, let native DM rules determine how to elicit for slots and/or drive confirmation. return(Delegate(sessionAttributes, slots)); } // If confirmation has occurred, continue filling any unfilled slot values or pass to fulfillment. if (string.Equals(lexEvent.CurrentIntent.ConfirmationStatus, "Confirmed", StringComparison.Ordinal)) { // Remove confirmationContext from sessionAttributes so it does not confuse future requests sessionAttributes.Remove("confirmationContext"); if (string.Equals(confirmationContext, "AutoPopulate", StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(reservation.DriverAge)) { return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, DRIVER_AGE_SLOT, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "How old is the driver of this car rental?" } )); } else if (string.IsNullOrEmpty(reservation.CarType)) { return(ElicitSlot(sessionAttributes, lexEvent.CurrentIntent.Name, slots, CAR_TYPE_SLOT, new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "What type of car would you like? Popular models are economy, midsize, and luxury." } )); } } return(Delegate(sessionAttributes, slots)); } } context.Logger.LogLine($"Book car at = {SerializeReservation(reservation)}"); if (sessionAttributes.ContainsKey(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE)) { context.Logger.LogLine($"Book car price = {sessionAttributes[CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE]}"); } sessionAttributes.Remove(CURRENT_RESERVATION_PRICE_SESSION_ATTRIBUTE); sessionAttributes.Remove(CURRENT_RESERVATION_SESSION_ATTRIBUTE); sessionAttributes[LAST_CONFIRMED_RESERVATION_SESSION_ATTRIBUTE] = SerializeReservation(reservation); return(Close( sessionAttributes, "Fulfilled", new LexResponse.LexMessage { ContentType = MESSAGE_CONTENT_TYPE, Content = "Thanks, I have placed your reservation." } )); }
public async Task <APIGatewayProxyResponse> Execute(APIGatewayProxyRequest req, ILambdaContext ctx) { ctx.Logger.LogLine($"Lambda Context: {JsonConvert.SerializeObject(ctx)}"); ctx.Logger.LogLine($"Create Subscription Request: {JsonConvert.SerializeObject(req)}"); var reqBody = JsonConvert.DeserializeObject <CreateSubscriptionRequestBody>(req.Body); using (var DynamoClient = serviceProvider.GetService <IAmazonDynamoDB>()) { var key = new Dictionary <string, AttributeValue>() { { "PRT", new AttributeValue() { S = reqBody.ProviderName } }, { "SRT", new AttributeValue() { S = $"F|SUB|{reqBody.ConsumerName}" } } }; var getSubResponse = await DynamoClient.GetItemAsync("Main", key); if (!getSubResponse.IsItemSet) { var attributes = new Dictionary <string, AttributeValue>(); attributes["PRT"] = new AttributeValue() { S = reqBody.ProviderName }; attributes["SRT"] = new AttributeValue() { S = $"F|SUB|{reqBody.ConsumerName}" }; attributes["G1S"] = new AttributeValue() { S = reqBody.ProviderName }; attributes[reqBody.Protocol] = new AttributeValue() { M = new Dictionary <string, AttributeValue>() { { "Endpoint", new AttributeValue() { S = reqBody.Endpoint } }, { "DiscordServerId", new AttributeValue() { S = reqBody.DiscordServerId } }, { "FilterPolicy", new AttributeValue() { M = new Dictionary <string, AttributeValue>() { { "PolicyType", new AttributeValue() { S = reqBody.FilterPolicy.Type } }, { "Games", new AttributeValue() { SS = reqBody.FilterPolicy.Games } }, { "Categories", new AttributeValue() { SS = reqBody.FilterPolicy.Categories } } } } } } }; var createSubRequest = new PutItemRequest() { TableName = "Main", Item = attributes }; var createSubResponse = await DynamoClient.PutItemAsync(createSubRequest); return(new APIGatewayProxyResponse() { StatusCode = 200, Headers = new Dictionary <string, string> { { "Access-Control-Allow-Origin", "*" } } }); } else { var sub = getSubResponse.Item; sub[reqBody.Protocol] = new AttributeValue() { M = new Dictionary <string, AttributeValue>() { { "Endpoint", new AttributeValue() { S = reqBody.Endpoint } }, { "DiscordServerId", new AttributeValue() { S = reqBody.DiscordServerId } }, { "FilterPolicy", new AttributeValue() { M = new Dictionary <string, AttributeValue>() { { "PolicyType", new AttributeValue() { S = reqBody.FilterPolicy.Type } }, { "Games", new AttributeValue() { SS = reqBody.FilterPolicy.Games } }, { "Categories", new AttributeValue() { SS = reqBody.FilterPolicy.Categories } } } } } } }; var addSubInstanceRequest = new PutItemRequest() { TableName = "Main", Item = sub }; var addSubInstanceResponse = await DynamoClient.PutItemAsync(addSubInstanceRequest); return(new APIGatewayProxyResponse() { StatusCode = 200, Headers = new Dictionary <string, string> { { "Access-Control-Allow-Origin", "*" } } }); } } }
public async Task <APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext context) { LambdaLogger.Log(request.Body); var response = new APIGatewayProxyResponse { StatusCode = (int)HttpStatusCode.OK }; try { var webhookMessage = JsonConvert.DeserializeObject <WebhookMessage>(request.Body); if (webhookMessage == null) { return(response); } var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var botService = serviceProvider.GetService <IBotService>(); if (webhookMessage.Message?.Location != null) { await botService.AskScaleAsync(webhookMessage.Message.Chat.Id, webhookMessage.Message.Location); } if (webhookMessage.CallbackQuery != null && webhookMessage.CallbackQuery.Message.Text == "Pafta ölçeğini seçiniz (1:___.000):" && int.TryParse(webhookMessage.CallbackQuery.Data, out int scale)) { await botService.QuerySheetAsync(webhookMessage.CallbackQuery.Message.MessageId, webhookMessage.CallbackQuery.Id, webhookMessage.CallbackQuery.Message.Chat.Id, scale); } } catch (Exception ex) { LambdaLogger.Log("Error: " + ex.Message); } return(response); }
/// <summary> /// A simple function that takes a string and does a ToUpper /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public string FunctionHandler(string input, ILambdaContext context) { return(input?.ToUpper()); }
public Task HandleAsync(TestNotification message, ILambdaContext context) => _tcs.Task;
public async Task <APIGatewayProxyResponse> Handle(APIGatewayProxyRequest request, ILambdaContext context) { var authenticationResult = authentication.Authenticate(request); switch (authenticationResult) { case AuthenticationResult.Success: context.Logger.Log("DEBUG: Request signature validated"); break; case AuthenticationResult.SignatureNotRequired: context.Logger.Log("WARNING: Request is not signed"); break; case AuthenticationResult.HasSignatureButMissingSecretToken: return(new APIGatewayProxyResponse { StatusCode = 500, Body = "ERROR: Secret token not configured" }); case AuthenticationResult.InvalidSignature: return(new APIGatewayProxyResponse { StatusCode = 400, Body = "ERROR: Invalid signature" }); case AuthenticationResult.InvalidPayload: return(new APIGatewayProxyResponse { StatusCode = 400, Body = "ERROR: Invalid payload" }); case AuthenticationResult.MismatchedSignature: return(new APIGatewayProxyResponse { StatusCode = 401, Body = "ERROR: Mismatched signature" }); default: throw new NotImplementedException($"Unknown authentication result '{authenticationResult}'"); } if (!request.Headers.TryGetValue(XGitHubDeliveryHeaderKey, out var deliveryId)) { return(new APIGatewayProxyResponse { StatusCode = 400, Body = $"Missing {XGitHubDeliveryHeaderKey} header" }); } if (!request.Headers.TryGetValue(XGitHubEventHeaderKey, out var eventId)) { return(new APIGatewayProxyResponse { StatusCode = 400, Body = $"Missing {XGitHubEventHeaderKey} header" }); } context.Logger.Log($"DEBUG: Processing delivery {deliveryId} ({eventId})"); var deliveryResult = new DeliveryResult(); var eventPayload = eventPayloadFactory.CreateEventPayload(eventId, request.Body); deliveryResult.SetEventPayloadType(eventPayload.GetType()); context.Logger.Log($"DEBUG: Payload deserialized as {eventPayload.GetType().Name}"); var handlers = eventHandlers.GetEventHandlersOrDefault(eventPayload); foreach (var handler in handlers) { var result = await handler.HandleEvent(request, context, deliveryId, eventPayload); var resultString = $"{handler}: {result}"; deliveryResult.EventHandlerResults.Add(resultString); context.Logger.Log($"DEBUG: {resultString}"); } return(new APIGatewayProxyResponse { StatusCode = 200, Body = JsonConvert.SerializeObject(deliveryResult, Formatting.Indented) }); }
public async Task <APIGatewayProxyResponse> GetListFunctionHandlerAsync(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) { var table = Environment.GetEnvironmentVariable("TABLE_NAME"); var userid = apigProxyEvent.PathParameters["userid"]; var entitiesRepo = RepositoryFactory.CreateEntityRepository(table); var list = await entitiesRepo.GetEntitiesByUserAsync(userid); return(APIGatewayProxyHelper.JsonAPIGatewayProxyResponse(list)); }
public async Task <ExpandoObject> FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context) { string lisBestSeller = await client.GetStringAsync("https://api.nytimes.com/svc/books/v3/lists/current/hardcover-fiction.json?api-key=vvIEkOE3bG6qWYYFkU48fZhtv7w9n6Nk"); dynamic sampleObject = JsonConvert.DeserializeObject <ExpandoObject>(lisBestSeller); return(sampleObject); }