public void Post_UnvalidAuthCode_TictailException()
        {
            var oauth = new Oauth
            {
                AuthCode     = "authcode_BAD",
                ClientId     = "clientid_ABCDEFGHIJKLM9876543",
                ClientSecret = "clientsecret_123456789abcdefghij"
            };

            const string tictailJsonReponse = "{" +
                                              "\"status\": 400, " +
                                              "\"message\": \"Invalid authorization code given\"," +
                                              "\"params\": {}, " +
                                              "\"support_email\": \"[email protected]\"" +
                                              "}";

            var testClient = new TictailClientTest
            {
                Content        = tictailJsonReponse,
                ResponseStatus = ResponseStatus.Completed,
                StatusCode     = HttpStatusCode.BadRequest
            };

            var sut = new OauthRepository(testClient);

            var tictailException = Assert.Throws <TictailException>(() => sut.Post(oauth));

            Assert.Equal(400, tictailException.Status);
            Assert.Equal("Invalid authorization code given", tictailException.Message);
            Assert.Equal("*****@*****.**", tictailException.SupportEmail);
        }
        /// <summary>
        /// All is OK : used by Post_ValidAuthCode_AccessToken
        /// </summary>
        /// <param name="oauth">The oauth data going in</param>
        /// <returns>A token</returns>
        public Token Post(Oauth oauth)
        {
            const string tictailJsonReponse = "{" +
                                              "\"access_token\": \"accesstoken_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"," +
                                              "\"token_type\": \"Bearer\"," +
                                              "\"expires_in\": 3155760000," +
                                              "\"store\": {" +
                                              "\"id\": \"ab1\"," +
                                              "\"name\": \"Some example store\"," +
                                              "\"language\": \"en\"," +
                                              "\"url\": \"http://example.tictail.com\"," +
                                              "\"storekeeper_email\": \"[email protected]\"," +
                                              "\"created_at\": \"1999-02-12T20:10:20\"," +
                                              "\"modified_at\": null" +
                                              "}" +
                                              "}";

            var testClient = new TictailClientTest
            {
                Content        = tictailJsonReponse,
                ResponseStatus = ResponseStatus.Completed,
                StatusCode     = HttpStatusCode.OK
            };

            var sut = new OauthRepository(testClient);

            return(sut.Post(oauth));
        }
Esempio n. 3
0
        public async Task <IActionResult> CreateSmartApp(OauthInfo authInfo)
        {
            if (ModelState.IsValid == false)
            {
                return(View(authInfo));
            }

            var conn = new SmartThingsConnection();

            if (await conn.Login(authInfo.STUserId, authInfo.STPassword) == false)
            {
                ModelState.AddModelError("STPassword", "Could not connect to smart things using the supplied credentials");
                return(View("Index", authInfo));
            }

            var cs = new DeviceTypeRepository(conn, "j64 Alarm", $"{myEnv.WebRootPath}/../SmartThingApps/j64AlarmDevice.groovy");
            var ss = new DeviceTypeRepository(conn, "j64 Contact Zone", $"{myEnv.WebRootPath}/../SmartThingApps/j64ContactZoneDevice.groovy");
            var mz = new DeviceTypeRepository(conn, "j64 Motion Zone", $"{myEnv.WebRootPath}/../SmartThingApps/j64MotionZoneDevice.groovy");
            var pd = new DeviceTypeRepository(conn, "j64 Partition", $"{myEnv.WebRootPath}/../SmartThingApps/j64PartitionDevice.groovy");

            var jal = new SmartAppRepository(conn, "j64 Alarm", $"{myEnv.WebRootPath}/../SmartThingApps/j64AlarmSmartApp.groovy");

            // Save the client/secret keys
            var oauth = OauthRepository.Get();

            oauth.clientKey = jal.clientKey;
            oauth.secretKey = jal.secretKey;
            OauthRepository.Save(oauth);

            return(View("Index", oauth));
        }
