Example #1
0
        public async Task<JsonResult> Authenticate()
        {
            var profile = await TryAuthenticateFromHttpContext();
            if (profile != null)
            {
                _baseModel.User = profile;
                return Json(new
                {
                    Status = "Connected",
                    Session = new
                    {
                        
                        User = SessionWrapper.Get<string>("CurrentUserProfileName")
                    },

                }, JsonRequestBehavior.AllowGet);
            }

            var svc = new LiveIdAuth();
            var url = svc.GetLogoutUrl("http://" + Request.Headers.Get("host"));

            SessionWrapper.Clear();
            return Json(new
            {
                Status = "unknown",
                S = url
            }, JsonRequestBehavior.AllowGet);
        }
Example #2
0
        protected static async Task <ProfileDetails> ValidateAuthentication()
        {
            var svc   = new LiveIdAuth();
            var token = System.Web.HttpContext.Current.Request.Headers["LiveUserToken"];

            if (token == null)
            {
                token = System.Web.HttpContext.Current.Request.QueryString["LiveUserToken"];
            }
            var cachedProfile = ProfileCacheManager.GetProfileDetails(token);

            if (cachedProfile != null)
            {
                return(cachedProfile);
            }
            var userId = await svc.GetUserId(token);

            if (userId != null && userId.Length > 3)
            {
                var profileService = DependencyResolver.Current.GetService(typeof(IProfileService)) as IProfileService;
                var profileDetails = profileService.GetProfile(userId);
                if (profileDetails != null)
                {
                    ProfileCacheManager.CacheProfile(token, profileDetails);
                }

                return(profileDetails);
            }

            return(null);
        }
Example #3
0
        public async Task <JsonResult> Authenticate()
        {
            var result = await TryAuthenticateFromHttpContext(_communityService, _notificationService);

            if (result.Status == LiveConnectSessionStatus.Connected)
            {
                _baseModel.User = SessionWrapper.Get <ProfileDetails>("ProfileDetails");
                return(Json(new
                {
                    Status = result.Status.ToString(),
                    Session = new
                    {
                        result.Session.AccessToken,
                        result.Session.AuthenticationToken,
                        Expires = result.Session.Expires.ToLocalTime().ToString(),
                        result.Session.RefreshToken,
                        result.Session.Scopes,
                        User = SessionWrapper.Get <string>("CurrentUserProfileName")
                    },
                }, JsonRequestBehavior.AllowGet));
            }

            var svc = new LiveIdAuth();
            var url = svc.GetLogoutUrl("http://" + Request.Headers.Get("host"));

            SessionWrapper.Clear();
            return(Json(new
            {
                Status = result.Status.ToString(),
                S = url
            }, JsonRequestBehavior.AllowGet));
        }
        private async Task <ProfileDetails> InitUserProfile(string liveId, string accessToken)
        {
            if (string.IsNullOrEmpty(liveId))
            {
                return(null);
            }
            var profileDetails = ProfileService.GetProfile(liveId);

            if (profileDetails == null)
            {
                if (string.IsNullOrEmpty(accessToken))
                {
                    return(null);
                }
                var svc = new LiveIdAuth();

                var getResult = await svc.GetMeInfo(accessToken);

                var jsonResult = getResult;
                profileDetails = new ProfileDetails(jsonResult)
                {
                    IsSubscribed = true,
                    UserType     = UserTypes.Regular
                };
                // While creating the user, IsSubscribed to be true always.

                // When creating the user, by default the user type will be of regular.
                profileDetails.ID = ProfileService.CreateProfile(profileDetails);

                // This will used as the default community when user is uploading a new content.
                // This community will need to have the following details:
                var communityDetails = new CommunityDetails
                {
                    CommunityType = CommunityTypes.User,         // 1. This community type should be User
                    CreatedByID   = profileDetails.ID,           // 2. CreatedBy will be the new USER.
                    IsFeatured    = false,                       // 3. This community is not featured.
                    Name          = Resources.UserCommunityName, // 4. Name should be NONE.
                    AccessTypeID  = (int)AccessType.Private,     // 5. Access type should be private.
                    CategoryID    = (int)CategoryType.GeneralInterest
                                                                 // 6. Set the category ID of general interest. We need to set the Category ID as it is a foreign key and cannot be null.
                };

                var communityService    = DependencyResolver.Current.GetService(typeof(ICommunityService)) as ICommunityService;
                var notificationService = DependencyResolver.Current.GetService(typeof(INotificationService)) as INotificationService;
                // 7. Create the community
                communityService.CreateCommunity(communityDetails);

                // Send New user notification.
                notificationService.NotifyNewEntityRequest(profileDetails,
                                                           HttpContext.Request.Url.GetServerLink());
            }

            SessionWrapper.Set("CurrentUserID", profileDetails.ID);
            SessionWrapper.Set("CurrentUserProfileName",
                               profileDetails.FirstName + " " + profileDetails.LastName);
            SessionWrapper.Set("ProfileDetails", profileDetails);

            return(profileDetails);
        }
        private async Task <ProfileDetails> TryRefreshToken(LiveIdAuth svc)
        {
            if (Request.Cookies["refresh_token"] != null && Request.Cookies["refresh_token"].Value.Length > 1)
            {
                var result = await svc.RefreshTokens();

                return(await UserFromToken(result, svc));
            }
            return(null);
        }
