Exemplo n.º 1
0
        public AccountUserDocument AddOrUpdateFacebookUser(FbModel model)
        {
            using (IDocumentSession Session = DataDocumentStore.Instance.OpenSession())
            {
                BCryptService crypto = new BCryptService();


                //Get the user by their facebook Id
                var user = Session.Query <AccountUserDocument, AccountUser_ByFacebookId>().Where(x => x.FacebookId == model.FacebookId).SingleOrDefault();


                if (user != null)
                {
                    //User exists, update it
                    user.Name             = model.Email;
                    user.FacebookEmail    = model.Email;
                    user.AllowedDatabases = new[] { "*" };
                    user.FirstName        = model.FirstName;
                    user.LastName         = model.LastName;
                    user.AccessToken      = model.AccessToken;
                    user.FacebookId       = model.FacebookId;
                    user.Expires          = model.Expires;
                    user.AccountHash      = System.Uri.EscapeDataString(crypto.Hash(model.FacebookId.ToString()));

                    //Save Changes
                    Session.SaveChanges();
                    return(user);
                }
                else
                {
                    //No user, create a new one
                    Guid userId = Guid.NewGuid();
                    Session.Store(new AccountUserDocument
                    {
                        Name             = model.Email,
                        FacebookEmail    = model.Email,
                        Id               = String.Format("FacebookTest/Users/{0}", userId.ToString()),
                        AllowedDatabases = new[] { "*" },
                        FirstName        = model.FirstName,
                        LastName         = model.LastName,
                        AccessToken      = model.AccessToken,
                        FacebookId       = model.FacebookId,
                        Expires          = model.Expires,
                        AccountHash      = System.Uri.EscapeDataString(crypto.Hash(model.FacebookId.ToString()))
                    });

                    //Save Changes
                    Session.SaveChanges();
                    return(Session.Load <AccountUserDocument>(String.Format("FacebookTest/Users/{0}", userId)));
                }
            }
        }
Exemplo n.º 2
0
 public AccountUserDocument ActivateFacebookAccount(FbModel model)
 {
     using (IDocumentSession Session = DataDocumentStore.Instance.OpenSession())
     {
         var user = Session.Query <AccountUserDocument>().Where(x => x.AccountHash == model.Code).SingleOrDefault();
         if (user != null)
         {
             user.Email = model.Email;
             user.SetPassword(model.Password);
             Session.SaveChanges();
             return(user);
         }
         else
         {
             throw new UserNotFoundException("User was not found while trying to active facebook acount", new Exception("AccountHash is " + model.Code));
         }
     }
 }
Exemplo n.º 3
0
 public ActionResult RegisterFacebook(FbModel model)
 {
     if (ModelState.IsValid)
     {
         try
         {
             var user = AccountService.ActivateFacebookAccount(model);
             AuthenticateUser(user.Id, user.FirstName, user.LastName, user.Email, user.FacebookId, user.AccessToken);
             return(RedirectToAction("Home", "Index"));
         }
         catch (UserNotFoundException ex)
         {
             return(RedirectToAction("Error", "Content"));
         }
     }
     else
     {
         return(View(model));
     }
 }
Exemplo n.º 4
0
        public ActionResult FbAuth(string returnUrl)
        {
            var client = new FacebookClient();

            try
            {
                var oauthResult = client.ParseOAuthCallbackUrl(Request.Url);


                // Build the Return URI form the Request Url
                var redirectUri = new UriBuilder(Request.Url);
                redirectUri.Path = Url.Action("FbAuth", "Account");

                //Get the Public Uri due to apphabor getting all "cloudy" with ports
                var urlHelper = new UrlHelper(Request.RequestContext);
                var publicUrl = urlHelper.ToPublicUrl(redirectUri.Uri);



                // Exchange the code for an access token
                dynamic result = client.Get("/oauth/access_token", new
                {
                    client_id     = ConfigurationManager.AppSettings["FacebookAppId"],
                    redirect_uri  = publicUrl,
                    client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
                    code          = oauthResult.Code,
                });

                // Read the auth values
                string   accessToken = result.access_token;
                DateTime expires     = DateTime.UtcNow.AddSeconds(Convert.ToDouble(result.expires));

                // Get the user's profile information
                dynamic me = client.Get("/me",
                                        new
                {
                    fields       = "first_name,last_name,email",
                    access_token = accessToken
                });

                //Instantiate FbModel
                var model = new FbModel();

                // Read the Facebook user values
                model.FacebookId = Convert.ToInt64(me.id);
                model.FirstName  = me.first_name;
                model.LastName   = me.last_name;
                model.Email      = me.email;


                // Add the user to our persistent store
                var user = AccountService.AddOrUpdateFacebookUser(model);


                //Check if the account requires the password to be set
                if (string.IsNullOrEmpty(user.Email))
                {
                    return(RedirectToAction("RegisterFacebook", "Account", new { @code = user.AccountHash }));
                }
                else
                {
                    AuthenticateUser(user.Id, user.FirstName, user.LastName, user.Email, user.FacebookId, user.AccessToken);
                    return(RedirectToAction("Index", "Home"));
                }
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            }


            return(RedirectToAction("Content", "Error"));
        }