Ejemplo n.º 1
0
        public string GetAccessToken(WorkContext wc, string code, string returnUrl)
        {
            try
            {
                var part = wc.CurrentSite.As<FacebookSettingsPart>();
                var clientId = part.ClientId;
                var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);

                var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
                var redirectUrl =
                    new Uri(wc.HttpContext.Request.Url,
                            urlHelper.Action("Auth", "FacebookOAuth", new { Area = "RM.QuickLogOn.OAuth" })).ToString();//, returnUrl = returnUrl
                var url = string.Format(TokenRequestUrl, urlHelper.Encode(clientId), urlHelper.Encode(redirectUrl), urlHelper.Encode(clientSecret), urlHelper.Encode(code));
                var wr = WebRequest.Create(url);
                wr.Proxy = OAuthHelper.GetProxy();
                wr.Method = "GET";
                var wres = wr.GetResponse();
                using (var stream = wres.GetResponseStream())
                using (var sr = new StreamReader(stream))
                {
                    var result = HttpUtility.ParseQueryString(sr.ReadToEnd());
                    return result["access_token"];
                }
                }
            catch (Exception ex)
            {
                string error = OAuthHelper.ReadWebExceptionMessage(ex);
                Logger.Error(ex, string.IsNullOrEmpty(error) ? ex.Message : error);
            }
            
            return null;
        }
 /// <summary>
 /// Concerts anonymous object into FlashVars string (like querystring but HTML encoded)
 /// </summary>
 /// <param name="html"></param>
 /// <param name="values"></param>
 /// <returns></returns>
 public static IHtmlString AnonymousToFlashVars(this HtmlHelper html, UrlHelper url, object values) {
     var dict = new RouteValueDictionary(values);
     // HTML and URL encode, glue and convert
     return MvcHtmlString.Create(
         dict.Select(kv => 
             html.Encode(url.Encode(kv.Key)) + "=" + html.Encode(url.Encode(kv.Value.ToString())))
             .Glue("&amp;"));
 }
Ejemplo n.º 3
0
 public string GetLogOnUrl(WorkContext context)
 {
     var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
     var part = context.CurrentSite.As<FacebookSettingsPart>();
     var clientId = part.ClientId;
     var returnUrl = context.HttpContext.Request.Url;
     var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "FacebookOAuth", new { Area = "RM.QuickLogOn.OAuth" })).ToString();//, returnUrl = returnUrl
     return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), urlHelper.Encode(returnUrl.ToString()));
 }
 public string GetLogOnUrl(WorkContext context)
 {
     var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
     var part = context.CurrentSite.As<RenrenSettingsPart>();
     var clientId = part.ClientId;
     var additional = part.Additional;
     //用于第三方应用防止CSRF攻击,成功授权后回调时会原样带回。请务必严格按照流程检查用户与state参数状态的绑定.
     var returnUrl = context.HttpContext.Request.Url;
     var state = urlHelper.Encode(returnUrl.ToString());
     var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "RenrenOAuth", new { Area = "Cabbage.OAuth" })).ToString();
     return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), state, (string.IsNullOrWhiteSpace(additional) ? "" : ("&" + additional)));
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Initial Index
        /// </summary>
        /// <returns>Index view</returns>
        public ActionResult Index()
        {
            if (User.IsInRole("Instructor") || User.IsInRole("Administrator"))
            {
                return this.View();
            }
            else
            {
                User user = this.db.Query<User>().Where(u => u.EmailAddress == User.Identity.Name).FirstOrDefault();
                if (user == null)
                {
                    UrlHelper helper = new UrlHelper();
                    return this.Redirect("/Home/Error?Message=" + helper.Encode("User " + User.Identity.Name + " does not exist"));
                }

                DateTime start = DateTime.Now.AddHours(1);
                List<Classroom> runningClassrooms = this.db.Query<Classroom>().Include(c => c.Course).Where(c => c.Start < start).ToList();
                runningClassrooms = runningClassrooms.Where(c => c.Start.AddDays(c.Course.Days).AddHours(c.Course.Hours + 1) > DateTime.Now).ToList();
                List<int> runningClassroomIds = runningClassrooms.Select(c => c.ClassroomId).ToList();
                List<Seat> seats = this.db.Query<Seat>().Where(s => s.UserId == user.UserId && runningClassroomIds.Contains(s.ClassroomId)).ToList();
                if (seats.Count == 0)
                {
                    UrlHelper helper = new UrlHelper();
                    return this.Redirect("/Home/Error?Message=" + helper.Encode("Running Classrooms: " + runningClassrooms.Count + "<br/>"
                                                                            + "Classroom IDs :" + runningClassroomIds.ToString() + "<br/>"
                                                                            + "User Id :" + user.UserId));
                }

                return this.RedirectToAction("Connect", new { id = seats[0].SeatId });
            }
        }
