コード例 #1
0
        public ActionResult ConnectFacebook(FacebookConnectionViewModel model)
        {
            // Save user settings to db
            using (UnitOfWork work = new UnitOfWork())
            {
                user currentUser = work.UserRepository.GetUser(WebSecurity.CurrentUserId);
                work.UserRepository.AddOrUpdateFacebookSettings(currentUser, model.NotificationsEnabled, model.AutomaticSharingEnabled);
                work.SaveChanges();
            }

            // Redirect to Facebook to ask for permissions
            string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("Default", new { Controller = "Settings", Action = "ProcessFacebookLogin" });
            string scope = string.Empty; // NOTE: No change in scope needed for notifications; apps don't need to ask permission

            if (model.AutomaticSharingEnabled)
            {
                scope += "publish_actions,";
            }
            string appId         = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppId);
            string fbRedirectUrl = string.Format("https://www.facebook.com/dialog/oauth"
                                                 + "?client_id={0}"
                                                 + "&redirect_uri={1}"
                                                 + "&scope={2}",
                                                 appId, redirectAfterLoginUri, scope); // TODO: state, response_type: https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/

            Response.Redirect(fbRedirectUrl);

            // Shouldn't ever get here; if we do, re-show the form
            return(View(model));
        }
コード例 #2
0
        public ActionResult BadgeDescription(int achievementID)
        {
            string achievementTitle, achievementDescription, imageUri;

            using (UnitOfWork work = new UnitOfWork())
            {
                achievement_template template = work.AchievementRepository.GetTemplateById(achievementID);
                if (template == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
                }

                achievementTitle       = template.title;
                achievementDescription = template.description;
                imageUri = JppUriInfo.GetAbsoluteUri(Request, template.icon);
            }

            var badgeDescription = new
            {
                // TODO: truncate data if too large; see https://wiki.mozilla.org/Badges/Onboarding-Issuer#E._Metadata_Spec
                name        = achievementTitle,
                description = achievementDescription,
                image       = imageUri,
                criteria    = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("AchievementsPlayersRoute", new { id = achievementID }),
                issuer      = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("OpenBadgesIssuerRoute"),
                // TODO: tags (optional)
            };

            return(Json(badgeDescription, JsonRequestBehavior.AllowGet));
        }
コード例 #3
0
        /*/// <summary>
         * /// Handles an individual achievement's page
         * /// </summary>
         * /// <param name="id">The id of the achievement</param>
         * /// <returns>GET: /Achievements/{id}</returns>
         * public ActionResult IndividualAchievement(int id)
         * {
         * if (User.Identity.IsAuthenticated)
         * return RedirectToAction("IndividualAchievement", new { id = id, playerID = WebSecurity.CurrentUserId });
         *
         *      AchievementViewModel model =
         *              AchievementViewModel.Populate(
         *                      id,
         *                      WebSecurity.IsAuthenticated ? WebSecurity.CurrentUserId : (int?)null);
         *
         *      return View(model);
         * }*/


        public ActionResult IndividualAchievement(int id, int?playerID)
        {
            //if (playerID == null && WebSecurity.IsAuthenticated)
            //    return RedirectToAction("IndividualAchievement", new { id = id, playerID = WebSecurity.CurrentUserId });

            AchievementViewModel model = AchievementViewModel.Populate(id);

            ViewBag.servername = Request.Url.GetLeftPart(UriPartial.Authority);

            bool fbEnabled = bool.Parse(JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookIntegrationEnabled));

            if (fbEnabled)
            {
                ViewBag.FacebookMetaEnabled = true;
                ViewBag.FacebookAppId       = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppId);
                ViewBag.FacebookOgUrl       = Request.Url.GetLeftPart(UriPartial.Path);
                ViewBag.FacebookOgType      = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppNamespace)
                                              + ":achievement";
                ViewBag.FacebookOgTitle       = model.Title;
                ViewBag.FacebookOgImageUri    = JppUriInfo.GetAbsoluteUri(Request, model.Image);
                ViewBag.FacebookOgDescription = model.Description;
            }

            return(View(model));
        }
