コード例 #1
0
 public void SetupWebApi(IWebApi webApi, string pathPrefix = "/api/notify")
 {
     webApi.OnPost($"{pathPrefix}/send-verify-code", async(req, res) => {
         Dict values    = await req.ParseAsJsonAsync <Dict>();
         string contact = values.GetAs("contact", (string)null);
         await this.SendVerifyCodeAsync(contact);
     });
 }
コード例 #2
0
        public static async Task TestWeb(IWebApi webServer, string url, Action start)
        {
            // Add routes
            webServer.OnGet("/test-get1", async(req, res) => {
                await res.WriteAsJsonAsync("test-get-response");
            });
            webServer.OnGet("/test-get2/{id}", async(req, res) => {
                await res.WriteAsJsonAsync(req.PathParams.GetAs("id", (string)null));
            });
            webServer.OnPost("/test-post", async(req, res) => {
                var text = await req.ParseAsJsonAsync <string>();
                Assert.AreEqual("test-post-request", text);

                await res.WriteAsJsonAsync("test-post-response");
            });
            webServer.Compile();

            // Start the underlying server
            start();

            // Test GET request #1
            using (WebClient webClient = new WebClient()) {
                string json = await webClient.DownloadStringTaskAsync(new Uri($"{url}test-get1"));

                string text = JsonUtil.Deserialize <string>(json);
                Assert.AreEqual("test-get-response", text);
            }

            // Test GET request #2
            using (WebClient webClient = new WebClient()) {
                string json = await webClient.DownloadStringTaskAsync(new Uri($"{url}test-get2/abc"));

                string text = JsonUtil.Deserialize <string>(json);
                Assert.AreEqual("abc", text);
            }

            // Test POST request
            using (WebClient webClient = new WebClient()) {
                string uploadJson   = JsonUtil.Serialize("test-post-request");
                string downloadJson = await webClient.UploadStringTaskAsync(new Uri($"{url}test-post"), uploadJson);

                string downloadText = JsonUtil.Deserialize <string>(downloadJson);
                Assert.AreEqual("test-post-response", downloadText);
            }
        }
コード例 #3
0
 public static void Setup(IWebApi webApi, Func <string, string, string, string[], Task <string> > handler)
 {
     webApi.OnPost(
         "/api/twilio/webhook",
         async(req, res) => {
         logger.Debug($"/api/twilio/webhook");
         Dictionary <string, string> evt = await req.ParseAsUrlEncodedAsync();
         logger.Debug($"/api/twilio/webhook,evt=" + JsonUtil.Serialize(evt));
         string fromPhone    = evt.GetAs("From", (string)null);
         string toPhone      = evt.GetAs("To", (string)null);
         string body         = evt.GetAs("Body", (string)null);
         int numMedia        = evt.GetAs("NumMedia", 0);
         string[] mediaUrls  = Enumerable.Range(0, numMedia).Select(x => evt.GetAs($"MediaUrl{x}", (string)null)).ToArray();
         string responseText = await handler(fromPhone, toPhone, body, mediaUrls);
         //logger.Debug($"/api/twilio/webhook,responseText={responseText}");
         if (!string.IsNullOrEmpty(responseText))
         {
             await res.WriteAsTextAsync(responseText);
         }
     }
         );
 }
