Пример #1
0
        public ActionResult Callback(string oauth_token, string oauth_verifier)
        {
            //this just makes sure if we hit this url without the token, verifier or having a current request token we return an error
            if (oauth_token.IsNullOrWhiteSpace() || oauth_verifier.IsNullOrWhiteSpace() || Session[RequestTokenKeyName] == null || Session[RequestTokenSecretKeyName] == null)
            {
                ViewBag.Error =
                    "Are you sure you meant to come to this URL? You do not have any request tokens. You should start by <a href='./GetRequestToken'>requesting some request token</a>";
                return(View());
            }
            var url = string.Format("{0}AccessToken", TradeMeOAuthApiUrl);

            //still use the base header, but add the token secret to the existing signature "<consumer_key>&" + "<oauth_token_secret>"
            //the Session["RequestTokenSecret"] is the oauth_token_secret and the base header already ends in "&"
            var authHeader = string.Format(
                "{0}{1}, oauth_verifier={2}, oauth_token={3}",
                OauthHelper.GetBaseOAuthHeader(), Session[RequestTokenSecretKeyName], oauth_verifier, Session[RequestTokenKeyName]);

            //make the last request to get our ACCESS tokens, these are permenant and can be used to authorize as the user on the API
            var responseText = OauthHelper.MakeHttpRequest("POST", new Uri(url), authHeader);

            var matches = _oauthAccessTokenRegex.Match(responseText);

            //save our final tokens
            Session[AccessTokenKeyName]       = matches.Groups[1].ToString();
            Session[AccessTokenSecretKeyName] = matches.Groups[2].ToString();
            ViewBag.AccessToken       = Session[AccessTokenKeyName];
            ViewBag.AccessTokenSecret = Session[AccessTokenSecretKeyName];
            return(View());
        }
Пример #2
0
        public async Task <IHttpActionResult> RegisterExternal(RegisterExternalModel model)
        {
            var verifiedAccessToken = new ParsedExternalAccessToken();

            if (ModelState.IsValid)
            {
                var helper = OauthHelper.Create();
                if (!string.IsNullOrEmpty(model.Provider) && !string.IsNullOrEmpty(model.ExternalAccessToken))
                {
                    verifiedAccessToken = await helper.VerifyExternalAccessToken(model.Provider, model.ExternalAccessToken);

                    if (verifiedAccessToken == null)
                    {
                        return(this.JsonError(HttpStatusCode.BadRequest, 10, "Invalid Provider or External Access Token", ModelState));
                    }
                }

                var loginInfo = await SignInManager.AuthenticationManager.GetExternalLoginInfoAsync();

                ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(loginInfo.ExternalIdentity as ClaimsIdentity);

                var registerGeneral = new RegisterGeneralModel()
                {
                    UserName = model.UserName,
                    Email    = model.Email,
                    //FirstName = externalLogin.UserName.Split(' ')[0], //First Name
                    //LastName = externalLogin.UserName.Split(' ').LastOrDefault(), //Last Name
                    ExternalAccessToken = model.ExternalAccessToken,
                    Provider            = model.Provider
                };

                var regResult = await RegisterInternal(registerGeneral);

                if (regResult.HasError)
                {
                    return(JsonError(regResult.HttpStatusCode, regResult.ServerErrorCode, regResult.ErrorMessage, regResult.ModelState));
                }
                else
                {
                    var result = new
                    {
                        userId = regResult.UserId
                    };
                    return(Json(result));
                }
            }
            else
            {
                return(JsonError(HttpStatusCode.BadRequest, 10, "Warning", ModelState));
            }
        }
Пример #3
0
        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MLogoutClick(object sender, EventArgs e)
        {
            var rs = MessageBox.Show("确定注销吗?\r\n注销后将会自动退出,重启程序继续使用。", "注销", MessageBoxButton.OKCancel);

            if (rs == MessageBoxResult.OK)
            {
                OauthHelper.Logout();
                OauthHelper.IsVerified           = false;
                AppSetting.IsScheduledAgent      = false;
                AppSetting.CheckUpdateSecondSpan = 0;

                App.Quit();
            }
        }