Example #6
0
        protected async Task <LiveLoginResult> TryAuthenticateFromHttpContext(ICommunityService communityService, INotificationService notificationService)
        {
            var svc    = new LiveIdAuth();
            var result = await svc.Authenticate();

            if (result.Status == LiveConnectSessionStatus.Connected)
            {
                var client = new LiveConnectClient(result.Session);
                SessionWrapper.Set("LiveConnectClient", client);
                SessionWrapper.Set("LiveConnectResult", result);
                SessionWrapper.Set("LiveAuthSvc", svc);

                var getResult = await client.GetAsync("me");

                var jsonResult     = getResult.Result as dynamic;
                var profileDetails = ProfileService.GetProfile(jsonResult.id);
                if (profileDetails == null)
                {
                    profileDetails = new ProfileDetails(jsonResult);
                    // While creating the user, IsSubscribed to be true always.
                    profileDetails.IsSubscribed = true;

                    // When creating the user, by default the user type will be of regular.
                    profileDetails.UserType = UserTypes.Regular;
                    profileDetails.ID       = ProfileService.CreateProfile(profileDetails);

                    // This will used as the default community when user is uploading a new content.
                    // This community will need to have the following details:
                    var communityDetails = new CommunityDetails
                    {
                        CommunityType = CommunityTypes.User,         // 1. This community type should be User
                        CreatedByID   = profileDetails.ID,           // 2. CreatedBy will be the new USER.
                        IsFeatured    = false,                       // 3. This community is not featured.
                        Name          = Resources.UserCommunityName, // 4. Name should be NONE.
                        AccessTypeID  = (int)AccessType.Private,     // 5. Access type should be private.
                        CategoryID    = (int)CategoryType.GeneralInterest
                                                                     // 6. Set the category ID of general interest. We need to set the Category ID as it is a foreign key and cannot be null.
                    };

                    // 7. Create the community
                    communityService.CreateCommunity(communityDetails);

                    // Send New user notification.
                    notificationService.NotifyNewEntityRequest(profileDetails,
                                                               HttpContext.Request.Url.GetServerLink());
                }

                SessionWrapper.Set <long>("CurrentUserID", profileDetails.ID);
                SessionWrapper.Set <string>("CurrentUserProfileName",
                                            profileDetails.FirstName + " " + profileDetails.LastName);
                SessionWrapper.Set("ProfileDetails", profileDetails);
                SessionWrapper.Set("AuthenticationToken", result.Session.AuthenticationToken);
            }
            return(result);
        }
        protected async Task <ProfileDetails> TryAuthenticateFromHttpContext()
        {
            if (SessionWrapper.Get <ProfileDetails>("ProfileDetails") != null)
            {
                return(SessionWrapper.Get <ProfileDetails>("ProfileDetails"));
            }

            var svc = new LiveIdAuth();

            var result = await svc.Authenticate();

            string userId = null;

            if (result.Status != LiveConnectSessionStatus.Connected)
            {
                var resultstring = await svc.RefreshTokens();

                if (string.IsNullOrEmpty(resultstring))
                {
                    return(null);
                }
                var tokens = new { access_token = "", refresh_token = "" };
                var json   = JsonConvert.DeserializeAnonymousType(resultstring, tokens);
                userId = await svc.GetUserId(tokens.access_token);

                if (string.IsNullOrEmpty(userId))
                {
                    return(null);
                }
                return(await InitUserProfile(userId, json.access_token));
            }

            var     client     = new LiveConnectClient(result.Session);
            dynamic jsonResult = null;
            var     getResult  = await client.GetAsync("me");

            jsonResult = getResult.Result as dynamic;
            foreach (KeyValuePair <string, object> item in jsonResult)
            {
                if (item.Key.ToLower() == "id")
                {
                    userId = item.Value.ToString();
                }
            }
            //userId = jsonResult["id"].ToString();

            return(await InitUserProfile(userId, result.Session.AccessToken));
        }
        private async Task <ProfileDetails> UserFromToken(string tokenResult, LiveIdAuth svc)
        {
            if (string.IsNullOrEmpty(tokenResult))
            {
                return(null);
            }
            var tokens = new { access_token = "", refresh_token = "" };
            var json   = JsonConvert.DeserializeAnonymousType(tokenResult, tokens);
            var userId = await svc.GetUserId(json.access_token);

            if (string.IsNullOrEmpty(userId))
            {
                return(null);
            }
            return(await InitUserProfile(userId, json.access_token));
        }
        protected static async Task <ProfileDetails> ValidateAuthentication()
        {
            var svc   = new LiveIdAuth();
            var token = System.Web.HttpContext.Current.Request.Headers["LiveUserToken"];

            if (token == null)
            {
                var authCookie = System.Web.HttpContext.Current.Request.Cookies["access_token"];
                if (authCookie != null)
                {
                    token = authCookie.Value;
                }
            }
            var cachedProfile = ProfileCacheManager.GetProfileDetails(token);

            if (cachedProfile != null)
            {
                return(cachedProfile);
            }
            string userId = null;

            userId = await svc.GetUserId(token);

            if (userId == null)
            {
                var result = await svc.RefreshTokens();

                var tokens = new { access_token = "", refresh_token = "" };
                var json   = JsonConvert.DeserializeAnonymousType(result, tokens);
                userId = await svc.GetUserId(json.access_token);
            }
            if (userId == null || userId.Length <= 3)
            {
                return(null);
            }
            var profileService = DependencyResolver.Current.GetService(typeof(IProfileService)) as IProfileService;
            var profileDetails = profileService.GetProfile(userId);

            if (profileDetails != null && token != null)
            {
                ProfileCacheManager.CacheProfile(token, profileDetails);
            }

            return(profileDetails);
        }
        protected async Task <ProfileDetails> TryAuthenticateFromHttpContext()
        {
            if (Request.Headers.Get("host").Contains("localhost"))
            {
                return(null);
            }
            if (SessionWrapper.Get <ProfileDetails>("ProfileDetails") != null)
            {
                return(SessionWrapper.Get <ProfileDetails>("ProfileDetails"));
            }

            var svc = new LiveIdAuth();

            var profile = await TryRefreshToken(svc);

            if (profile != null)
            {
                return(profile);
            }
            var result = await svc.Authenticate();

            string userId = null;

            if (result.Status != LiveConnectSessionStatus.Connected)
            {
                return(await UserFromToken(await svc.RefreshTokens(), svc));
            }

            var     client     = new LiveConnectClient(result.Session);
            dynamic jsonResult = null;
            var     getResult  = await client.GetAsync("me");

            jsonResult = getResult.Result;
            foreach (KeyValuePair <string, object> item in jsonResult)
            {
                if (item.Key.ToLower() == "id")
                {
                    userId = item.Value.ToString();
                }
            }
            //userId = jsonResult["id"].ToString();

            return(await InitUserProfile(userId, result.Session.AccessToken));
        }
        protected async Task <ProfileDetails> TryAuthenticateFromAuthCode(string authCode)
        {
            if (Request.Headers.Get("host").Contains("localhost"))
            {
                return(null);
            }
            if (SessionWrapper.Get <ProfileDetails>("ProfileDetails") != null)
            {
                return(SessionWrapper.Get <ProfileDetails>("ProfileDetails"));
            }
            var svc     = new LiveIdAuth();
            var profile = await TryRefreshToken(svc);

            if (profile == null && authCode.Length > 1)
            {
                profile = await UserFromToken(await svc.GetTokens(authCode), svc);
            }
            return(profile);
        }
        protected async Task <ProfileDetails> TryAuthenticateFromAuthCode(string authCode)
        {
            var    svc    = new LiveIdAuth();
            string result = "";

            if (Request.Cookies["refresh_token"] != null && Request.Cookies["refresh_token"].Value.Length > 1)
            {
                result = await svc.RefreshTokens();
            }
            else
            {
                result = await svc.GetTokens(authCode);
            }
            var tokens = new { access_token = "", refresh_token = "" };
            var json   = JsonConvert.DeserializeAnonymousType(result, tokens);
            var userId = await svc.GetUserId(json.access_token);

            return(await InitUserProfile(userId, json.access_token));
        }
        public async Task <bool> RegisterUser()
        {
            var profileDetails = await ValidateAuthentication();

            if (profileDetails == null)
            {
                var     svc        = new LiveIdAuth();
                dynamic jsonResult = svc.GetMeInfo(System.Web.HttpContext.Current.Request.Headers["LiveUserToken"]);
                profileDetails = new ProfileDetails(jsonResult);
                // While creating the user, IsSubscribed to be true always.
                profileDetails.IsSubscribed = true;

                // When creating the user, by default the user type will be of regular.
                profileDetails.UserType = UserTypes.Regular;
                profileDetails.ID       = ProfileService.CreateProfile(profileDetails);

                // This will used as the default community when user is uploading a new content.
                // This community will need to have the following details:
                var communityDetails = new CommunityDetails
                {
                    CommunityType = CommunityTypes.User,              // 1. This community type should be User
                    CreatedByID   = profileDetails.ID,                // 2. CreatedBy will be the new USER.
                    IsFeatured    = false,                            // 3. This community is not featured.
                    Name          = Resources.UserCommunityName,      // 4. Name should be NONE.
                    AccessTypeID  = (int)AccessType.Private,          // 5. Access type should be private.
                    CategoryID    = (int)CategoryType.GeneralInterest // 6. Set the category ID of general interest. We need to set the Category ID as it is a foreign key and cannot be null.
                };

                // 7. Create the community
                _communityService.CreateCommunity(communityDetails);

                // Send New user notification.
                _notificationService.NotifyNewEntityRequest(profileDetails,
                                                            HttpContext.Request.Url.GetServerLink());
            }
            else
            {
                throw new WebFaultException <string>("User already registered", HttpStatusCode.BadRequest);
            }
            return(true);
        }
Example #14
0
 public ActionResult Logout()
 {
     var svc = new LiveIdAuth();
     var url =  svc.GetLogoutUrl("http://" + Request.Headers.Get("host")); 
     
     SessionWrapper.Clear();
     var refreshTokenCookie = Response.Cookies["refresh_token"];
     var accessTokenCookie = Response.Cookies["access_token"];
     if (refreshTokenCookie != null && !string.IsNullOrEmpty(refreshTokenCookie.Value))
     {
         refreshTokenCookie.Expires = DateTime.Now.AddDays(-1);
         Response.Cookies.Add(refreshTokenCookie);
     }
     if (accessTokenCookie != null && !string.IsNullOrEmpty(accessTokenCookie.Value))
     {
         accessTokenCookie.Expires = DateTime.Now.AddDays(-1);
         Response.Cookies.Add(accessTokenCookie);
     }
     
     return Redirect(url); 
 }