示例#1
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ILocalizedTextService textService = ApplicationContext.Services.TextService;

            // Get the state from the query string
            string state = Request.QueryString["state"];

            // Check whether the state is present
            if (string.IsNullOrWhiteSpace(state))
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "noAccess" });
                return;
            }

            // Get the session value

            // Has the session expire?
            if (!(Session["PieMan_" + state] is string session))
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "sorrySessionExpired" });
                return;
            }

            // Get the refresh token from the query string (kinda bad practice though)
            string refreshToken = Request.QueryString["token"];

            // Do we have a refresh token?
            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "somethingWentWrong" });
                return;
            }

            // Initalize a new instance of the GoogleService class
            GoogleService service = GoogleService.CreateFromRefreshToken(Config.ClientIdFromPropertyEditor, Config.ClientSecretFromPropertyEditor, refreshToken);

            try
            {
                //Get the authenticated user
                GoogleUserInfo user = service.GetUserInfo().Body;

                //Set the refresh token in our config
                Config.RefreshTokenFromPropertyEditor = refreshToken;

                //Ouput some info about the user
                _content.Text  = "Hi there " + user.Name + ". We have saved your information to a config file, so Umbraco can pull stats from your Google Analytics account.";
                _content.Text += "<br /><br />Close this window and go grab a piping hot serve of stats - you'll need to reopen the settings panel and select an account and profile.";
            }
            catch
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "somethingWentWrong" });
            }

            // Clear the session state
            Session.Remove("PieMan_" + state);
        }
示例#2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get the state from the query string
            string state = Request.QueryString["state"];

            // Check whether the state is present
            if (String.IsNullOrWhiteSpace(state))
            {
                //Ouput an error message
                Content.Text += "No state specified.";
                return;
            }

            // Get the session value
            string session = Session["Analytics_" + state] as string;

            // Has the session expire?
            if (session == null)
            {
                //Ouput an error message
                Content.Text += "Sorry - your session has most likely expired.";
                return;
            }

            // Get the refresh token from the query string (kinda bad practice though)
            string refreshToken = Request.QueryString["token"];

            // Do we have a refresh token?
            if (String.IsNullOrWhiteSpace(refreshToken))
            {
                //Ouput an error message
                Content.Text += "Okay. Something went wrong.";
                return;
            }

            // Initalize a new instance of the GoogleService class
            GoogleService service = GoogleService.CreateFromRequestToken(AnalyticsConfig.ClientId, AnalyticsConfig.ClientSecret, refreshToken);

            try {
                //Get the authenticated user
                GoogleUserInfo user = service.GetUserInfo();

                //Set the refresh token in our config
                AnalyticsConfig.RefreshToken = refreshToken;

                //Ouput some info about the user
                Content.Text = "Hi there " + user.Name + ". We have saved your information to a config file, so Umbraco can pull stats from your Analytics account.";
            }
            catch
            {
                //Ouput an error message
                Content.Text += "Okay. Something went wrong.";
            }

            // Clear the session state
            Session.Remove("Analytics_" + state);
        }