Пример #4
0
        public ActionResult MyTradeMeSummary()
        {
            if (Session[AccessTokenKeyName] == null || Session[AccessTokenSecretKeyName] == null)
            {
                ViewBag.Error =
                    "Are you sure you meant to come to this URL? You do not have any access tokens. You should start by <a href='./GetRequestToken'>requesting some request token</a>";
                return(View());
            }
            //now we can just use the base header along with the (access) oauth token and secret
            var authHeader        = string.Format("{0}{1}, oauth_token={2}", OauthHelper.GetBaseOAuthHeader(), Session[AccessTokenSecretKeyName], Session[AccessTokenKeyName]);
            var response          = OauthHelper.MakeHttpRequest("GET", new Uri(MyTradeMeSummaryUrl), authHeader);
            var json              = JsonConvert.DeserializeObject(response);
            var formattedResponse = JsonConvert.SerializeObject(json, Formatting.Indented);

            ViewBag.Response = formattedResponse;
            return(View());
        }
Пример #5
0
        private Uri GetUri(IDictionary <string, object> param)
        {
            if (this.m_method == "GET")
            {
                var ub = new UriBuilder(this.m_url)
                {
                    Query = OauthHelper.ToQuery(param, false)
                };

                ub.Path = OauthHelper.NamedFormat(NamedFormat, param);

                return(ub.Uri);
            }
            else
            {
                return(new Uri(this.m_url));
            }
        }
Пример #6
0
        public ActionResult GetRequestToken()
        {
            //set up the URL we will bhe using to get the request tokens, in this case we want to be able to read and write to the users account
            var url = string.Format("{0}RequestToken?scope=MyTradeMeRead,MyTradeMeWrite", TradeMeOAuthApiUrl);

            var authHeader = OauthHelper.GetBaseOAuthHeader();

            //make the request to get the request tokens and store the result in responseText
            //responseText looks like this:
            //oauth_token=F4B999BE86A4EA64CB82E7F6A1ED151E&oauth_token_secret=13791AEA7D1592067B2AA9F549DA82C8&oauth_callback_confirmed=true
            string responseText;

            try
            {
                responseText = OauthHelper.MakeHttpRequest("POST", new Uri(url), authHeader);
            }
            catch (WebException e)
            {
                ViewBag.ErrorMessage = e.Message;
                var inner      = (WebException)e.InnerException;
                var statusCode = (int)((HttpWebResponse)inner.Response).StatusCode;
                ViewBag.HelpMessage =
                    "Make sure you have entered valid credentials for consumer key and consumer secret";
                ViewBag.StatusCode = statusCode;
                ViewBag.HasError   = true;
                return(View());
            }

            //get the values out using regex
            var matches = _oauthRequestTokenRegex.Match(responseText);

            //store the token and token secret in the session for access later on
            Session[RequestTokenKeyName]       = matches.Groups[1].ToString();
            Session[RequestTokenSecretKeyName] = matches.Groups[2].ToString();

            //set this Url on the viewbag so that the user can click this link when the page loads
            //this URL will send the user back to Trade Me and ask them to log in and give permission to your application if they haven't done so before
            //if they already have given your application permission then they will just need to login
            ViewBag.AuthorizeUrl       = string.Format("https://secure.tmsandbox.co.nz/Oauth/Authorize?oauth_token={0}", Session[RequestTokenKeyName]);
            ViewBag.RequestToken       = Session[RequestTokenKeyName];
            ViewBag.RequestTokenSecret = Session[RequestTokenSecretKeyName];
            return(View());
        }