コード例 #4
0
        public ActionResult ProcessFacebookLogin()
        {
            if (Request.QueryString["error"] != null)
            {
                TempData["FacebookResultMessage"] = "There was an error validating with Facebook: " + Request.QueryString["error_description"];
                return(RedirectToAction("Index"));
                // TODO: log error?
            }

            // Exchange code for an access token
            string code = Request.QueryString["code"];
            // Redirect to Facebook to ask for permissions
            string redirectAfterLoginUri = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("Default", new { Controller = "Settings", Action = "ProcessFacebookLogin" });
            object accessTokenGetParams  = new
            {
                client_id     = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppId),
                redirect_uri  = redirectAfterLoginUri,
                client_secret = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.FacebookAppSecret),
                code          = code
            };

            var     fbClient             = new FacebookClient();
            dynamic getAccessTokenResult = fbClient.Get("/oauth/access_token", accessTokenGetParams);

            string   accessToken          = getAccessTokenResult.access_token;
            Int64    secondsTilExpiration = getAccessTokenResult.expires;
            DateTime expireTime           = DateTime.Now.AddSeconds(secondsTilExpiration);

            // Verify token is valid
            bool isTokenValid = IsUserAccessTokenValid(accessToken);

            if (!isTokenValid)
            {
                TempData["FacebookResultMessage"] = "There was an error validating with Facebook: User access token was invalid.";
                return(RedirectToAction("Index"));
            }

            // Get user ID
            fbClient = new FacebookClient(accessToken);
            dynamic fbMe     = fbClient.Get("me");
            string  fbUserId = fbMe.id.ToString();

            // Save data from Facebook into db
            using (UnitOfWork work = new UnitOfWork())
            {
                user currentUser = work.UserRepository.GetUser(WebSecurity.CurrentUserId);
                work.UserRepository.UpdateFacebookDataForExistingConnection(currentUser, fbUserId, accessToken, expireTime);
                work.SaveChanges();
            }

            TempData["FacebookResultMessage"] = "Successfully connected to Facebook!";
            return(RedirectToAction("Index"));
        }
コード例 #5
0
        public ActionResult Assertion(int userID, int achievementID)
        {
            string   userEmail, achievementImageURL;
            DateTime achievementDate;

            using (UnitOfWork work = new UnitOfWork())
            {
                // Verify user actually has achievement
                if (!work.AchievementRepository.DoesUserHaveAchievement(userID, achievementID))
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.NotFound));
                }

                // If so, get data and generate assertion
                userEmail = work.UserRepository.GetUser(userID).email;

                achievement_template achievementTemplate = work.AchievementRepository.GetTemplateById(achievementID);
                achievementImageURL = JppUriInfo.GetAbsoluteUri(Request, achievementTemplate.icon);

                achievement_instance achievementInstance = work.AchievementRepository.GetUserAchievementInstance(userID, achievementID);
                achievementDate = achievementInstance.achieved_date;
            }
            string salt = "CoeA8DQf"; // As we are exposing the salt anyway, using a constant isn't an issue, and it saves us from having to store every randomly-generated salt in the db
            string hashedEmail;

            hashedEmail = Sha256Helper.HashStringWithSalt(userEmail, salt);

            var badgeAssertion = new
            {
                uid       = GenerateUniqueId(userID, achievementID),
                recipient = new
                {
                    identity = "sha256$" + hashedEmail,
                    type     = "email",
                    hashed   = true,
                    salt     = salt
                },
                image  = achievementImageURL,
                badge  = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("OpenBadgeDescriptionRoute", new { Action = "BadgeDescription", achievementID = achievementID }),
                verify = new
                {
                    type = "hosted",
                    url  = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("OpenBadgeRoute", new { Action = "Assertion", userID = userID, achievementID = achievementID }),
                },
                issuedOn = achievementDate.ToString("s", System.Globalization.CultureInfo.InvariantCulture),
                evidence = JppUriInfo.GetCurrentDomain(Request) + Url.RouteUrl("AchievementsPlayersRoute", new { id = achievementID, playerID = userID }),
            };

            return(Json(badgeAssertion, JsonRequestBehavior.AllowGet));
        }
コード例 #6
0
        public JsonResult Issuer()
        {
            string organizationName = JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SchoolName);
            string organizationLogo = JppUriInfo.GetAbsoluteUri(Request, JPPConstants.SiteSettings.GetValue(JPPConstants.SiteSettings.SchoolLogo));

            var issuerOrganization = new
            {
                name  = organizationName,
                url   = JppUriInfo.GetCurrentDomain(Request), // TODO: Get org-specific URL rather than badge site?
                image = organizationLogo
            };

            return(Json(issuerOrganization, JsonRequestBehavior.AllowGet));
        }