示例#1
0
        /// <summary>
        /// Creates or Inserts (upserts) a Subscriber based on their email
        /// </summary>
        /// <param name="sub"></param>
        /// <returns></returns>
        public async Task UpsertSubscriber(PostedSubscribeObject sub)
        {
            await FirestoreSetup();

            Subscriber s = Subscriber.FromPostedSubscriber(sub);

            try {
                DocumentReference doc = DBHandle.Collection(SUBSCRIBERS).Document(s.DocumentId);
                if (doc != null)
                {
                    DocumentSnapshot ds = await doc.GetSnapshotAsync();

                    if (ds.Exists)
                    {
                        // UPDATE
                        await DBHandle.RunTransactionAsync(async transaction => {
                            transaction.Update(doc, "matches", s.Matches);
                        });

                        return;
                    }
                }
                // CREATE
                await DBHandle.RunTransactionAsync(async transaction => {
                    transaction.Create(doc, s);
                });

                return;
            }
            catch (Exception e) {
                Logger.Log($"Some error ocurred while Upserting a subscriber: {e.Message}");
                // some error ocurred while trying to create or update a subscriber
            }
        }
示例#2
0
文件: Function.cs 项目: 0xNF/esk8bst
        /// <summary>
        /// Adds users email to the database with their chosen match objects.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> ConfirmSubscribe(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = new Esk8LambdaLogger(context.Logger);

            logger.Log("Confirm Subscribe endpoint reached");

            if (request.QueryStringParameters.ContainsKey("confirmkey"))
            {
                string encryptionkey = Environment.GetEnvironmentVariable("ESK8BST_ENCRYPTION_KEY");
                string b64payload    = request.QueryStringParameters["confirmkey"];
                logger.Log("Received this as the confirm key: " + request.QueryStringParameters["confirmkey"]);
                string decrypted          = EncryptorService.DecryptConfirmKey(b64payload, encryptionkey);
                PostedSubscribeObject pso = null;
                try {
                    JObject jobj = JObject.Parse(decrypted);
                    pso = PostedSubscribeObject.FromJson(jobj);
                } catch (Exception e) {
                    logger.Log($"Tried to parse malformed json and failed at Confirm Subscribe: {e.Message}");
                    return(new APIGatewayProxyResponse()
                    {
                        StatusCode = (int)HttpStatusCode.InternalServerError,
                        Body = "Failed to parse json properly",
                        Headers = new Dictionary <string, string> {
                            { "Content-Type", "text/plain" }
                        },
                    });
                }

                if (pso != null && pso.Email.Contains("@") && pso.Matches.Count > 0)
                {
                    FirestoreService FSS = new FirestoreService(logger);
                    await FSS.UpsertSubscriber(pso);

                    await FSS.InsertPreconfirmed(pso.Email);

                    return(new APIGatewayProxyResponse()
                    {
                        StatusCode = (int)HttpStatusCode.Created,
                        Body = "Alright! You've been confirmed as interested in receiving updates from https://esk8bst.com",
                        Headers = new Dictionary <string, string> {
                            { "Content-Type", "text/plain" }
                        },
                    });
                }
            }

            return(new APIGatewayProxyResponse()
            {
                StatusCode = (int)HttpStatusCode.BadRequest,
                Body = "Failed to properly parse the confirm link.",
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            });
        }
示例#3
0
        public static List <PostedSubscribeObject> ParseSubscribers(JArray jarr)
        {
            List <PostedSubscribeObject> subs = new List <PostedSubscribeObject>();

            foreach (JObject jobj in jarr)
            {
                PostedSubscribeObject pso = PostedSubscribeObject.FromJson(jobj);
                subs.Add(pso);
            }
            return(subs);
        }
示例#4
0
        public async Task TestDecryptConfirmKey()
        {
            string  b64       = "KwB6AEgATwBtAGIAMwBzAGwAQgA4AHQAcQBFAGsAUABPAEYAaQBnAEkARgBXAHAAawBVAFYAawBsAGIATgAzAHkAWAA2AEQAWQB6AHYAaQA5AHcATQBxAG0AbQBZAHUASwB5AEsARABLAE8AOQB4AC8AcQBqAHYAegBSAE8ALwBoAE0ARgBJAEIAdwBEADQAYwBmAFIAWABkAHAAdwB6AFUAegBNAGUATQBhADgARgBoAHoAUwBqADAAdQArAHYAaABnADUAegBMAHIATwA4AFQANABwAFMAaABVAEMAawB3ADIAdQByAG0ALwBGAEkAWgB0ADcAZQBmAEkARQAwAHEANgAyAEYAeQBZAFoASwBUAFcAOQBsADUAcgBiAGgALwAwAFIATwBxAGgARABHAHMASgBRAG0AagAyADEATgBzAGIAbQBTAGsANgBvAFMAOQBOAGoAdgBhAE4ASABJAGcAbABRAGoAUgAyAHgAawBBAGsAagA1AHQAZABOAHUAcQBZAEUAdwBaAFcARwBPAEYALwBjAGcAOQAzADkAcABsAEgAdwAzAHoAYgBhAGwAawBYAC8AcgBwAHgAcQBBAGQARQBOAGcARgBCAFAAcQBpAFoAcQA4AHUANgB0AHkAagBKADgAaQBsAEoAUwBHADcAYQBkAHkANwBuAHoAOABHAHUAWABHAEIAcgBIAFEAMQBJAHkAegB6AHcANQBLAGYAcwBsAFkAMwBRAD0APQA*";
            string  decrypted = EncryptorService.DecryptConfirmKey(b64, key);
            JObject jobj      = JObject.Parse(decrypted);
            PostedSubscribeObject decryptedPso = PostedSubscribeObject.FromJson(jobj);

            Assert.Equal(decryptedPso.Email, pso.Email);
            PostedMatchObject postedMatch = decryptedPso.Matches.FirstOrDefault();
            PostedMatchObject staticMatch = pso.Matches.FirstOrDefault();

            Assert.Equal(postedMatch.BST, staticMatch.BST);
            Assert.Equal(postedMatch.Currency, staticMatch.Currency);
            Assert.Equal(postedMatch.Price, staticMatch.Price);
            Assert.Equal(postedMatch.Companies.Count, staticMatch.Companies.Count);
        }
