private InMemoryUserStore <IdentityUser> NewUserStore()
        {
            var userStore = new InMemoryUserStore <IdentityUser>();

            userStore.Clear();
            return(userStore);
        }
        public ActionResult SendToFacebook(int id)
        {
            var model = repository.Especiales.First(e => e.EspecialId == id);

            try
            {
                var     facebookId = User.Identity.Name;
                var     user       = InMemoryUserStore.Get(facebookId);
                var     client     = new FacebookClient(user.AccessToken);
                dynamic parameters = new ExpandoObject();
                parameters.message = string.Format("{0} esta oferta es valida desde {1} hasta {2}", model.Nombre, model.FechaInicio.ToShortDateString(), model.FechaTermino.ToShortDateString());
                //parameters.link = "http://www.youtube.com/watch?v=tko0vvD0N-E";
                //parameters.picture = "http://i3.ytimg.com/vi/2Me7BRES0wQ/default.jpg";
                parameters.name        = model.Nombre;
                parameters.caption     = model.Precio;
                parameters.description = model.Descripcion;

                dynamic result = client.Post(user.FacebookId + "/feed", parameters);
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Detalles", new { id = id }));
            }

            return(RedirectToAction("Detalles", new { id = id }));
        }
Пример #3
0
 protected override void OnAuthorization(AuthorizationContext filterContext)
 {
     base.OnAuthorization(filterContext);
     if (InMemoryUserStore.Get(User.Identity.Name) == null)
     {
         filterContext.Result = new HttpUnauthorizedResult();
     }
 }
        public void ctor_shoud_create()
        {
            //
            var userStore = new InMemoryUserStore();

            var service = GetServiceTestInstance();

            Assert.NotNull(service);
        }
Пример #5
0
        public ActionResult Friends()
        {
            var        user        = InMemoryUserStore.Get(User.Identity.Name);
            var        fb          = new FacebookClient(user.AccessToken);
            JsonObject friendsData = fb.Get("/me/friends") as JsonObject;
            var        data        = friendsData["data"] as JsonArray;

            ViewBag.Friends = data;
            return(View());
        }
 protected override IIdentityManagerService CreateIdentityManager()
 {
     var store = new InMemoryUserStore();
     userManager = new UserManager<InMemoryUser>(store);
     userManager.PasswordValidator = new PasswordValidator
     {
         RequiredLength = 4
     };
     return new IdentityManagerService<InMemoryUser, string>(userManager);
 }
        public async Task UserLoginManager_UserLogin_ExistingUser_HasPropertiesAndRoleClaimsUpdated()
        {
            var documentDbUserStore = new InMemoryUserStore(new InMemoryDocumentService());

            var userLoginManager = new UserLoginManager(documentDbUserStore, new Mock <ILogger>().Object);

            var userId     = "HealthCatalyst\\foo.bar";
            var provider   = FabricIdentityConstants.FabricExternalIdentityProviderTypes.Windows;
            var clientId   = "sampleApp";
            var userName   = "******";
            var firstName  = "foo";
            var lastName   = "bar";
            var middleName = "dot";
            var claims     = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtClaimTypes.GivenName, firstName),
                new Claim(JwtClaimTypes.FamilyName, lastName),
                new Claim(JwtClaimTypes.MiddleName, middleName),
                new Claim(JwtClaimTypes.Role, @"FABRIC\Health Catalyst Viewer")
            };

            var existingUser = await userLoginManager.UserLogin(provider, userId, claims, clientId);

            var existingRoleClaim = existingUser.Claims.Single(c => c.Type == JwtClaimTypes.Role);
            var firstLoginDate    = existingUser.LastLoginDatesByClient.First().LoginDate;

            userId     = "HealthCatalyst\\foo.bar";
            provider   = FabricIdentityConstants.FabricExternalIdentityProviderTypes.Windows;
            clientId   = "sampleApp";
            userName   = "******";
            firstName  = "abc";
            lastName   = "def";
            middleName = "zzz";
            claims     = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(JwtClaimTypes.GivenName, firstName),
                new Claim(JwtClaimTypes.FamilyName, lastName),
                new Claim(JwtClaimTypes.MiddleName, middleName),
                new Claim(JwtClaimTypes.Role, @"FABRIC\Health Catalyst Editor")
            };

            var updatedUser = await userLoginManager.UserLogin(provider, userId, claims, clientId);

            Assert.Equal(userName, updatedUser.Username);
            Assert.Equal(firstName, updatedUser.FirstName);
            Assert.Equal(lastName, updatedUser.LastName);
            Assert.Equal(middleName, updatedUser.MiddleName);
            Assert.Equal(5, updatedUser.Claims.Count);
            Assert.NotEqual(existingRoleClaim.Value, updatedUser.Claims.First().Value);
            Assert.True(firstLoginDate.Ticks < updatedUser.LastLoginDatesByClient.First().LoginDate.Ticks);
        }