Ejemplo n.º 6
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            // No checking of password for this sample.  Just care about the username
            // as that's what we're including in the token to send back to the authorization server

            // Corresponds to shared secret the authorization server knows about for this resource
            const string encryptionKey = "WebAPIsAreAwesome";

            // Build token with info the authorization server needs to know
            var tokenContent = model.UserName + ";" + DateTime.Now.ToString(CultureInfo.InvariantCulture) + ";" + model.RememberMe;
            var encryptedToken = EncodingUtility.Encode(tokenContent, encryptionKey);

            // Redirect back to the authorization server, including the authentication token
            // Name of authentication token corresponds to that known by the authorization server
            returnUrl += (returnUrl.Contains("?") ? "&" : "?");
            returnUrl += "resource-authentication-token=" + encryptedToken;
            var url = new Uri(returnUrl);
            var redirectUrl = url.ToString();

            // URL Encode the values of the querystring parameters
            if (url.Query.Length > 1)
            {
                var helper = new UrlHelper(HttpContext.Request.RequestContext);
                var qsParts = HttpUtility.ParseQueryString(url.Query);
                redirectUrl = url.GetLeftPart(UriPartial.Path) + "?" + String.Join("&",qsParts.AllKeys.Select(x => x + "=" + helper.Encode(qsParts[x])));
            }

            return Redirect(redirectUrl);
        }
Ejemplo n.º 7
0
 public static string GetGoogleLogOnUrl(this HtmlHelper htmlHelper, WorkContext workContext)
 {
     var urlHelper = new UrlHelper(workContext.HttpContext.Request.RequestContext);
     var part = workContext.CurrentSite.As<GoogleSettingsPart>();
     var clientId = part.ClientId;
     var returnUrl = workContext.HttpContext.Request.Url;
     var redirectUrl = new Uri(
         returnUrl,
         urlHelper.Action("GoogleAuth", "Account", new {area = "Teeyoot.Account"})
         ).ToString();
     return string.Format(
         GoogleUrl,
         clientId,
         urlHelper.Encode(redirectUrl),
         urlHelper.Encode(Scope),
         urlHelper.Encode(returnUrl.ToString()));
 }