示例#5
0
        public async Task TestSubscribeMethod()
        {
            TestLambdaContext       context;
            APIGatewayProxyRequest  request;
            APIGatewayProxyResponse response;

            Functions functions = new Functions();

            PostedSubscribeObject pso = new PostedSubscribeObject()
            {
                Email   = "*****@*****.**",
                Matches = new List <PostedMatchObject>()
                {
                    new PostedMatchObject()
                    {
                        BST       = "SELL",
                        Companies = new List <string>()
                        {
                            "boosted"
                        },
                        Currency = "USD",
                        Price    = 1000
                    }
                }
            };
            string s = pso.ToJson().ToString();


            request = new APIGatewayProxyRequest {
                HttpMethod = HttpMethod.Post.Method,
                Body       = s
            };
            context  = new TestLambdaContext();
            response = await functions.Subscribe(request, context);

            Assert.Equal((int)HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("An email has been sent to the address specified confirming your subscription", response.Body);
        }
示例#6
0
文件: Function.cs 项目: 0xNF/esk8bst
        /// <summary>
        /// The endpoint hit when a user submits their email to esk8bst
        /// This schedules a Mailgun Email that will include a Confirm Subscribe Link
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> Subscribe(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = new Esk8LambdaLogger(context.Logger);

            logger.Log("Subscribe endpoint reached");


            if (request.HttpMethod != HttpMethod.Post.Method)
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.MethodNotAllowed
                });
            }
            ;

            string postbody           = request.Body;
            PostedSubscribeObject pso = null;
            string confirmkey         = "";

            try {
                JObject jobj = JObject.Parse(postbody);
                pso = PostedSubscribeObject.FromJson(jobj);

                if (pso.Email.Contains("@") && pso.Matches.Count > 0)   // we can proceed

                {
                    FirestoreService FSS = new FirestoreService(logger);
                    if (await FSS.CheckIsPreconfirmed(pso.Email))
                    {
                        // Immediately subscribe the user, they've already been here.
                        await FSS.UpsertSubscriber(pso);

                        return(new APIGatewayProxyResponse()
                        {
                            StatusCode = (int)HttpStatusCode.Created,
                            Headers = new Dictionary <string, string> {
                                { "Content-Type", "text/plain" }
                            },
                            Body = "Alright! You've been confirmed as interested in receiving updates from https://esk8bst.com",
                        });
                    }
                    else
                    {
                        // Not pre-confirmed, send an opt-in email.
                        string encryptionKey = Environment.GetEnvironmentVariable("ESK8BST_ENCRYPTION_KEY");
                        confirmkey = EncryptorService.CreateConfirmKey(pso.ToJson().ToString(), encryptionKey);
                    }
                }
            } catch (Exception e) {
                logger.Log($"Tried to parse a malformed subscriber json: {e.Message}");
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                    Body = "Failed to parse json properly",
                });
            }

            if (String.IsNullOrWhiteSpace(confirmkey))
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "Failed to parse json properly - no email found",
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            MailgunService MSS = new MailgunService(logger);
            MailgunEmail   m   = new MailgunEmail()
            {
                To = new List <string> {
                    pso.Email
                },
                From    = MailgunService.POSTMASTER,
                Subject = "Esk8Bst Notification Opt In Request",
                Body    = "" +
                          "Someone has registered you as being interested in receiving notifications about new electric skateboard postings from https://esk8bst.com.\n\n" +
                          "If this was you, please click the link below to confirm your email. If this was not you, or you no longer wish to receive emails from us, then ignore this message.\n\n" +
                          $"https://1lol87xzbj.execute-api.us-east-2.amazonaws.com/Prod/confirm?confirmkey={confirmkey}",
            };

            bool success = await MSS.Send(m);

            if (!success)
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "Failed to send email to recipent",
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            //An email has been sent to the address specified confirming your subscription
            var response = new APIGatewayProxyResponse {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = "An email has been sent to the address specified confirming your subscription",
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            };

            return(response);
        }