Пример #8
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current)
                    {
                        RedirectUri = new Uri(RedirectUrl)
                    };
                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    var expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    var     fbClient   = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("me?fields=id,name");
                    long    facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
Пример #9
0
        public ActionResult ProfileInfo()
        {
            var facebookId = long.Parse(User.Identity.Name);
            var user       = InMemoryUserStore.Get(facebookId);
            var client     = new FacebookClient(user.AccessToken);

            dynamic me = client.Get("me?fields=id,name,username,email,birthday");

            ViewBag.Name     = me.name;
            ViewBag.Id       = me.id;
            ViewBag.Email    = me.email;
            ViewBag.Birthday = me.birthday;
            ViewBag.UserId   = Membership.GetUser().ProviderUserKey;
            return(View());
        }
Пример #10
0
        public ActionResult Index()
        {
            try
            {
                var user = InMemoryUserStore.Get(User.Identity.Name);

                var     fb = new FacebookClient(user.AccessToken);
                dynamic me = fb.Get("me");

                ViewBag.name = me.name;
            }
            catch (FacebookApiException)
            {
                FormsAuthentication.SignOut();
                return(new HttpUnauthorizedResult());
            }

            return(View());
        }
Пример #11
0
        public ActionResult PostToWall(FormCollection formCollection)
        {
            List <ExpandoObject> results = new List <ExpandoObject>();
            var user = InMemoryUserStore.Get(User.Identity.Name);
            var fb   = new FacebookClient(user.AccessToken);

            var friends = formCollection["chkFriends"];

            if (!string.IsNullOrEmpty(friends))
            {
                string[] users = friends.Split(',');
                foreach (var friend in users)
                {
                    if (!string.IsNullOrEmpty(friend))
                    {
                        dynamic fbFriendValue = fb.Get(string.Format("{0}?fields=id,name", friend));
                        dynamic data          = new ExpandoObject();
                        string  path          = string.Format(@"/{0}/feed", friend);
                        Dictionary <string, object> parameters = new Dictionary <string, object>();
                        parameters.Add("name", formCollection["Name"]);
                        parameters.Add("link", formCollection["Link"]);
                        parameters.Add("picture", formCollection["Picture"]);
                        parameters.Add("message", formCollection["Message"]);
                        parameters.Add("caption", formCollection["Caption"]);
                        if (ConfigurationManager.AppSettings["AllowFeedPosting"] == "True")
                        {
                            dynamic fbFeedValue = fb.Post(path, parameters);
                            data.FeedId = fbFeedValue.id;
                        }
                        else
                        {
                            data.FeedId = -1;
                        }

                        data.FriendName = fbFriendValue.name;
                        results.Add(data);
                    }
                }
            }

            ViewBag.Results = results;
            return(View());
        }
Пример #12
0
        private void ProcessSuccesfulFacebookCallback(IDictionary <string, object> result)
        {
            string accessToken = (string)result["access_token"];

            // incase the expires on is not present, it means we have offline_access permission
            DateTime expiresOn = result.ContainsKey("expires") ? DateTime.UtcNow.AddSeconds(Convert.ToDouble(result["expires"])) : DateTime.MaxValue;

            var     fb   = new FacebookClient(accessToken);
            dynamic me   = fb.Get("me?fields=id,name");
            string  id   = me.id;
            string  name = me.name;

            // do your custom logic to store the user here
            InMemoryUserStore.AddOrUpdate(new FacebookUser {
                AccessToken = accessToken, FacebookId = id, Name = name
            });

            // set the forms auth cookie
            FormsAuthentication.SetAuthCookie(id, false);
        }