Ejemplo n.º 8
0
 public string GetLogOnUrl(WorkContext context)
 {
     var urlHelper = new UrlHelper(context.HttpContext.Request.RequestContext);
     var part = context.CurrentSite.As<LinkedInSettingsPart>();
     var clientId = part.ClientId;
     var returnUrl = context.HttpContext.Request.Url;
     var redirectUrl = new Uri(returnUrl, urlHelper.Action("Auth", "LinkedInOAuth", new { Area = "RM.QuickLogOn.OAuth", ReturnUrl = returnUrl })).ToString();//
     var state = Guid.NewGuid().ToString().Trim('{', '}');
     return string.Format(Url, clientId, urlHelper.Encode(redirectUrl), state);
 }
        private DoubanAccessTokenJsonModel GetAccessToken(WorkContext wc, string code)
        {
            try
            {
                var part = wc.CurrentSite.As<DoubanSettingsPart>();
                var clientId = part.ClientId;
                var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);

                var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
                var redirectUrl =
                    new Uri(wc.HttpContext.Request.Url,
                            urlHelper.Action("Auth", "DoubanOAuth", new { Area = "Cabbage.OAuth" })).ToString();

                var encodeUrl = urlHelper.Encode(redirectUrl);

                var wr = WebRequest.Create(string.Format(TokenRequestUrl, clientId, clientSecret, code, encodeUrl));
                wr.Proxy = OAuthHelper.GetProxy();
                wr.ContentType = "application/x-www-form-urlencoded";
                wr.Method = "POST";
                using (var stream = wr.GetRequestStream())
                using (var ws = new StreamWriter(stream, Encoding.UTF8))
                {
                    //此段参数为保险起见,加入的,实际上只需要URL拼接即可
                    ws.Write("client_id={0}&", clientId);
                    ws.Write("client_secret={0}&", clientSecret);
                    ws.Write("grant_type=authorization_code&");
                    ws.Write("code={0}&", code);
                    ws.Write("redirect_uri={0}", encodeUrl);

                }
                var wres = wr.GetResponse();
                using (var stream = wres.GetResponseStream())
                {
                    return OAuthHelper.FromJson<DoubanAccessTokenJsonModel>(stream);
                }
            }
            catch (WebException ex)
            {
                var webResponse = ex.Response as HttpWebResponse;
                using (var stream = webResponse.GetResponseStream())
                using (var sr = new StreamReader(stream))
                {
                    var error = sr.ReadToEnd();
                    Logger.Error(ex, error);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, ex.Message);
            }

            return null;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Get only the url to retrieve the gravatar image
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="email"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public static string GravatarUrl(this HtmlHelper helper, string email, int size)
        {
            if (email == null)
            email = string.Empty;

             UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
             string defaultAvatar = helper.ViewContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority).Contains("localhost") ? "wavatar" : urlHelper.Encode(WebHelper.GetSiteRoot() + "/Resources/img/gravatar-default.png");

             return string.Concat("http://gravatar.com/avatar/",
                              email.ToLowerInvariant().EncryptToMD5(),
                              ".jpg?s=", size, "&amp;d=", defaultAvatar);
        }
Ejemplo n.º 11
0
        private string GetAccessToken(WorkContext wc, string code, string returnUrl)
        {
            try
            {
                var part = wc.CurrentSite.As<LinkedInSettingsPart>();
                var clientId = part.ClientId;
                var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);

                var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
                var redirectUrl =
                    new Uri(wc.HttpContext.Request.Url,
                            urlHelper.Action("Auth", "LinkedInOAuth", new { Area = "RM.QuickLogOn.OAuth", ReturnUrl = returnUrl })).ToString(); //

                var url = string.Format(TokenRequestUrl,
                                        urlHelper.Encode(clientId),
                                        urlHelper.Encode(redirectUrl),
                                        urlHelper.Encode(clientSecret),
                                        urlHelper.Encode(code));

                var wr = WebRequest.Create(url);
                wr.Method = "POST";
                wr.Proxy = OAuthHelper.GetProxy();

                //if (ServicePointManager.ServerCertificateValidationCallback == null) ServicePointManager.ServerCertificateValidationCallback = ((sender, cert, chain, errors) => true);

                var wres = wr.GetResponse();
                using (var stream = wres.GetResponseStream())
                {
                    var result = OAuthHelper.FromJson<LinkedInAccessTokenJsonModel>(stream);
                    return result.access_token;
                }
            }
            catch (Exception ex)
            {
                string error = OAuthHelper.ReadWebExceptionMessage(ex);
                Logger.Error(ex, error ?? ex.Message);
            }
            return null;
        }
Ejemplo n.º 12
0
 public override string ToString()
 {
     var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
     var result = new StringBuilder();
     if (base.AllKeys.Any())
         result.Append("?");
     foreach (var key in base.AllKeys)
     {
         string[] values = base.GetValues(key);
         if (values != null && values.Count() > 0)
             result.Append(key + "=" + url.Encode(values[0]) + "&");
     }
     string resultString = result.ToString();
     return resultString.EndsWith("&") ? resultString.Substring(0, resultString.Length - 1) : resultString;
 }
