예제 #1
0
        public async Task <OAuth2AccessToken> ExchangeAuthCodeForAccessTokenAsync(string code)
        {
            HttpClient httpClient = new HttpClient();

            string postUrl = OAuth2Helper.FitbitOauthPostUrl;

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("client_id", ClientId),
                //new KeyValuePair<string, string>("client_secret", AppSecret),
                new KeyValuePair <string, string>("code", code),
                new KeyValuePair <string, string>("redirect_uri", this.RedirectUri)
            });


            string clientIdConcatSecret = OAuth2Helper.Base64Encode(ClientId + ":" + ClientSecret);

            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", clientIdConcatSecret);

            HttpResponseMessage response = await httpClient.PostAsync(postUrl, content);

            string responseString = await response.Content.ReadAsStringAsync();

            OAuth2AccessToken accessToken = OAuth2Helper.ParseAccessTokenResponse(responseString);

            return(accessToken);
        }
예제 #2
0
        // 20171026 Pandita: Mejor no poner token en DB

        /*
         * // Add user token to the the TokenManagement Table in DB
         * private void SyncFitbitCred(OAuth2AccessToken accessToken)
         * {
         *  if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
         *  {
         *
         *      string userId = System.Web.HttpContext.Current.User.Identity.GetUserId();
         *      var userToken = from table in Db.TokenManagement
         *                      where table.AspNetUserId.Equals(userId)
         *                      select table;
         *      bool tokenAvailable = false;
         *
         *      foreach (TokenManagement token in userToken)
         *      {
         *          if (token.AspNetUserId == System.Web.HttpContext.Current.User.Identity.GetUserId())
         *          {
         *              tokenAvailable = true;
         *              token.DateChanged = DateTime.UtcNow;
         *              token.Token = accessToken.Token;
         *              token.TokenType = accessToken.TokenType;
         *              token.ExpiresIn = accessToken.ExpiresIn;
         *              token.RefreshToken = accessToken.RefreshToken;
         *          }
         *      }
         *
         *      if (tokenAvailable == false)
         *      {
         *          TokenManagement token = new TokenManagement()
         *          {
         *          AspNetUserId = System.Web.HttpContext.Current.User.Identity.GetUserId(),
         *          DateChanged = DateTime.UtcNow,
         *          Token = accessToken.Token,
         *          TokenType = accessToken.TokenType,
         *          ExpiresIn = accessToken.ExpiresIn,
         *          RefreshToken = accessToken.RefreshToken
         *      };
         *
         *          //Db.TokenManagement.InsertOnSubmit(token);
         *          Db.TokenManagement.Add(token);
         *      }
         *
         *
         *      // 20171022 Pandita: unify with EF
         *      // Db.SubmitChanges();
         *      Db.SaveChanges();
         *  }
         * }
         */
        public ActionResult DirectToSync()
        {
            if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                throw new Exception("You Must be Loged in to sync Fitbit Data");
            }
            //Loading Session data when the user has does not have Key creds in their session
            FitbitAppCredentials appCredentials = new FitbitAppCredentials()
            {
                ClientId     = ConfigurationManager.AppSettings["FitbitClientId"],
                ClientSecret = ConfigurationManager.AppSettings["FitbitClientSecret"]
            };

            Session["AppCredentials"] = appCredentials;

            OAuth2AccessToken accessToken = new OAuth2AccessToken();

            /*
             * // 20161108 Pandita
             * bool fitbitConnected = false;
             *
             * string userId = System.Web.HttpContext.Current.User.Identity.GetUserId(); // Get user ID
             * IEnumerable <TokenManagement> userToken = from a in Db.TokenManagement // Get user token
             *              where a.AspNetUserId.Equals(userId)
             *              select a;
             *
             * // 20170828 Pandita: BUG!! should not retrieve token from DB, instead, should replace the token in DB by the new token
             * // ************************** TO BE REVISED ********************************************************
             * foreach (TokenManagement data in userToken)
             * {
             *  if (data.AspNetUserId == userId && data.ExpiresIn == 28800)
             *  {
             *      fitbitConnected = true;
             *      accessToken.Token = data.Token;
             *      accessToken.TokenType = data.TokenType;
             *      accessToken.ExpiresIn = data.ExpiresIn;
             *      accessToken.RefreshToken = data.RefreshToken;
             *      accessToken.UserId = data.UserId;
             *      accessToken.UtcExpirationDate = data.DateChanged.AddSeconds(data.ExpiresIn);
             *  }
             * }
             *
             * // 20170213 Pandita: Possibly more than one Token stored for a user?
             * // 20170828 Pandita: should renew the token in DB?
             * if (fitbitConnected == true)
             * {
             *  FitbitClient tempSyncClient = GetFitbitClient(accessToken);
             *  accessToken = tempSyncClient.AccessToken;
             *  // 20171026 Pandita: removed
             *  // SyncFitbitCred(accessToken); // 20170213 Pandita: Add token again to DB.TokenManagements?????
             *  //     return View("Callback");
             *  return RedirectToAction("Sync", "UserDatas"); // 20170213 Pandita: Should redirect to UserDatas/Sync() or UserDatas/FitbitDataSync(string UserID) ?????
             * }*/

            return(Authorize()); // If no token is found, direct user to Fitbit authorization page.
        }