コード例 #4
0
        /// <summary>
        /// Call to setup a Web API with the specified <paramref name="webApi"/>
        /// </summary>
        /// <remarks>
        /// The following API URLs will be setup...
        /// <code>
        ///     GET /api/auth/check-username/{username}
        ///     GET /api/auth/check-auth-token/{id}
        ///     POST /api/auth/create-anonymous
        ///     POST /api/auth/register
        ///     POST /api/auth/login
        ///     POST /api/auth/forgot-password
        ///     POST /api/auth/reset-password
        ///     POST /api/auth/verify-email
        ///     POST /api/auth/verify-phone
        /// </code>
        /// </remarks>
        /// <param name="webApi"></param>
        /// <param name="pathPrefix">Defaults to /api/auth</param>
        public void SetupWebApi(IWebApi webApi, string pathPrefix = "/api/auth")
        {
            webApi.OnGet($"{pathPrefix}/check-username/{{username}}", async(req, res) => {
                string username = req.PathParams.GetAs("username", (string)null);
                logger.Debug($"/check-username/{username}");
                Dict user      = await this.LookupUsernameAsync(username, this.userTableIdFieldName);
                bool available = user == null;
                await res.WriteAsJsonAsync(available);
            });

            webApi.OnGet($"{pathPrefix}/check-auth-token/{{id}}", async(req, res) => {
                string id             = req.PathParams.GetAs("id", (string)null);
                string rawVersionText = req.QueryParams.GetAs("v", "");
                string versionText    = VERSION_CLEAN_REGEX.Replace(rawVersionText, "");
                Version version       = string.IsNullOrEmpty(versionText) ? null : Version.Parse(versionText);
                logger.Debug($"/check-auth-token/{id}?v={version}"); //?join_code={joinCode}");
                if (this.onCheckVersion != null)
                {
                    this.onCheckVersion(version);
                }
                AuthToken authToken = await this.AuthenticateAsync(id);
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/create-anonymous", async(req, res) => {
                Dict data           = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.CreateAnonymousUserAsync();
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/register", async(req, res) => {
                Dict registration   = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.RegisterAsync(registration, new Dict {
                    { "host_name", Dns.GetHostName() },
                    { "user_agent", req.Headers.GetAs("User-Agent", "") },
                    { "user_host_name", req.Headers.GetAs("Host", "") },
                });
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/login", async(req, res) => {
                Dict login          = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.LoginAsync(login);
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/forgot-password", async(req, res) => {
                Dict data       = await req.ParseAsJsonAsync <Dict>();
                string username = data.GetAs("username", (string)null);
                await this.ForgotPasswordAsync(username);
            });

            webApi.OnPost($"{pathPrefix}/reset-password", async(req, res) => {
                Dict resetPassword  = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.ResetPasswordAsync(resetPassword);
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/verify-email", async(req, res) => {
                Dict data = await req.ParseAsJsonAsync <Dict>();
                await this.VerifyAsync(data, "email", "email_verified_at", this.onEmailVerify);
            });

            webApi.OnPost($"{pathPrefix}/verify-phone", async(req, res) => {
                Dict data = await req.ParseAsJsonAsync <Dict>();
                await this.VerifyAsync(data, "phone", "phone_verified_at", this.onPhoneVerify);
            });
        }
コード例 #5
0
        public static async Task SetupAsync(IWebApi webApi, string topicArn, string endPoint, string bucketName, Func <string, string, string[], Task <string> > handler)
        {
            if (!string.IsNullOrEmpty(endPoint))
            {
                Uri endPointUri = new Uri(endPoint);
                //logger.Debug($"SetupWebApi():endPointUri.PathAndQuery={endPointUri.PathAndQuery}");

                using (AmazonSimpleNotificationServiceClient amazonSimpleNotificationServiceClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast1)) {
                    SubscribeResponse subscribeResponse = await amazonSimpleNotificationServiceClient.SubscribeAsync(new SubscribeRequest {
                        TopicArn = topicArn,
                        Protocol = endPointUri.Scheme,
                        Endpoint = endPoint
                    });
                }

                AmazonS3Client amazonS3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);

                webApi.OnPost(
                    endPointUri.PathAndQuery,
                    async(req, res) => {
                    logger.Debug($"{endPointUri.PathAndQuery}");
                    Dict evt = await req.ParseAsJsonAsync <Dict>();
                    logger.Debug($"{endPointUri.PathAndQuery},evt=" + JsonUtil.Serialize(evt));
                    string type = evt.GetAs("Type", (string)null);
                    if (type == "SubscriptionConfirmation")
                    {
                        string subscribeUrl = evt.GetAs("SubscribeURL", (string)null);
                        using (WebClient webClient = new WebClient()) {
                            string result = await webClient.DownloadStringTaskAsync(new Uri(subscribeUrl));
                            logger.Debug($"{endPointUri.PathAndQuery},result=" + result);
                        }
                    }
                    else if (type == "Notification")
                    {
                        //string messageId = evt.GetAs("MessageId", (string)null);
                        string messageJson = evt.GetAs("Message", (string)null);
                        logger.Debug($"{endPointUri.PathAndQuery},messageJson={messageJson}");

                        Dict message = JsonUtil.Deserialize <Dict>(messageJson);
                        Dict mail    = message.GetAs("mail", (Dict)null);

                        Dict[] headers       = mail.GetAs("headers", (Dict[])null);
                        Dict inReplyToHeader = Array.Find(headers, x => x.GetAs("name", "") == "In-Reply-To");
                        string inReplyTo     = inReplyToHeader.GetAs("value", "");
                        logger.Debug($"{endPointUri.PathAndQuery},inReplyTo={inReplyTo}");
                        Match match = IN_REPLY_TO_REGEX.Match(inReplyTo);
                        if (match.Success)
                        {
                            string sentMessageId = match.Groups[1].Value;
                            string bucketKey     = mail.GetAs("messageId", (string)null);
                            logger.Debug($"{endPointUri.PathAndQuery},sentMessageId={sentMessageId},bucketKey={bucketKey}");
                            if (!string.IsNullOrEmpty(bucketKey))
                            {
                                GetObjectResponse getObjectResponse = await amazonS3Client.GetObjectAsync(new GetObjectRequest {
                                    BucketName = bucketName,
                                    Key        = bucketKey
                                });
                                logger.Debug($"{endPointUri.PathAndQuery},getObjectResponse={getObjectResponse}");

                                MimeMessage mimeMessage = await MimeMessage.LoadAsync(getObjectResponse.ResponseStream);
                                logger.Debug($"{endPointUri.PathAndQuery},mimeMessage={mimeMessage}");

                                await handler(sentMessageId, mimeMessage.TextBody, new string[] { });
                            }
                        }
                    }
                }
                    );
            }
        }