示例#3
0
        /// <summary>
        /// Tries to login with Google Auth
        /// </summary>
        public void Login()
        {
            string            code    = Request.QueryString["code"];
            string            error   = Request.QueryString["error"];
            string            baseUrl = System.Configuration.ConfigurationManager.AppSettings["baseUrl"];
            GoogleOAuthClient oauth   = new GoogleOAuthClient
            {
                ClientId     = "clientId",
                ClientSecret = "clientSecret",
                RedirectUri  = baseUrl + "/umbraco/surface/auth/login"
            };

            // Handle if an error occurs during the Google authentication (eg. if the user cancels the login)
            if (!String.IsNullOrWhiteSpace(error))
            {
                return;
            }
            // Handle the state when the user is redirected back to our page after a successful login with the Google API
            if (!String.IsNullOrWhiteSpace(code))
            {
                MemberServiceController memberService = new MemberServiceController();
                // Exchange the authorization code for an access token
                GoogleAccessTokenResponse response = oauth.GetAccessTokenFromAuthorizationCode(code);
                string accessToken = response.AccessToken;
                // Initialize a new instance of the GoogleService class so we can make calls to the API
                GoogleService service = GoogleService.CreateFromAccessToken(accessToken);

                // Make a call to the API to get information about the authenticated user
                GoogleUserInfo user = service.GetUserInfo();

                //Checks whether the user is logging in with a emakina account
                if (memberService.CreateNewMember(user.GivenName, user.FamilyName, user.Email, user.Id, user.Picture))
                {
                    FormsAuthentication.SetAuthCookie("google_" + user.Id, false);
                    Response.Redirect("/");
                }
                else
                {
                    return;
                }
            }
            else
            {
                string redirect = (Request.QueryString["redirect"] ?? "/");
                // Set the state (a unique/random value)
                string state = Guid.NewGuid().ToString();
                Session["Google_" + state] = redirect;
                // Construct the authorization URL
                string authorizationUrl = oauth.GetAuthorizationUrl(state, GoogleScopes.Email + GoogleScopes.Profile, GoogleAccessType.Online, GoogleApprovalPrompt.Force);
                // Redirect the user to the OAuth dialog
                Response.Redirect(authorizationUrl);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Title = "Google OAuth";

            Callback         = Request.QueryString["callback"];
            ContentTypeAlias = Request.QueryString["contentTypeAlias"];
            PropertyAlias    = Request.QueryString["propertyAlias"];
            Feature          = Request.QueryString["feature"];

            if (AuthState != null)
            {
                NameValueCollection stateValue = Session["Skybrud.Social_" + AuthState] as NameValueCollection;
                if (stateValue != null)
                {
                    Callback         = stateValue["Callback"];
                    ContentTypeAlias = stateValue["ContentTypeAlias"];
                    PropertyAlias    = stateValue["PropertyAlias"];
                    Feature          = stateValue["Feature"];
                }
            }

            // Get the prevalue options
            GoogleOAuthPreValueOptions options = GoogleOAuthPreValueOptions.Get(ContentTypeAlias, PropertyAlias);

            if (!options.IsValid)
            {
                Content.Text += "Hold on now! The options of the underlying prevalue editor isn't valid.";
                return;
            }

            // Configure the OAuth client based on the options of the prevalue options
            GoogleOAuthClient client = new GoogleOAuthClient {
                ClientId     = options.ClientId,
                ClientSecret = options.ClientSecret,
                RedirectUri  = options.RedirectUri
            };

            // Session expired?
            if (AuthState != null && Session["Skybrud.Social_" + AuthState] == null)
            {
                Content.Text = "<div class=\"error\">Session expired?</div>";
                return;
            }

            // Check whether an error response was received from Google
            if (AuthError != null)
            {
                Content.Text = "<div class=\"error\">Error: " + AuthErrorDescription + "</div>";
                if (AuthState != null)
                {
                    Session.Remove("Skybrud.Social:" + AuthState);
                }
                return;
            }

            string state;

            // Redirect the user to the Google login dialog
            if (AuthCode == null)
            {
                // Generate a new unique/random state
                state = Guid.NewGuid().ToString();

                // Save the state in the current user session
                Session["Skybrud.Social_" + state] = new NameValueCollection {
                    { "Callback", Callback },
                    { "ContentTypeAlias", ContentTypeAlias },
                    { "PropertyAlias", PropertyAlias },
                    { "Feature", Feature }
                };

                // Declare the scope
                GoogleScopeCollection defaultScope = new[] {
                    GoogleScope.OpenId,
                    GoogleScope.Email,
                    GoogleScope.Profile
                };

                string scope = options.Scope != null?string.Join(" ", options.Scope) : defaultScope.ToString();

                // Construct the authorization URL
                string url = client.GetAuthorizationUrl(state, scope, GoogleAccessType.Offline, GoogleApprovalPrompt.Force);

                // Redirect the user
                Response.Redirect(url);
                return;
            }

            GoogleAccessTokenResponse info;

            try {
                info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
            } catch (Exception ex) {
                Content.Text = "<div class=\"error\"><b>Unable to acquire access token</b><br />" + ex.Message + "</div>";
                return;
            }

            try {
                // Initialize the Google service
                GoogleService service = GoogleService.CreateFromRefreshToken(client.ClientIdFull, client.ClientSecret, info.RefreshToken);

                // Get information about the authenticated user
                GoogleUserInfo user = service.GetUserInfo();

                Content.Text += "<p>Hi <strong>" + user.Name + "</strong></p>";
                Content.Text += "<p>Please wait while you're being redirected...</p>";

                // Set the callback data
                GoogleOAuthData data = new GoogleOAuthData {
                    Id           = user.Id,
                    Name         = user.Name,
                    Avatar       = user.Picture,
                    ClientId     = client.ClientIdFull,
                    ClientSecret = client.ClientSecret,
                    RefreshToken = info.RefreshToken
                };

                // Update the UI and close the popup window
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "callback", String.Format(
                                                                "self.opener." + Callback + "({0}); window.close();",
                                                                data.Serialize()
                                                                ), true);
            } catch (Exception ex) {
                Content.Text = "<div class=\"error\"><b>Unable to get user information</b><br />" + ex.Message + "</div>";
                return;
            }
        }