예제 #3
0
        /// <summary>
        /// Simplest constructor for OAuth2- requires the minimum information required by FitBit.Net client to make succesful calls to Fitbit Api
        /// </summary>
        /// <param name="credentials">Obtain this information from your developer dashboard. App credentials are required to perform token refresh</param>
        /// <param name="accessToken">Authenticate with Fitbit API using OAuth2. Authenticator2 class is a helper for this process</param>
        /// <param name="interceptor">An interface that enables sniffing all outgoing and incoming http requests from FitbitClient</param>
        public FitbitClient(FitbitAppCredentials credentials, OAuth2AccessToken accessToken, List <IFitbitInterceptor> interceptors, bool enableOAuth2TokenRefresh = true, ITokenManager tokenManager = null)
        {
            this.AppCredentials = credentials;
            this.AccessToken    = accessToken;

            this.FitbitInterceptorPipeline = new List <IFitbitInterceptor>();

            if (interceptors != null && interceptors.Count > 0)
            {
                this.FitbitInterceptorPipeline.AddRange(interceptors);
            }

            ConfigureTokenManager(tokenManager);

            //Auto refresh should always be the last handle to be registered.
            ConfigureAutoRefresh(enableOAuth2TokenRefresh);
            CreateHttpClientForOAuth2();
        }
예제 #4
0
 /// <summary>
 /// HttpClient and hence FitbitClient are designed to be long-lived for the duration of the session. This method ensures only one client is created for the duration of the session.
 /// More info at: http://stackoverflow.com/questions/22560971/what-is-the-overhead-of-creating-a-new-httpclient-per-call-in-a-webapi-client
 /// </summary>
 /// <returns></returns>
 public FitbitClient GetFitbitClient(OAuth2AccessToken accessToken = null)
 {
     if (Session["FitbitClient"] == null)
     {
         if (accessToken != null)
         {
             var          appCredentials = (FitbitAppCredentials)Session["AppCredentials"];
             FitbitClient client         = new FitbitClient(appCredentials, accessToken);
             Session["FitbitClient"] = client;
             return(client);
         }
         else
         {
             throw new Exception("First time requesting a FitbitClient from the session you must pass the AccessToken.");
         }
     }
     else
     {
         return((FitbitClient)Session["FitbitClient"]);
     }
 }
예제 #5
0
        //Final step. Take this authorization information and use it in the app
        public async Task <ActionResult> Callback()
        {
            FitbitAppCredentials appCredentials = (FitbitAppCredentials)Session["AppCredentials"];

            var authenticator = new OAuth2Helper(appCredentials, Request.Url.GetLeftPart(UriPartial.Authority) + "/Fitbit/Callback");

            string code = Request.Params["code"];

            OAuth2AccessToken accessToken = await authenticator.ExchangeAuthCodeForAccessTokenAsync(code);

            /*Console.WriteLine("Zilu-debug");
             * Console.Write(accessToken);
             * Console.WriteLine(accessToken);*/

            //Store credentials in FitbitClient. The client in its default implementation manages the Refresh process
            FitbitClient fitbitClient = GetFitbitClient(accessToken);

            //20171025 Pandita: removed saving tokens
            //SyncFitbitCred(accessToken);

            //return RedirectToAction("Index", "Home");
            return(RedirectToAction("Sync", "UserDatas")); // redirect to UserdatasController.cs/Sync().
        }
예제 #6
0
 public FitbitClient(FitbitAppCredentials credentials, OAuth2AccessToken accessToken, IFitbitInterceptor interceptor, ITokenManager tokenManager) : this(credentials, accessToken, interceptor, true, tokenManager)
 {
 }
예제 #7
0
 public FitbitClient(FitbitAppCredentials credentials, OAuth2AccessToken accessToken, List <IFitbitInterceptor> interceptors, bool enableOAuth2TokenRefresh) : this(credentials, accessToken, interceptors, enableOAuth2TokenRefresh, null)
 {
 }
예제 #8
0
 public FitbitClient(FitbitAppCredentials credentials, OAuth2AccessToken accessToken, bool enableOAuth2TokenRefresh) : this(credentials, accessToken, null, enableOAuth2TokenRefresh)
 {
 }