コード例 #6
0
ファイル: AuthManager.cs プロジェクト: NeoTim/butterfly-auth
        /// <summary>
        /// Call to setup a Web API with the specified <paramref name="webApi"/>
        /// </summary>
        /// <remarks>
        /// The following API URLs will be setup...
        /// <code>
        ///     GET /api/auth/check-username/{username}
        ///     GET /api/auth/check-auth-token/{id}
        ///     POST /api/auth/create-anonymous
        ///     POST /api/auth/register
        ///     POST /api/auth/login
        ///     POST /api/auth/forgot-password
        ///     POST /api/auth/reset-password
        ///     POST /api/auth/verify
        /// </code>
        /// </remarks>
        /// <param name="webApi"></param>
        /// <param name="pathPrefix">Defaults to /api/auth</param>
        public void SetupWebApi(IWebApi webApi, string pathPrefix = "/api/auth")
        {
            webApi.OnGet($"{pathPrefix}/check-username/{{username}}", async(req, res) => {
                string username = req.PathParams.GetAs("username", (string)null);
                logger.Debug($"/check-username/{username}");
                Dict user      = await this.LookupUsernameAsync(username, this.userTableIdFieldName);
                bool available = user == null;
                await res.WriteAsJsonAsync(available);
            });

            webApi.OnGet($"{pathPrefix}/check-user-ref-token/{{id}}", async(req, res) => {
                string id             = req.PathParams.GetAs("id", (string)null);
                string rawVersionText = req.QueryParams.GetAs("v", "");
                string versionText    = VERSION_CLEAN_REGEX.Replace(rawVersionText, "");
                Version version       = string.IsNullOrEmpty(versionText) ? null : Version.Parse(versionText);
                logger.Debug($"/check-auth-token/{id}?v={version}"); //?join_code={joinCode}");
                if (this.onCheckVersion != null)
                {
                    this.onCheckVersion(version);
                }
                AuthToken authToken = await this.AuthenticateAsync(UserRefTokenAuthenticator.AUTH_TYPE, id);
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/create-anonymous", async(req, res) => {
                Dict data           = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.CreateAnonymousUserAsync();
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/register", async(req, res) => {
                Dict registration   = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.RegisterAsync(registration);
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/login", async(req, res) => {
                Dict login          = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.LoginAsync(login);
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/forgot-password", async(req, res) => {
                Dict data       = await req.ParseAsJsonAsync <Dict>();
                string username = data.GetAs("username", (string)null);
                await this.ForgotPasswordAsync(username);
            });

            webApi.OnPost($"{pathPrefix}/reset-password", async(req, res) => {
                Dict resetPassword  = await req.ParseAsJsonAsync <Dict>();
                AuthToken authToken = await this.ResetPasswordAsync(resetPassword);
                await res.WriteAsJsonAsync(authToken);
            });

            webApi.OnPost($"{pathPrefix}/forgot-username", async(req, res) => {
                Dict data      = await req.ParseAsJsonAsync <Dict>();
                string contact = data.GetAs("contact", (string)null);
                await this.ForgotUsernameAsync(contact);
            });

            webApi.OnPost($"{pathPrefix}/send-email-verify-code", async(req, res) => {
                UserRefToken userRefToken = await this.GetUserRefToken(req);

                string email = await this.database.SelectValueAsync <string>("SELECT email FROM user", vars: userRefToken.userId);
                await this.SendVerifyCodeAsync(email);
            });

            webApi.OnPost($"{pathPrefix}/send-phone-verify-code", async(req, res) => {
                UserRefToken userRefToken = await this.GetUserRefToken(req);

                string phone = await this.database.SelectValueAsync <string>("SELECT phone FROM user", vars: userRefToken.userId);
                await this.SendVerifyCodeAsync(phone);
            });


            webApi.OnPost($"{pathPrefix}/verify", async(req, res) => {
                Dict data = await req.ParseAsJsonAsync <Dict>();
                await this.VerifyAsync(data);
            });
        }