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);
            }
        }
        /// <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);
            });
        }
Exemplo n.º 3
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
        /// </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);
            });
        }