Esempio n. 4
0
        public IActionResult Index()
        {
            ViewBag.ClientId     = _oAuthConfig.ClientId;
            ViewBag.ClientSecret = _oAuthConfig.ClientSecret;

            var repo = OauthRepository.Get();

            return(View(repo));
        }
Esempio n. 5
0
        public IActionResult Index()
        {
            var repo = OauthRepository.Get();

            if (string.IsNullOrWhiteSpace(repo.clientKey))
            {
                repo.clientKey = "600e71d3-ea32-4c3d-be3f-8f1614c4e562";
                repo.secretKey = "391bdbaa-892b-445e-90f6-2a453da81816";
            }

            return(View(repo));
        }
Esempio n. 6
0
        public IActionResult Index()
        {
            // If not connected to the smart hub go to the configure page
            if (myHub.hubConfig == null || String.IsNullOrEmpty(j64Config.ChannelDevice) || String.IsNullOrEmpty(j64Config.VolumeDevice))
            {
                return(RedirectToAction("Edit", "FirstTimeConfig"));
            }

            if (String.IsNullOrEmpty(OauthRepository.Get().accessToken))
            {
                return(RedirectToAction("Index", "Oauth"));
            }

            return(View(myHomeViewModel));
        }
Esempio n. 7
0
        public ActionResult BeginAuth([Bind("clientKey", "secretKey")] OauthInfo authInfo)
        {
            string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");

            // Reset the token info
            authInfo.accessToken      = null;
            authInfo.tokenType        = null;
            authInfo.expiresInSeconds = 0;

            OauthRepository.Save(authInfo);

            string Url = $"https://graph.api.smartthings.com/oauth/authorize?response_type=code&scope=app&redirect_uri={authorizedUrl}&client_id={authInfo.clientKey}";

            return(Redirect(Url));
        }
        private SmartThingsService GetSmartThingsService()
        {
            OauthInfo authInfo = OauthRepository.Get();

            if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
            {
                throw new Exception("OAuth endpoints have not been created. Cannot update smart things at this time");
            }
            string url   = authInfo.endpoints[0].uri;
            string token = authInfo.accessToken;

            SmartThingsService service = new SmartThingsService(token, url);

            return(service);
        }
Esempio n. 9
0
        public async Task <IActionResult> Devices()
        {
            OauthInfo authInfo = OauthRepository.Get();

            if (authInfo == null | authInfo.endpoints == null || authInfo.endpoints.Count == 0)
            {
                throw new Exception("OAuth endpoints have not been created. Cannot update smart things at this time");
            }
            string url   = authInfo.endpoints[0].uri;
            string token = authInfo.accessToken;

            SmartThingsService service = new SmartThingsService(token, url);
            var devices = await service.ListDevices();

            return(View(devices));
        }
Esempio n. 10
0
        public IActionResult Index()
        {
            if (myHub.hubConfig == null || String.IsNullOrEmpty(j64Config.ChannelDevice) || String.IsNullOrEmpty(j64Config.VolumeDevice))
            {
                return(RedirectToAction("Edit", "FirstTimeConfig"));
            }

            var oauth = OauthRepository.Get();
            var ovm   = new OauthViewModel()
            {
                ClientKey = oauth.clientKey,
                SecretKey = oauth.secretKey
            };

            return(View(ovm));
        }
        public IActionResult Index()
        {
            // If not connected to the smart hub go to the configure page
            if (myHub.hubConfig == null || String.IsNullOrEmpty(j64Config.ChannelDevice) || String.IsNullOrEmpty(j64Config.VolumeDevice))
            {
                return(RedirectToAction("Edit", "FirstTimeConfig"));
            }

            if (String.IsNullOrEmpty(OauthRepository.Get().accessToken))
            {
                return(RedirectToAction("Index", "Oauth"));
            }

            List <FavoriteChannelViewModel> l = new List <FavoriteChannelViewModel>();

            j64Config.FavoriteChannels.ForEach(x => l.Add(new FavoriteChannelViewModel()
            {
                ChannelNumber = x.Channel, Name = x.Name
            }));

            return(View(l));
        }