Пример #13
0
        /// <summary>
        ///  Facebook authentication
        /// </summary>
        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    string url = string.Format(@"https://graph.facebook.com/oauth/access_token?client_id=146563355411375&client_secret=03232f1f920aec6f4e4600105f1dfba4&scope=publish_stream&grant_type=client_credentials&redirect_uri={0}", redirectUrl);

                    var request = (HttpWebRequest)WebRequest.Create(url);

                    var response    = (HttpWebResponse)request.GetResponse();
                    var reader      = new StreamReader(response.GetResponseStream());
                    var token       = reader.ReadToEnd();
                    var accessToken = token.Split('=')[1];

                    var expiresOn = DateTime.MaxValue;

                    var     fbClient   = new FacebookClient(accessToken);
                    dynamic me         = fbClient.Get("drquipe");
                    string  facebookId = me.id;

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.username,
                    });

                    FormsAuthentication.SetAuthCookie(facebookId, false);
                }

                return(RedirectToAction("Index", "Productos"));
            }


            return(RedirectToAction("Index", "Home"));
        }
Пример #14
0
        //
        // GET: /Account/LogOff/

        public ActionResult LogOff()
        {
            var facebookId = long.Parse(User.Identity.Name);
            var user       = InMemoryUserStore.Get(facebookId);

            FormsAuthentication.SignOut();
            if (user != null)
            {
                var logoutUrl = String.Format("https://www.facebook.com/logout.php?next={0}&access_token={1}", logoffUrl, user.AccessToken);
                return(Redirect(logoutUrl));
            }
            else
            {
                return(Redirect(logoffUrl));
            }


            //var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
            //oAuthClient.RedirectUri = new Uri(logoffUrl);
            //var logoutUrl = oAuthClient.GetLogoutUrl();
            //return Redirect(logoutUrl);//.AbsoluteUri);
        }
Пример #15
0
        //
        // GET: /Account/OAuth/

        public ActionResult OAuth(string code, string state)
        {
            FacebookOAuthResult oauthResult;

            if (FacebookOAuthResult.TryParse(Request.Url, out oauthResult))
            {
                if (oauthResult.IsSuccess)
                {
                    var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
                    oAuthClient.RedirectUri = new Uri(redirectUrl);

                    dynamic tokenResult = oAuthClient.ExchangeCodeForAccessToken(code);
                    string  accessToken = tokenResult.access_token;

                    DateTime expiresOn = DateTime.MaxValue;

                    if (tokenResult.ContainsKey("expires"))
                    {
                        DateTimeConvertor.FromUnixTime(tokenResult.expires);
                    }

                    FacebookClient fbClient   = new FacebookClient(accessToken);
                    dynamic        me         = fbClient.Get("me?fields=id,name,email,birthday,gender");
                    long           facebookId = Convert.ToInt64(me.id);

                    InMemoryUserStore.Add(new FacebookUser
                    {
                        AccessToken = accessToken,
                        Expires     = expiresOn,
                        FacebookId  = facebookId,
                        Name        = (string)me.name,
                    });

                    var user = Membership.GetUser(facebookId.ToString());

                    FormsAuthentication.SetAuthCookie(facebookId.ToString(), false);

                    string      format   = "d";
                    CultureInfo provider = CultureInfo.InvariantCulture;
                    DateTime    birthday = new DateTime();
                    try
                    {
                        birthday = DateTime.ParseExact(me.birthday, format, provider);
                    }
                    catch
                    {
                    }

                    if (user == null)
                    {
                        var u = Membership.CreateUser(facebookId.ToString(), Guid.NewGuid().ToString());
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Create((Guid)u.ProviderUserKey,
                                                 facebookId.ToString(),
                                                 (string)me.name,
                                                 Transfer.GetPictureUrl(facebookId.ToString()),
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }
                    else
                    {
                        using (BestPlaceEntities db = new BestPlaceEntities())
                        {
                            db.bp_Profile_Update((Guid)user.ProviderUserKey,
                                                 (string)me.name,
                                                 (string)me.email,
                                                 null,
                                                 birthday,
                                                 ((string)me.gender == "male") ? true : false,
                                                 null, null);
                        }
                    }

                    // prevent open redirection attack by checking if the url is local.
                    if (Url.IsLocalUrl(state))
                    {
                        return(Redirect(state));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                }
            }

            return(RedirectToAction("Index", "Home"));
        }
 public UsersControllerTests(string provider = FabricIdentityConstants.StorageProviders.InMemory) : base(provider)
 {
     UserStore = new InMemoryUserStore(new InMemoryDocumentService());
 }
 public InMemoryUserStoreTests()
 {
     _authenticationService = new Mock <ILdapService <OpenLdapAppUser> >();
     _inMemoryUserStore     = new InMemoryUserStore <OpenLdapAppUser>(_authenticationService.Object);
 }