Ejemplo n.º 13
0
        private string GetAccessToken(WorkContext wc, string code)
        {
            try
            {
                var part = wc.CurrentSite.As<QQSettingsPart>();
                clientId = part.ClientId;
                clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);

                var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
                var redirectUrl =
                    new Uri(wc.HttpContext.Request.Url,
                            urlHelper.Action("Auth", "QQOAuth", new { Area = "Cabbage.OAuth" })).ToString();

                var wr = WebRequest.Create(string.Format(TokenRequestUrl, clientId, clientSecret, code, urlHelper.Encode(redirectUrl)));
                wr.Proxy = OAuthHelper.GetProxy();
                wr.ContentType = "application/x-www-form-urlencoded";
                wr.Method = "GET";
                var wres = wr.GetResponse();
                using (var stream = wres.GetResponseStream())
                using (var sr = new StreamReader(stream))
                {
                    var result = HttpUtility.ParseQueryString(sr.ReadToEnd());
                    return result["access_token"];
                }
            }
            catch (WebException ex)
            {
                var webResponse = ex.Response as HttpWebResponse;
                using (var stream = webResponse.GetResponseStream())
                using (var sr = new StreamReader(stream))
                {
                    var error = sr.ReadToEnd();
                    Logger.Error(ex, error);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex, ex.Message);
            }

            return null;
        }