Esempio n. 12
0
        public async Task <IActionResult> CreateSmartApp(OauthViewModel authInfo)
        {
            if (ModelState.IsValid == false)
            {
                return(View(authInfo));
            }

            var conn = new SmartThingsConnection();

            if (await conn.Login(authInfo.STUserId, authInfo.STPassword) == false)
            {
                ModelState.AddModelError("STPassword", "Could not connect to smart things using the supplied credentials");
                return(View("Index", authInfo));
            }

            var cs = new DeviceTypeRepository(conn, "j64 Channel Switch", $"{myEnv.WebRootPath}/../SmartThingApps/j64ChannelSwitchDevice.groovy");
            var ss = new DeviceTypeRepository(conn, "j64 Surfing Switch", $"{myEnv.WebRootPath}/../SmartThingApps/j64SurfingSwitchDevice.groovy");
            var vs = new DeviceTypeRepository(conn, "j64 VCR Switch", $"{myEnv.WebRootPath}/../SmartThingApps/j64VcrSwitchDevice.groovy");
            var os = new DeviceTypeRepository(conn, "j64 Volume Switch", $"{myEnv.WebRootPath}/../SmartThingApps/j64VolumeSwitchDevice.groovy");
            var cc = new DeviceTypeRepository(conn, "j64 Custom Command Switch", $"{myEnv.WebRootPath}/../SmartThingApps/j64CustomCommandSwitchDevice.groovy");

            var har = new SmartAppRepository(conn, "j64 Harmony", $"{myEnv.WebRootPath}/../SmartThingApps/j64HarmonySmartApp.groovy");

            // Save the client/secret keys
            var oauth = OauthRepository.Get();

            oauth.clientKey = har.clientKey;
            oauth.secretKey = har.secretKey;
            OauthRepository.Save(oauth);

            var ovm = new OauthViewModel()
            {
                ClientKey = oauth.clientKey,
                SecretKey = oauth.secretKey
            };

            return(View("Index", ovm));
        }
        public void DeserializeGet_ValidTokenJson_Token()
        {
            const string accessJson = "{" +
                                      "\"access_token\": \"accesstoken_abcdef123456\", " +
                                      "\"token_type\": \"Bearer\", " +
                                      "\"expires_in\": 123450000, " +
                                      "\"store\": {" +
                                      "\"description\": \"Some description\", " +
                                      "\"language\": \"en\", " +
                                      "\"url\": \"http://some.tictail.com\", " +
                                      "\"country\": \"SE\", " +
                                      "\"created_at\": \"2013-01-02T10:15:18\", " +
                                      "\"dashboard_url\": \"https://tictail.com/dashboard/store/somedashboard\", " +
                                      "\"modified_at\": null, " +
                                      "\"logotype\": null, " +
                                      "\"appstore_currency\": \"SEK\", " +
                                      "\"currency\": \"SEK\", " +
                                      "\"sandbox\": true, " +
                                      "\"contact_email\": \"\", " +
                                      "\"storekeeper_email\": \"[email protected]\", " +
                                      "\"short_description\": null, " +
                                      "\"followers\": 0, " +
                                      "\"name\": \"A random name\", " +
                                      "\"id\": \"ab1\", " +
                                      "\"vat\": {" +
                                      "\"applied_to_shipping\": true, " +
                                      "\"rate\": \"0.250000\", " +
                                      "\"region\": \"SE\", " +
                                      "\"included_in_prices\": true" +
                                      "}," +
                                      "\"wallpapers\": {}" +
                                      "}" +
                                      "}";
            var sut = new OauthRepository(new TictailClientTest());

            var token = sut.DeserializeGet(accessJson);

            Assert.Equal("accesstoken_abcdef123456", token.AccessToken);
            Assert.Equal("Bearer", token.TokenType);
            Assert.Equal(123450000, token.ExpiresIn);
            Assert.NotNull(token.Store);
            Assert.Equal("Some description", token.Store.Description);
            Assert.Equal("en", token.Store.Language);
            Assert.Equal("http://some.tictail.com", token.Store.Url);
            Assert.Equal("SE", token.Store.Country);
            Assert.Equal(new DateTime(2013, 1, 2, 10, 15, 18), token.Store.CreatedAt);
            Assert.Equal("https://tictail.com/dashboard/store/somedashboard", token.Store.DashboardUrl);
            Assert.Null(token.Store.ModifiedAt);
            Assert.Null(token.Store.Logotypes);
            Assert.Equal("SEK", token.Store.AppstoreCurrency);
            Assert.Equal("SEK", token.Store.Currency);
            Assert.True(token.Store.Sandbox);
            Assert.Equal("", token.Store.ContactEmail);
            Assert.Equal("*****@*****.**", token.Store.StorekeeperEmail);
            Assert.Null(token.Store.ShortDescription);
            Assert.Equal(0, token.Store.NumberOfFollowers);
            Assert.Equal("A random name", token.Store.Name);
            Assert.Equal("ab1", token.Store.Id);
            //TODO: Wallpapers
            Assert.NotNull(token.Store.Vat);
            Assert.True(token.Store.Vat.AppliedToShipping);
            Assert.Equal(0.25m, token.Store.Vat.Rate);
            Assert.Equal("SE", token.Store.Vat.Region);
            Assert.True(token.Store.Vat.IncludedInPrices);
        }
