Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Carlos Casalicchio 176 posts 735 karma points
    Apr 14, 2017 @ 14:59
    Carlos Casalicchio
    0

    Implementation Tutorial / Sample

    Great package. I did install it and configure all the Apis (Google, Facebook, Twitter, Instagram) in the backoffice, but am not sure how to implement it in the front-end (login page).

    Are there any tutorials or sample code for this?

  • Anders Bjerner 487 posts 2990 karma points MVP 8x admin c-trib
    Apr 15, 2017 @ 00:37
    Anders Bjerner
    0

    Hi Carlos,

    Are you trying to setup a login in the frontend of your site?

    Skybrud.Social for Umbraco 7 isn't really for handling that use case. The package is for letting developers/editors authenticate in the backoffice so you as a developer have a context for calling the various APIs.

    There are other packages to handle login in the frontend - you can for instance use Skybrud.Social directly. You can read more about this at the following links:

    Facebook: http://social.skybrud.dk/facebook/authentication/user-access-token/ Twitter: https://gist.github.com/abjerner/10997293 (old WebForms example) http://social.skybrud.dk/google/authentication/

    However these examples are for ASP.NET in general.

  • Carlos Casalicchio 176 posts 735 karma points
    Apr 19, 2017 @ 20:13
    Carlos Casalicchio
    0

    Anders,

    Thank you for your response. I did implement it using your example, but now I'm getting this error:

    An active access token must be used to query information about the current user.
    
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
    
    Exception Details: Skybrud.Social.Facebook.Exceptions.FacebookException: An active access token must be used to query information about the current user.
    
    Source Error: 
    
    
    Line 93: 
    Line 94:         // Make a call to the API to get information about the authenticated user (aka "me")
    Line 95:         FacebookUserResponse response = service.Users.GetUser("me");
    Line 96: 
    Line 97: 
    

    How can I fix this?

    The code snippet is:

    ...
    // Remove the state from the session
            Session.Remove("facebook_" + state);
    
            // Exchange the auth code for an access token
            string accessToken = oauth.GetAccessTokenFromAuthCode(code);
    
            // Print out the access token to the user (we really shouldn't do this in a live environment)
            <strong>Access token:</strong> @accessToken
    
            // Initialize a new instance of the FacebookService class so we can make calls to the API
            FacebookService service = FacebookService.CreateFromAccessToken(accessToken);
    
            // Make a call to the API to get information about the authenticated user (aka "me")
            FacebookUserResponse response = service.Users.GetUser("me");
    
    
            if (!string.IsNullOrEmpty(accessToken))
            {
    ...
    

    When I comment out the buggy code, I see that the URL returned from facebook is

    http://localhost:19127/minha-conta/login?code=[long code]&state=86cfc634-489e-4a1e-84f8-23e45a931727#_=_
    

    Does the #_=_ messes it up?

    string accessToken = oauth.GetAccessTokenFromAuthCode(code);
    

    is returning an empty string...

  • Anders Bjerner 487 posts 2990 karma points MVP 8x admin c-trib
    Apr 19, 2017 @ 20:28
    Anders Bjerner
    100

    What version of Skybrud.Social are you using? Facebook has recently deprecated an older version of their API, which affects authentication if you're using an older version of Skybrud.Social.

    Assuming this is the issue you're also experiencing, it should be fixed with the latest release:

    https://github.com/abjerner/Skybrud.Social/releases/tag/v0.9.5

  • Carlos Casalicchio 176 posts 735 karma points
    Apr 19, 2017 @ 20:53
    Carlos Casalicchio
    0

    That is probably why. I was using version 0.9.4.8

    I'll update it and let you know if that was the issue.

    Thanks!

  • Carlos Casalicchio 176 posts 735 karma points
    Apr 20, 2017 @ 22:45
    Carlos Casalicchio
    0

    Anders,

    After updating the dll it worked. I have implemented Facebook, Google, and Twitter. Now I'm looking into implementing Instagram.

    Do you have a code sample anywhere that I can follow? (twitter was different from google and facebook)

  • Anders Bjerner 487 posts 2990 karma points MVP 8x admin c-trib
    Apr 21, 2017 @ 14:15
    Anders Bjerner
    0

    Instagram uses the same version of OAuth as Google and Facebook, so it should be be very similar. Other you can have a look at the Instagram dialog in my Umbraco package:

    https://github.com/abjerner/Skybrud.Social.Umbraco/blob/master/src/Skybrud.Social.Umbraco/App_Plugins/Skybrud.Social/Dialogs/InstagramOAuth.aspx.cs

    Twitter uses another version of OAuth, which is why that is different.

  • neel 9 posts 79 karma points
    Oct 23, 2018 @ 13:18
    neel
    0

    Are there any tutorials or sample code for this?

  • Carlos Casalicchio 176 posts 735 karma points
    Oct 23, 2018 @ 13:53
    Carlos Casalicchio
    0

    Here's the code of how I got it to work. I don't claim to be the best way of implementing it, but it fit my scenario.

    Please pardon the Portuguese text..

    Controller [MemberLoginSurfaceController]

    using RevistaUFO.Helpers;
    using RevistaUFO.Models;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;
    using umbraco.cms.businesslogic.web;
    using Umbraco.Core.Models;
    using Umbraco.Core.Services;
    using Umbraco.Web;
    using Umbraco.Web.Models;
    using Umbraco.Web.Security;
    
    namespace RevistaUFO.Controllers
    {
        /// <summary>
        /// Summary description for MemberLoginSurfaceController
        /// </summary>
        public class MemberLoginSurfaceController : Umbraco.Web.Mvc.SurfaceController
        {
            private readonly UmbracoHelper umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
            private readonly Smtp email;
            private readonly string _adminEmail = "[email protected]";
            private readonly IPublishedContent home;
            private static readonly Regex _regex = new Regex("[^a-zA-Z0-9]");
    
            public MemberLoginSurfaceController()
            {
                home = umbracoHelper.TypedContentAtRoot().First();
                _adminEmail = home.GetPropertyValue<string>("from");
                email = new Smtp();
            }
            // The MemberLogout Action signs out the user and redirects to the site home page:
    
            [HttpGet]
            public ActionResult MemberLogout()
            {
                Session.Clear();
                FormsAuthentication.SignOut();
                return Redirect("/");
            }
    
            // The MemberLoginPost Action checks the entered credentials using the standard Asp Net membership provider and redirects the user to the same page. Either as logged in, or with a message set in the TempData dictionary:
    
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            [ActionName("MemberLogin")]
            public ActionResult MemberLoginPost(MemberLoginModel model, string returnUrl = "/")
            {
                var cMember = Services.MemberService.GetByUsername(model.Username);
                if (cMember.IsApproved)
                {
                    if (Membership.ValidateUser(model.Username, model.Password))
                    {
                        FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        TempData["Status"] = "Usuário ou senha inválida";
                        return CurrentUmbracoPage();
                    }
                }
                TempData["Status"] = "Conta ainda não aprovada, verifique seu inbox";
                return CurrentUmbracoPage();
            }
    
            private string GeneratePassword()
            {
                // Generate a password which we'll email the member
                var password = Membership.GeneratePassword(10, 1);
                return _regex.Replace(password, "9");
            }
            // http://fee-dev.org/Umbraco/Api/UserAPI/[email protected]
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            [ActionName("PasswordReset")]
            public ActionResult ResetPasswordForMember(string email)
            {
                var cMember = Services.MemberService.GetByEmail(email);
    
                if (cMember != null)
                {
                    // Found the user
                    var password = GeneratePassword();
    
                    // Change the password to the new generated one above
                    Services.MemberService.SavePassword(cMember, password);
                    // Save the password/member
    
                    dynamic message = new
                    {
                        NewPassword = password,
                        cMember.Email,
                        cMember.Name,
                        Subject = "Redefinir Senha"
    
                    };
                    if (SendUserEmail(message))
                        TempData["Status"] = "Nova senha enviada para " + cMember.Email;
                    else TempData["Status"] = "Erro ao enviar senha, tente mais tarde ";
    
                    return Redirect("/minha-conta/redefinirsenha/");
                }
                TempData["Status"] = "Erro ao redefinir senha, tente mais tarde ";
                return RedirectToCurrentUmbracoPage();
            }
    
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            [ActionName("Register")]
            public ActionResult Register(string Email, string Password)
            {
                RegisterModel newMember = Members.CreateRegistrationModel("Member");
                string GUID = Guid.NewGuid().ToString();
    
                newMember.Name = Email;
                newMember.Email = Email;
                newMember.Password = Password;
                newMember.UsernameIsEmail = true;
                newMember.Username = Email;
                newMember.LoginOnSuccess = false;
                UmbracoProperty activation = newMember.MemberProperties.Single(p => p.Alias == "activationCode");
                activation.Value = GUID;
    
                MembershipCreateStatus status = new MembershipCreateStatus();
                MembershipUser member = Members.RegisterMember(newMember, out status);
                Roles.AddUserToRole(newMember.Username, "Registrados");
                member.IsApproved = false;
                Membership.UpdateUser(member);
    
                //signout before activation
                Session.Clear();
                FormsAuthentication.SignOut();
    
                dynamic message = new
                {
                    ValidationUrl = GUID,
                    Email,
                    Name = Email,
                    Subject = "Validar Conta Revista UFO"
    
                };
                if (SendValidationEmail(message))
                    TempData["Status"] = "Validação enviada para " + Email;
                else TempData["Status"] = "Erro ao enviar validação, tente mais tarde ";
    
                return Redirect("/minha-conta/login/");
                TempData["Status"] = "Erro ao criar conta, tente mais tarde ";
                return RedirectToCurrentUmbracoPage();
            }
    
            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            [ActionName("RegisterCustom")]
            public ActionResult RegisterCustom(string Name, string Email, string Password, string groupName, string redirectTo)
            {
                RegisterModel newMember = Members.CreateRegistrationModel("Member");
                string GUID = Guid.NewGuid().ToString();
    
                if (!string.IsNullOrEmpty(Email))
                {
                    newMember.Name = Name;
                    newMember.Email = Email;
                    newMember.Password = Password;
                    newMember.UsernameIsEmail = true;
                    newMember.Username = Email;
                    newMember.LoginOnSuccess = false;
                    UmbracoProperty activation = newMember.MemberProperties.Single(p => p.Alias == "activationCode");
                    activation.Value = GUID;
    
                    MembershipCreateStatus status = new MembershipCreateStatus();
                    MembershipUser member = Members.RegisterMember(newMember, out status);
                    Roles.AddUserToRole(newMember.Username, groupName);
                    member.IsApproved = false;
                    Membership.UpdateUser(member);
    
                    //signout before activation
                    Session.Clear();
                    FormsAuthentication.SignOut();
    
                    dynamic message = new
                    {
                        ValidationUrl = GUID,
                        Email,
                        Name = Email,
                        Subject = "Validar Conta CBPDV"
    
                    };
                    if (SendValidationEmail(message))
                        TempData["Status"] = "Validação enviada para " + Email;
                    else TempData["Status"] = "Erro ao enviar validação, tente mais tarde ";
    
                    return Redirect(redirectTo);
                }
                TempData["Status"] = "Erro ao criar conta, tente mais tarde ";
                return RedirectToCurrentUmbracoPage();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult AddToGroup( string groupName, string redirectTo)
            {
                Roles.AddUserToRole(Membership.GetUser().UserName, groupName);
                return Redirect(redirectTo);
            }
    
            public ActionResult RegisterViaExternal(string Email)
            {
                RegisterModel newMember = Members.CreateRegistrationModel("Member");
    
                if (!string.IsNullOrEmpty(Email))
                {
                    newMember.Name = Email;
                    newMember.Email = Email;
                    newMember.Password = GeneratePassword();
                    newMember.UsernameIsEmail = true;
                    newMember.Username = Email;
                    newMember.LoginOnSuccess = true;
    
                    MembershipCreateStatus status = new MembershipCreateStatus();
                    MembershipUser member = Members.RegisterMember(newMember, out status);
                    Roles.AddUserToRole(newMember.Username, "Registrados");
                    member.IsApproved = true;
                    Membership.UpdateUser(member);
    
                    TempData["Status"] = "Conta criada e novo login para " + Email;
                    return Redirect("/minha-conta/login/");
                }
                TempData["Status"] = "Erro ao fazer login externo, tente mais tarde ";
                return RedirectToCurrentUmbracoPage();
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            [ActionName("DisconnectSocial")]
            public ActionResult DisconnectSocial(string name, string token)
            {
                var user = Umbraco.MembershipHelper.GetCurrentMemberProfileModel();
                var member = Services.MemberService.GetByEmail(user.Email);
                member.Properties[token].Value = "";
                Services.MemberService.Save(member);
    
                TempData["Status"] = "Vinculo " + name + " Removida!";
                return Redirect("/minha-conta/perfil");
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            [ActionName("RemoveMyAccount")]
            public ActionResult RemoveMyAccount()
            {
                var member = Umbraco.MembershipHelper.GetCurrentMemberProfileModel();
                var delete = Services.MemberService.GetByEmail(member.Email);
                Services.MemberService.Delete(delete);
                //Logout
                Session.Clear();
                FormsAuthentication.SignOut();
    
                TempData["Status"] = "Conta Removida!";
                return Redirect("/minha-conta/login");
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            [ActionName("UpdateAvatar")]
            public ActionResult UpdateAvatar(HttpPostedFileBase file)
            {
                var user = Umbraco.MembershipHelper.GetCurrentMemberProfileModel();
    
                if (user != null)
                {
                    var member = Services.MemberService.GetByEmail(user.Email);
                    var _mediaService = Services.MediaService;
                    var previousAvatar = member.GetValue("avatar") != null ? _mediaService.GetMediaByPath(member.Properties["avatar"].Value.ToString()) : null;
                    int mediaId = 0;
    
                    if (previousAvatar == null)
                    {
                        var media = _mediaService.CreateMedia(user.UserName, 8617, "Image");
                        media.SetValue("umbracoFile", file.FileName, file.InputStream);
                        Services.MediaService.Save(media);
                        mediaId = media.Id;
                    }
                    else
                    {
                        previousAvatar.SetValue("umbracoFile", file.FileName, file.InputStream);
                        Services.MediaService.Save(previousAvatar);
                        mediaId = previousAvatar.Id;
                    }
                    dynamic savedMedia = Umbraco.Media(mediaId);
                    member.Properties["avatar"].Value = savedMedia.UmbracoFile;
                    Services.MemberService.Save(member);
    
                    TempData["Status"] = "Avatar atualizado";
                    return Redirect("/minha-conta/perfil");
                }
    
                TempData["Status"] = "Erro ao atualizar avatar, tente mais tarde ";
                return Redirect("/minha-conta/perfil");
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            [ActionName("UpdateMember")]
            public ActionResult UpdateMember([Bind(Include = "Name,Email,DateOfBirth,Gender")] MemberProfileModel profile)
            {
                var u = Umbraco.MembershipHelper.GetCurrentMemberProfileModel();
                var member = Services.MemberService.GetByUsername(u.UserName);
    
                if (member != null)
                {
                    member.Name = profile.Name;
                    member.Email = profile.Email;
                    member.Properties["dateOfBirth"].Value = profile.DateOfBirth;
                    member.Properties["gender"].Value = profile.Gender;
                    Services.MemberService.Save(member);
    
                    TempData["Status"] = "Usuário atualizado";
                    return Redirect("/minha-conta/perfil");
                }
    
                TempData["Status"] = "Erro ao atualizar perfil, tente mais tarde ";
                return Redirect("/minha-conta/perfil");
            }
    
            [HttpPost]
            [ValidateAntiForgeryToken]
            [ActionName("ChangePassword")]
            public ActionResult ChangePassword(MemberPasswordModel model)
            {
                var u = Umbraco.MembershipHelper.GetCurrentMemberProfileModel();
                var member = Services.MemberService.GetByUsername(u.UserName);
    
                if (member != null)
                {
                    if (!string.IsNullOrEmpty(model.Password) && Membership.ValidateUser(member.Username, model.PreviousPassword))
                        Services.MemberService.SavePassword(member, model.Password);
    
                    TempData["Status"] = "Senha atualizada";
                    return Redirect("/minha-conta/senha");
                }
    
                TempData["Status"] = "Erro ao atualizar senha, tente mais tarde ";
                return Redirect("/minha-conta/senha");
            }
    
            public bool SendValidationConfirmed(string emailAddress, string subject)
            {
                var emailMessage = umbracoHelper.GetDictionaryValue("[Emails]AccountConfirmed");
                SetupSmtp();
                email.To = emailAddress;
                email.ToName = emailAddress;
                email.Subject = subject;
                email.Message = email.UsingTemplate(emailMessage,
                    new
                    {
                        Website = "Site Revista UFO",
                        Email = emailAddress
                    });
    
                return email.Send();
            }
    
            protected void SetupSmtp()
            {
                email.Hostname = home.GetPropertyValue<string>("hostname");
                email.Port = home.GetPropertyValue<int>("port");
                email.Username = home.GetPropertyValue<string>("username");
                email.Password = home.GetPropertyValue<string>("password");
                email.UseSSL = home.GetPropertyValue<bool>("useSSL");
                email.From = _adminEmail;
                email.FromName = home.GetPropertyValue<string>("fromName");
            }
    
            protected bool SendUserEmail(dynamic message)
            {
                var emailMessage = umbracoHelper.GetDictionaryValue("[Emails]PasswordReset");
                SetupSmtp();
                email.To = message.Email;
                email.ToName = message.Name;
                email.Subject = message.Subject;
                email.Message = email.UsingTemplate(emailMessage,
                    new
                    {
                        Website = "Site Revista UFO",
                        AdminEmail = _adminEmail,
                        Password = message.NewPassword,
                        message.Name
                    });
    
                return email.Send();
            }
    
            protected bool SendValidationEmail(dynamic message)
            {
                var emailMessage = umbracoHelper.GetDictionaryValue("[Emails]ValidateAccount");
                SetupSmtp();
                email.To = message.Email;
                email.ToName = message.Name;
                email.Subject = message.Subject;
                email.Message = email.UsingTemplate(emailMessage,
                    new
                    {
                        Website = "Site Revista UFO",
                        ValidationUrl = string.Format("http://{0}?u={1}&a={2}", RootDomain() + "/minha-conta/verificar", message.Email, message.ValidationUrl),
                        message.Name
                    });
    
                return email.Send();
            }
    
            protected string RootDomain()
            {
                return Request.Url.Authority;
            }
        }
    }
    

    Login Page

    @model RevistaUFO.Models.MemberLoginModel
    @{
        var umbHelper = new UmbracoHelper(UmbracoContext.Current);
    
        using (Html.BeginUmbracoForm("MemberLogin", "MemberLoginSurface", new { area = "Account", ReturnUrl = Request.QueryString["RedirectUrl"] }, new { @class = "form" }, FormMethod.Post))
        {
            @Html.AntiForgeryToken()
            <h5>@TempData["Status"]</h5>
            @Html.EditorFor(x => Model)
            <input type="submit" value="Entrar" />
            <a href="/minha-conta/redefinirsenha/" class="hyperlink">@umbHelper.GetDictionaryValue("[Sitewide][Login]ForgotPassword")</a>
            @Html.Partial("Parts/oauth")
        }
    }
    

    Oauth Login Part

    @{
        var umbHelper = new UmbracoHelper(UmbracoContext.Current);
        <div class="oauth">
            <h6>@umbHelper.GetDictionaryValue("[Sitewide][Login]OAuth")</h6>
            <ul>
                <li>@Html.Partial("Parts/facebook-login", new ViewDataDictionary { { "Connect", false } })</li>
                <li>@Html.Partial("Parts/google-login", new ViewDataDictionary { { "Connect", false } })</li>
                <li>@Html.Partial("Parts/twitter-login", new ViewDataDictionary { { "Connect", false } })</li>
                @*<li><i class="fa fa-instagram" aria-hidden="true"></i></li>*@
            </ul>
        </div>
    }
    

    Facebook Login

    @using Skybrud.Social.Facebook
    @using Skybrud.Social.Facebook.OAuth
    @using Skybrud.Social.Facebook.Responses.Users
    @using Umbraco.Web.Security
    @using Umbraco.Web.Models
    @using Umbraco.Core
    @using RevistaUFO.Controllers
    @model dynamic
    @{
        var umbHelper = new UmbracoHelper(UmbracoContext.Current);
    
        var home = umbHelper.TypedContentAtRoot().First();
    
        //FACEBOOK
        // Initialize a new instance of the OAuth client
        FacebookOAuthClient oauth = new FacebookOAuthClient
        {
            AppId = home.GetPropertyValue<string>("APIfacebookAppId"),
            AppSecret = home.GetPropertyValue<string>("APIfacebookAppSecret"),
            RedirectUri = home.UrlAbsolute() + "minha-conta/login?m=facebook"
        }; //"http://revistaufo.gq/minha-conta"
    
        // Read some input from the query string
        string code = Request.QueryString["code"];
        string action = Request.QueryString["do"];
        string error = Request.QueryString["error"];
        string errorCode = Request.QueryString["error_code"];
        string errorDescription = Request.QueryString["error_description"];
        string medium = Request.QueryString["m"];
    
        // Handle the state when the user clicks our login button
        if (action == "loginfacebook")
        {
            // Get the redirect URI (if present)
            string redirect = (Request.QueryString["redirect"] ?? "/");
    
            // Set the state (a unique/random value)
            string state = Guid.NewGuid().ToString();
            Session["Facebook_" + state] = redirect;
    
            // Construct the authorization URL
            string authorizatioUrl = oauth.GetAuthorizationUrl(state, FacebookScope.Email);
    
            // Redirect the user to the OAuth dialog
            Response.Redirect(authorizatioUrl);
            return;
    
        }
    
        if (medium == "facebook")
        {
            // Handle if an error occurs during the Facebook authentication (eg. if the user cancels the login)
            if (!String.IsNullOrWhiteSpace(error))
            {
                <div class="alert alert-danger">
                    <strong>Erro durante o Login</strong><br />
                    @errorDescription (código: @errorCode)
                </div>
                return;
            }
            // Handle the state when the user is redirected back to our page after a successful login with the Facebook API
            if (!String.IsNullOrWhiteSpace(code))
            {
    
                // Get the state from the query string
                string state = Request.QueryString["state"];
    
                // Validate state - Step 1
                if (state == null)
                {
                    <div class="alert alert-danger">Nenhum <strong>estado</strong> especificado no link.</div>
                    return;
                }
    
                // Validate state - Step 2
                string session = Session["Facebook_" + state] as string;
                if (session == null)
                {
                    <div class="alert alert-danger">Sessão expirada?</div>
                    return;
                }
    
                Session.Remove("facebook_" + state);
    
                string accessToken = oauth.GetAccessTokenFromAuthCode(code);
    
                FacebookService service = FacebookService.CreateFromAccessToken(accessToken);
                FacebookUserResponse response = service.Users.GetUser("me?fields=email");
    
                if (!string.IsNullOrEmpty(accessToken))
                {
                    ProfileModel user = null;
                    IMember member = null;
                    if (User.Identity.IsAuthenticated)
                    {
                        //Check if user Exists, if not, create user
                        user = new MembershipHelper(UmbracoContext.Current).GetCurrentMemberProfileModel();
                        member = ApplicationContext.Current.Services.MemberService.GetByEmail(user.Email);
                    }
                    else
                    {
                        var m = ApplicationContext.Current.Services.MemberService.GetAllMembers().ToList();
                        foreach (var mm in m)
                        {
                            if (mm.GetValue("oAuthFacebook") != null && mm.Properties["oAuthFacebook"].Value.Equals(accessToken))
                            {
                                member = mm;
                            }
                        }
                        if (member == null)
                        {
                            member = ApplicationContext.Current.Services.MemberService.GetByEmail(response.Body.Email);
                        }
                    }
    
                    if (user == null && member == null)
                    {
                        if (!string.IsNullOrEmpty(response.Body.Email))
                        {
                            new MemberLoginSurfaceController().RegisterViaExternal(response.Body.Email);
                            member = ApplicationContext.Current.Services.MemberService.GetByEmail(response.Body.Email);
                        }
                    }
    
                    member.Properties["oAuthFacebook"].Value = response.Body.Email;
                    ApplicationContext.Current.Services.MemberService.Save(member);
                    FormsAuthentication.SetAuthCookie(member.Username, true);
    
                }
                Response.Redirect("/minha-conta");
    
            }
        }
        if ((bool)ViewData["Connect"])
        {
            <a href="?do=loginfacebook" title="Vincular com Facebook" class="button connect">Vincular</a>
        }
        else
        {
            <a href="?do=loginfacebook" title="Entrar com Facebook"><i class="fa fa-facebook-square" aria-hidden="true"></i></a>
        }
    }
    

    Twitter Login

    @using Skybrud.Social.Twitter
    @using Skybrud.Social.OAuth
    @using Skybrud.Social.Twitter.OAuth
    @using Skybrud.Social.Twitter.Options.Account
        @using Umbraco.Web.Security
        @using Umbraco.Web.Models
        @using RevistaUFO.Controllers
        @using Umbraco.Core
        @model dynamic
        @{
            var umbHelper = new UmbracoHelper(UmbracoContext.Current);
    
            var home = umbHelper.TypedContentAtRoot().First();
    
            TwitterOAuthClient oauth = new TwitterOAuthClient
            {
                ConsumerKey = home.GetPropertyValue<string>("APItwitterConsumerKey"),
                ConsumerSecret = home.GetPropertyValue<string>("APItwitterConsumerSecret"),
                Callback = "http://" + Request.Url.Authority + "/minha-conta/login?m=twitter"
            };
            string code = Request.QueryString["code"];
            string action = Request.QueryString["do"];
            string error = Request.QueryString["error"];
            string errorCode = Request.QueryString["error_code"];
            string errorDescription = Request.QueryString["error_description"];
            string medium = Request.QueryString["m"];
    
            if (Request.QueryString["do"] == "logintwitter")
            {
                // Get a request token from the Twitter API
                OAuthRequestToken token = oauth.GetRequestToken();
    
                // Save the token information to the session so we can grab it later
                Session["Twitter_token_" + token.Token] = token.Token;
                Session["Twitter_secret_" + token.Token] = token.TokenSecret;
    
                // Redirect the user to the authentication page at Twitter.com
                Response.Redirect(token.AuthorizeUrl);
                return;
            }
            if (Request.QueryString["oauth_token"] != null)
            {
    
                // Get OAuth parameters from the query string
                string oAuthToken = Request.QueryString["oauth_token"];
                string oAuthVerifier = Request.QueryString["oauth_verifier"];
    
                // Grab the request token from the session
                string token = Session["Twitter_token_" + oAuthToken] as string;
                string tokenSecret = Session["Twitter_secret_" + oAuthToken] as string;
    
                if (token == null)
                {
                    <p>An error occured. Timeout?</p>
                    return;
                }
    
    
                // Update the OAuth client with information from the request token
                oauth.Token = token;
                oauth.TokenSecret = tokenSecret;
    
                Session.Remove("Twitter_token_" + oAuthToken);
                Session.Remove("Twitter_secret_" + oAuthToken);
    
                try
                {
    
                    // Obtain an access token from the request token and OAuth verifier
                    OAuthAccessToken accessToken = oauth.GetAccessToken(oAuthVerifier);
    
                    // Update the OAuth client with the access token and access token secret
                    oauth.Token = accessToken.Token;
                    oauth.TokenSecret = accessToken.TokenSecret;
    
                    // Initialize a new TwitterService instance based on the OAuth client
                    TwitterService service = TwitterService.CreateFromOAuthClient(oauth);
    
                    // Get information about the authenticated user
                    var options = new TwitterVerifyCrendetialsOptions();
                    options.IncludeEmail = true;
    
                    var response = service.Account.VerifyCredentials(options);
    
                    if (medium == "twitter")
                    {
                        if (!string.IsNullOrEmpty(response.Body.Email))
                        {
                            ProfileModel user = null;
                            IMember member = null;
                            if (User.Identity.IsAuthenticated)
                            {
                                //Check if user Exists, if not, create user
                                user = new MembershipHelper(UmbracoContext.Current).GetCurrentMemberProfileModel();
                                member = ApplicationContext.Current.Services.MemberService.GetByEmail(user.Email);
                            }
                            else
                            {
                                var m = ApplicationContext.Current.Services.MemberService.GetAllMembers().ToList();
                                foreach (var mm in m)
                                {
                                    if (mm.GetValue("oAuthTwitter") != null && mm.Properties["oAuthTwitter"].Value.Equals(response.Body.ScreenName))
                                    {
                                        member = mm;
                                    }
                                }
                                if (member == null)
                                {
                                    member = ApplicationContext.Current.Services.MemberService.GetByEmail(response.Body.Email);
                                }
                            }
    
                            if (user == null && member == null)
                            {
                                if (!string.IsNullOrEmpty(user.Email))
                                {
                                    new MemberLoginSurfaceController().RegisterViaExternal(response.Body.Email);
                                    member = ApplicationContext.Current.Services.MemberService.GetByEmail(response.Body.Email);
                                }
                            }
                            member.Properties["oAuthTwitter"].Value = response.Body.ScreenName;
                            ApplicationContext.Current.Services.MemberService.Save(member);
                            FormsAuthentication.SetAuthCookie(member.Username, true);
    
                        }
                        Response.Redirect("/minha-conta");
    
                    }
    
                }
                catch (Exception ex)
                {
    
                    <pre style="color: red;">
                    @ex.GetType().FullName @ex.Message
                            @ex.StackTrace </pre>
    
    
                }
    
            }
    
    
            if (Request.QueryString["denied"] != null)
            {
    
                // Get OAuth parameters from the query string
                string oAuthToken = Request.QueryString["denied"];
    
                // Remove the request token from the session
                Session.Remove(oAuthToken);
    
                // Write some output for the user
                <p>It seems that you cancelled the login!</p>
                <p><a href="?do=logintwitter">Try again?</a></p>
                return;
    
            }
            if ((bool)ViewData["Connect"])
            {
                <a href="?do=logintwitter" title="Vincular com Twitter" class="button connect">Vincular</a>
            }
            else
            {
                <a href="?do=logintwitter" title="Entrar com Twitter"><i class="fa fa-twitter-square" aria-hidden="true"></i></a>
            }
        }
    
Please Sign in or register to post replies

Write your reply to:

Draft