Ejemplo n.º 14
0
        public static MvcHtmlString ImageLink(this HtmlHelper helper, string actionName, 
            string imageUrl, string alternateText, object routeValues, 
            object linkHtmlAttributes, object imageHtmlAttributes)
        {
            //  Create an instance of the url helper class
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            //  Set up variables for the parameters to be passed to the various methods
            //  of the helper to construct the html.
            //  Use the Action method to generate the correct Url
            var url = urlHelper.Action(actionName, routeValues);
            //  Add any attributes to the RouteValueDictionary
            var linkAttributes = new RouteValueDictionary(linkHtmlAttributes);
            //  Use the Content method to generate the url fot eh image (not an action url)
            var imgUrl = urlHelper.Content(imageUrl);
            //  Use the Encode method to ensure any text is property encoded, to stop scripting attacks
            var imgAltText = urlHelper.Encode(alternateText);
            var imgAttributes = new RouteValueDictionary(imageHtmlAttributes);

            //  Create the Anchor tag to hold the href.
            var linkTagbuilder = new TagBuilder("a");
            //  Add the href attribute
            linkTagbuilder.MergeAttribute("href", url);
            //  Add any attributes passed into method.
            linkTagbuilder.MergeAttributes(linkAttributes);

            //  Create the img tag to contain the image
            var imageTagBuilder = new TagBuilder("img");
            //  Add the alt and src attributes
            imageTagBuilder.MergeAttribute("alt", imgAltText);
            imageTagBuilder.MergeAttribute("src", imgUrl);
            //  Add any additional attributes passed into the method.
            imageTagBuilder.MergeAttributes(imgAttributes);

            //  Add the img tag inside the Anchor tag.
            linkTagbuilder.InnerHtml = imageTagBuilder.ToString(TagRenderMode.SelfClosing);

            //  Wrap the html in an MvcHtmlString and return.
            //  If we use the TagRenderMode.SelfClosing for this operation, it wipes out
            //  the innerHtml.
            return new MvcHtmlString(linkTagbuilder.ToString());
        }
        /// <summary>
        /// Checks that the user is authenticated, and setsup the user. If User Setup fails, redirects to Activation page. 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controller = (AuthenticatedController) filterContext.Controller;

            if (!(controller is HIGController) && controller.OrgUser != null 
                && ((controller.OrgUser.LatestHig != null && controller.OrgUser.LatestHig.CaptureDate.Date < DateTime.Today) 
                     || controller.OrgUser.LatestHig == null   
                     )
                
                )
            {
                var originalurl = filterContext.HttpContext.Request.Url.AbsolutePath;
                var helper = new UrlHelper(filterContext.RequestContext);

                var redirect = (originalurl == "/" ? "" : helper.Encode(originalurl)); 
                filterContext.Result = String.IsNullOrEmpty(redirect) ? new RedirectResult("/HIG/HowsItGoing") : new RedirectResult(String.Format("/HIG/HowsItGoing?wctx={0}", redirect));

                
            }
        }
        public static string ImageLink(this HtmlHelper helper, string actionName, string imageUrl, string alternateText, object routeValues, object linkHtmlAttributes, object imageHtmlAttributes)
        {
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
            var url = urlHelper.Action(actionName, routeValues);

            // Create link
            var linkTagBuilder = new TagBuilder("a");
            linkTagBuilder.MergeAttribute("href", url);
            linkTagBuilder.MergeAttributes(new RouteValueDictionary(linkHtmlAttributes));

            // Create image
            var imageTagBuilder = new TagBuilder("img");
            imageTagBuilder.MergeAttribute("src", urlHelper.Content(imageUrl));
            imageTagBuilder.MergeAttribute("alt", urlHelper.Encode(alternateText));
            imageTagBuilder.MergeAttributes(new RouteValueDictionary(imageHtmlAttributes));

            // Add image to link
            linkTagBuilder.InnerHtml = imageTagBuilder.ToString(TagRenderMode.SelfClosing);

            return linkTagBuilder.ToString();
        }
        private static HtmlString MicrosoftAudioResourcePlayer(UrlHelper url, int width, int height, Resource resource, string resourceHandler, bool preview)
        {
            if (preview)
            {
                return new HtmlString(String.Format("<img src=\"{0}\" width=\"{1}\" height=\"{2}\" alt=\"{3}\" title=\"{3}\" class=\"Resource Preview\"/>",
                    url.Content("~/Content/images/audio.png"), width, height, resource.OriginalFileName));
            }

            string format = "<div class=\"Resource MusicViewer\">" +
                                "<object id=\"mediaplayer\" classid=\"clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701\" standby=\"loading microsoft windows media player components...\" type=\"application/x-oleobject\" width=\"320\" height=\"100\">" +
                                     "<param name=\"filename\" value=\"{0}\" />" +
                                     "<param name=\"animationatstart\" value=\"true\" />" +
                                     "<param name=\"transparentatstart\" value=\"true\" />" +
                                     "<param name=\"autostart\" value=\"true\" />" +
                                     "<param name=\"showcontrols\" value=\"true\" />" +
                                     "<param name=\"showStatusBar\" value=\"true\" />" +
                                     "<param name=\"windowlessvideo\" value=\"true\" />" +
                                     "<param name=\"wmode\" value=\"transparent\" />" +
                                     "<embed src=\"{0}\" autostart=\"true\" showcontrols=\"true\" showstatusbar=\"1\" bgcolor=\"white\" width=\"320\" height=\"100\" wmode=\"transparent\" />" +
                                "</object>" +
                           "</div>";
            return new HtmlString(string.Format(format, url.Encode(GetResourceUrl(resource, resourceHandler))));
        }
        private static HtmlString AudioResourcePlayer(UrlHelper url, int width, int height, Resource resource, string resourceHandler, bool preview)
        {
            if (preview)
            {
                return new HtmlString(String.Format("<img src=\"{0}\" width=\"{1}\" height=\"{2}\" alt=\"{3}\" title=\"{3}\" class=\"Resource Preview\"/>",
                    url.Content("~/Content/images/audio.png"), width, height, resource.OriginalFileName));
            }

            string format = "<div class=\"Resource MusicViewer\">" +
                                "<object data=\"{0}\" width=\"250\" height=\"65\" name=\"dewplayer\" id=\"dewplayer\" type=\"application/x-shockwave-flash\">" +
                                    "<param name=\"movie\" value=\"{0}\" />" +
                                    "<param name=\"flashvars\" value=\"mp3={1}\" />" +
                                    "<param name=\"wmode\" value=\"transparent\" />" +
                                "</object>" +
                            "</div>";
            return new HtmlString(string.Format(format, url.Content("~/Content/swf/dewplayer-bubble.swf"), url.Encode(GetResourceUrl(resource, resourceHandler))));
        }
Ejemplo n.º 19
0
        public string GetAccessTokenUrl(WorkContext wc, string code, string error, string returnUrl)
        {
            var part = wc.CurrentSite.As<FacebookSettingsPart>();
            var clientId = part.ClientId;
            var clientSecret = _oauthHelper.Decrypt(part.Record.EncryptedClientSecret);

            var urlHelper = new UrlHelper(wc.HttpContext.Request.RequestContext);
            var redirectUrl =
                new Uri(wc.HttpContext.Request.Url,
                        urlHelper.Action("Auth", "FacebookOAuth", new { Area = "RM.QuickLogOn.OAuth", returnUrl = returnUrl })).ToString();
            return string.Format(TokenRequestUrl, clientId, urlHelper.Encode(redirectUrl), clientSecret, code);
        }