示例#5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Get current user
            var currentUser = UmbracoContext.Current.Security.CurrentUser;

            //Check a user is logged into backoffice
            if (currentUser == null)
            {
                //Ouput an error message
                Content.Text += ui.Text("analytics", "noAccess");
                return;
            }

            //Check the user has access to the analytics section
            //Prevents anyone with this URL to page from just hitting it
            if (!currentUser.AllowedSections.Contains("analytics"))
            {
                //Ouput an error message
                Content.Text += ui.Text("analytics", "noAccess");
                return;
            }

            // Get the state from the query string
            string state = Request.QueryString["state"];

            // Check whether the state is present
            if (String.IsNullOrWhiteSpace(state))
            {
                //Ouput an error message
                Content.Text += ui.Text("analytics", "noStateSpecified");
                return;
            }

            // Get the session value
            string session = Session["Analytics_" + state] as string;

            // Has the session expire?
            if (session == null)
            {
                //Ouput an error message
                Content.Text += ui.Text("analytics", "sorrySessionExpired");
                return;
            }

            // Get the refresh token from the query string (kinda bad practice though)
            string refreshToken = Request.QueryString["token"];

            // Do we have a refresh token?
            if (String.IsNullOrWhiteSpace(refreshToken))
            {
                //Ouput an error message
                Content.Text += ui.Text("analytics", "somethingWentWrong");
                return;
            }

            // Initalize a new instance of the GoogleService class
            GoogleService service = GoogleService.CreateFromRefreshToken(AnalyticsConfig.ClientId, AnalyticsConfig.ClientSecret, refreshToken);

            try {
                //Get the authenticated user
                GoogleUserInfo user = service.GetUserInfo();

                //Set the refresh token in our config
                AnalyticsConfig.RefreshToken = refreshToken;


                //Ouput some info about the user
                //Using UmbracoUser (obsolete) - somehow it fails to compile when using Security.CurrentUser
                //ui.text requires OLD BusinessLogic User object type not shiny new one
                //Can we use another helper/library to get the translation text?
                var umbUser = new User(currentUser.Id);
                Content.Text = ui.Text("analytics", "informationSavedMessage", user.Name, umbUser);
            }
            catch
            {
                //Ouput an error message
                Content.Text += ui.Text("analytics", "somethingWentWrong");
            }

            // Clear the session state
            Session.Remove("Analytics_" + state);
        }