Esempio n. 14
0
        public IActionResult Authorized(string code)
        {
            OauthInfo oai = OauthRepository.Get();

            if (code == null)
            {
                return(View(oai));
            }

            oai.authCode = code;

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            var url = "https://graph.api.smartthings.com/oauth/token";

            List <KeyValuePair <string, string> > parms = new List <KeyValuePair <string, string> >();

            parms.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
            parms.Add(new KeyValuePair <string, string>("code", oai.authCode));
            parms.Add(new KeyValuePair <string, string>("client_id", oai.clientKey));
            parms.Add(new KeyValuePair <string, string>("client_secret", oai.secretKey));
            string authorizedUrl = "http://" + this.Request.Host.Value + this.Url.Content("~/OAuth/Authorized");

            parms.Add(new KeyValuePair <string, string>("redirect_uri", authorizedUrl));

            var content  = new System.Net.Http.FormUrlEncodedContent(parms);
            var response = client.PostAsync(url, content);

            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get Auth Code Error: " + response.Result.StatusCode.ToString());
                return(View(oai));
            }

            // Save the interim result
            var val = JsonConvert.DeserializeObject <Dictionary <string, string> >(response.Result.Content.ReadAsStringAsync().Result);

            oai.accessToken      = val["access_token"];
            oai.expiresInSeconds = Convert.ToInt32(val["expires_in"]);
            oai.tokenType        = val["token_type"];
            OauthRepository.Save(oai);

            // Get the endpoint info
            client = new System.Net.Http.HttpClient();
            url    = "https://graph.api.smartthings.com/api/smartapps/endpoints";

            System.Net.Http.HttpRequestMessage msg = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            msg.Headers.Add("Authorization", $"Bearer {oai.accessToken}");

            response = client.SendAsync(msg);
            response.Wait();

            if (response.Result.StatusCode != System.Net.HttpStatusCode.OK)
            {
                ViewData.Add("GetTokenError", "Get EndPoints Error: " + response.Result.StatusCode.ToString());
                return(View(oai));
            }

            string jsonString = response.Result.Content.ReadAsStringAsync().Result;

            oai.endpoints = JsonConvert.DeserializeObject <List <OauthEndpoint> >(jsonString);

            OauthRepository.Save(oai);

            // Prepare the smart app to be called from the local traffic
            SmartThingsRepository.PrepTheInstall(j64Config);

            // Send all of the default devices to the smart app
            SmartThingsRepository.InstallDevices(j64Config, Request.Host.Value);

            // all done!
            return(View(oai));
        }
 public IActionResult Index()
 {
     return(View(OauthRepository.Get()));
 }
Esempio n. 16
0
        public IActionResult Index()
        {
            var repo = OauthRepository.Get();

            return(View(repo));
        }