Пример #7
0
        ///// <summary>
        ///// 手势结束
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void GestureListener_GestureCompleted(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        //{
        //    if (isVerticalDrag || AppSetting.HightDragSensitivity)
        //    {
        //        var scrollviewer = AppSetting.FindChildOfType<ScrollViewer>(FanListBox);
        //        if (scrollviewer == null)
        //        {
        //            return;
        //        }
        //        //到底部
        //        if (Math.Abs(scrollviewer.VerticalOffset - scrollviewer.ScrollableHeight) < 2)
        //        {
        //            GetNextPage();
        //        }
        //        //顶部
        //        else if (scrollviewer.VerticalOffset < 0.000001)
        //        {
        //            GetLastest();
        //        }
        //    }
        //}

        ///// <summary>
        ///// 手势开始
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void GestureListener_GestureBegin(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        //{
        //    while (TouchPanel.IsGestureAvailable)
        //    {
        //        GestureSample gs = TouchPanel.ReadGesture();
        //        if (gs.GestureType == GestureType.VerticalDrag)
        //        {
        //            isVerticalDrag = true;
        //        }
        //    }
        //}

        #endregion 操作事件

        #region 公共方法

        /// <summary>
        /// 初始化控件,首页和提及调用此方法
        /// </summary>
        /// <param name="beforeLoading"></param>
        /// <param name="afterCallback"></param>
        public void Init(Action beforeLoading = null, Action <object> afterCallback = null)
        {
            if (_statusApi == null)
            {
                _statusApi = new Statuses(OauthHelper.OAuth());
            }

            if (IsInited)
            {
                return;
            }

            if (beforeLoading != null)
            {
                BeforeLoadingCallback = beforeLoading;
                beforeLoading();
            }

            if (afterCallback != null)
            {
                AfterLoadedCallback = afterCallback;
            }

            PollType = EPollType.Default;

            IsPolling = true;

            switch (Timeline)
            {
            case ETimeline.Home:
                _statusApi.GetHomeTimeLine(GetTimelineEnd, null, null, null, AppSetting.PageCount, 0, "default");
                break;

            case ETimeline.Reply:
                _statusApi.GetReplies(GetTimelineEnd, null, null, AppSetting.PageCount, 0, "default");
                break;

            case ETimeline.Public:
                _statusApi.GetPublicTimeline(GetTimelineEnd, AppSetting.PageCount, null, null, "default");
                break;
            }
        }
Пример #8
0
        internal virtual WebRequest GetRequest(OAuth oauth)
        {
            var param = this.GetParameters();

            var req = oauth.CreateWebRequest(this.m_method, this.GetUri(param), param);

            if (this.m_method == "POST" && this.m_autoRequest)
            {
                var postData = OauthHelper.ToQuery(param, true);
                var buff     = Encoding.UTF8.GetBytes(postData);

                if (buff.Length > 0)
                {
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.GetRequestStream().Write(buff, 0, buff.Length);
                }
            }

            return(req);
        }
Пример #9
0
 protected virtual T ParseResultString(string data)
 => OauthHelper.ParseJsonObject <T>(data);
Пример #10
0
        /// <summary>
        /// suguo.yao 2016-9-4
        /// 获取当前授权登录的用户信息及用户accesstoken
        /// </summary>
        /// <returns></returns>
        public static RetResult <Userinfo> GetTokenWithUserinfo(string code)
        {
            var url = OauthHelper.GetAccessTokenUrl(Config.ClientId, Config.ClientSecret, code);

            return(CommonJsonSend.Send <RetResult <Userinfo> >(null, url, null, CommonJsonSendType.GET));
        }
Пример #11
0
        /// <summary>
        /// suguo.yao 2016-9-24
        /// 应用授权
        /// </summary>
        /// <returns></returns>
        public static GetTokenResult GetToken(int timeOut = 10000)
        {
            var url = OauthHelper.GetTokenUrl(Config.ClientId, Config.ClientSecret);

            return(CommonJsonSend.Send <GetTokenResult>(null, url, null, CommonJsonSendType.GET, timeOut));       //应用授权同时支持GET和POST
        }