Пример #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceRecord"></param>
        private void AddPlayerToIdentities(ServiceRecord serviceRecord)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var gamertag     = serviceRecord.Gamertag;
                var gamertagSafe = GamerIdentity.EscapeGamerId(gamertag);

                var gamerIdentity = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamertagSafe);
                if (gamerIdentity == null)
                {
                    gamerIdentity = new GamerIdentity
                    {
                        GamerId     = gamertag,
                        GamerIdSafe = gamertagSafe,
                        Type        = IdentityType.XblGamertag
                    };
                    sqlStorage.GamerIdentities.Add(gamerIdentity);
                    sqlStorage.SaveChanges();
                }

                var halo4Identity = sqlStorage.Halo4Identities.FirstOrDefault(h => h.GamerIdentity.Id == gamerIdentity.Id) ??
                                    new Halo4Identity();

                halo4Identity.GamerIdentity   = gamerIdentity;
                halo4Identity.ServiceTag      = serviceRecord.ServiceTag;
                halo4Identity.FavouriteWeapon = serviceRecord.FavoriteWeaponName;
                halo4Identity.KillDeathRatio  = serviceRecord.GameModes.First(m => m.Id == GameMode.WarGames).KdRatio ?? 1.0;
                halo4Identity.PlayerModelUrl  = GetPlayerModelUrl(gamertag, pose: "posed");
                halo4Identity.TopCsr          = serviceRecord.TopSkillRank != null ? serviceRecord.TopSkillRank.CompetitiveSkillRank ?? 0 : 0;
                halo4Identity.TotalKills      = serviceRecord.GameModes.Sum(m => m.TotalKills);

                sqlStorage.Halo4Identities.AddOrUpdate(halo4Identity);
                sqlStorage.SaveChanges();
            }
        }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serviceRecord"></param>
        private static void AddPlayerToIdentities(ServiceRecord serviceRecord)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var gamertag     = serviceRecord.Player.Gamertag;
                var gamertagSafe = GamerIdentity.EscapeGamerId(gamertag);

                var gamerIdentity = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamertagSafe);
                if (gamerIdentity == null)
                {
                    gamerIdentity = new GamerIdentity
                    {
                        GamerId     = gamertag,
                        GamerIdSafe = gamertagSafe,
                        Type        = IdentityType.XblGamertag
                    };
                    sqlStorage.GamerIdentities.Add(gamerIdentity);
                    sqlStorage.SaveChanges();
                }

                var reachIdentity = sqlStorage.ReachIdentities.FirstOrDefault(h => h.GamerIdentity.Id == gamerIdentity.Id) ??
                                    new ReachIdentity();

                reachIdentity.GamerIdentity    = gamerIdentity;
                reachIdentity.ServiceTag       = serviceRecord.Player.ServiceTag;
                reachIdentity.PlayerModelUrl   = String.Format("https://spartans.svc.halowaypoint.com/players/{0}/Reach/spartans/fullbody", gamertag);
                reachIdentity.CompetitiveKills = serviceRecord.Player.MultiplayerKills;
                reachIdentity.Rank             = serviceRecord.Player.CurrentRankName;
                reachIdentity.TotalGames       = serviceRecord.Player.GamesTotal;

                if (serviceRecord.Player.MultiplayerDeaths > 0)
                {
                    var ratio = (float)serviceRecord.Player.MultiplayerKills / serviceRecord.Player.MultiplayerDeaths;
                    reachIdentity.KillDeathRatio = Math.Round(Convert.ToDouble(ratio), 2, MidpointRounding.AwayFromZero);
                }
                else
                {
                    reachIdentity.KillDeathRatio = serviceRecord.Player.MultiplayerKills;
                }

                sqlStorage.ReachIdentities.AddOrUpdate(reachIdentity);
                try
                {
                    sqlStorage.SaveChanges();
                }
                catch (Exception e)
                {
                }
            }
        }
Пример #3
0
        public ActionResult Destroy()
        {
            using (var sqlStorage = new SqlStorage())
            {
                var sessionIdentifier = Request.Cookies["SessionIdentifier"];
                if (sessionIdentifier != null)
                {
                    var sessionGuid = Guid.Parse(sessionIdentifier.Value);
                    var session     = sqlStorage.BranchSessions.Include(s => s.BranchIdentity).FirstOrDefault(s => s.Identifier == sessionGuid);
                    if (session != null)
                    {
                        sqlStorage.BranchSessions.First(s => s.Id == session.Id).Revoked = true;
                        sqlStorage.SaveChanges();
                    }
                }

                var myCookie = new HttpCookie("SessionIdentifier", "girl comes up to me and says \"what you drive?\" and i said \"BUGATTI\"")
                {
                    Expires = DateTime.UtcNow.AddDays(-69d)
                };
                Response.Cookies.Add(myCookie);

                return(RedirectToRoute("Welcome"));
            }
        }
Пример #4
0
        public ActionResult Create(CreateSessionViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            using (var sqlStorage = new SqlStorage())
            {
                // trimmin
                viewModel.Username = (viewModel.Username ?? "").Trim();

                var branchIdentity =
                    sqlStorage.BranchIdentities.FirstOrDefault(
                        i => i.Email.ToLower() == viewModel.Username.ToLower() || i.Username.ToLower() == viewModel.Username.ToLower());
                if (branchIdentity == null)
                {
                    ModelState.AddModelError("Username", "An Identity with that Username/Email doesn't exist.");
                    return(View(viewModel));
                }

                if (!Pbkdf2Crypto.ValidateHash(viewModel.Password, branchIdentity.PasswordHash, branchIdentity.PasswordSalt, branchIdentity.PasswordIterations))
                {
                    ModelState.AddModelError("Password", "Incorrect Password.");
                    return(View(viewModel));
                }

                // Create Session
                var ipAddress     = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, viewModel.RememberMe);
                sqlStorage.BranchSessions.Add(branchSession);
                branchIdentity.BranchIdentitySessions.Add(branchSession);

                // Set Cookie
                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return(RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username }));
            }
        }
Пример #5
0
        public ActionResult Create(CreateSessionViewModel viewModel)
        {
            if (!ModelState.IsValid) return View(viewModel);

            using (var sqlStorage = new SqlStorage())
            {
                // trimmin
                viewModel.Username = (viewModel.Username ?? "").Trim();

                var branchIdentity =
                    sqlStorage.BranchIdentities.FirstOrDefault(
                        i => i.Email.ToLower() == viewModel.Username.ToLower() || i.Username.ToLower() == viewModel.Username.ToLower());
                if (branchIdentity == null)
                {
                    ModelState.AddModelError("Username", "An Identity with that Username/Email doesn't exist.");
                    return View(viewModel);
                }

                if (!Pbkdf2Crypto.ValidateHash(viewModel.Password, branchIdentity.PasswordHash, branchIdentity.PasswordSalt, branchIdentity.PasswordIterations))
                {
                    ModelState.AddModelError("Password", "Incorrect Password.");
                    return View(viewModel);
                }

                // Create Session
                var ipAddress = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, viewModel.RememberMe);
                sqlStorage.BranchSessions.Add(branchSession);
                branchIdentity.BranchIdentitySessions.Add(branchSession);

                // Set Cookie
                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username });
            }
        }
Пример #6
0
        /// <summary>
        ///     Updates the stored spartan tokens used for authenticating with 343's backend api systems.
        /// </summary>
        /// <returns>A boolean saying if everything was</returns>
        public static bool UpdateAuthentication(AzureStorage storage)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var everythingWentGucci = false;
                var strResponse = "";
                var httpClient = new HttpClient();

                // Try up to 10 times
                for (var i = 0; i < 10; i++)
                {
                    var response = httpClient.Get(CloudConfigurationManager.GetSetting("SpartanTokenApi"));

                    if (response.StatusCode == HttpStatusCode.OK && !String.IsNullOrEmpty(response.RawText.Trim()))
                    {
                        try
                        {
                            strResponse = response.RawText;

                            var waypointToken = JsonConvert.DeserializeObject<Halo4Waypoint>(response.RawText);
                            if (waypointToken != null && !String.IsNullOrWhiteSpace(waypointToken.SpartanToken))
                            {
                                var authentication = new Models.Sql.Authentication
                                {
                                    Type = AuthenticationType.Halo4,
                                    IsValid = true,
                                    Key = waypointToken.SpartanToken
                                };
                                sqlStorage.Authentications.AddOrUpdate(a => a.Type, authentication);
                                sqlStorage.SaveChanges();

                                everythingWentGucci = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.ToString());
                            everythingWentGucci = false;
                        }
                    }

                    if (everythingWentGucci)
                        break;
                }

                if (everythingWentGucci)
                    return true;

                // make sure halo 4 auth row has been deleted
                var invalidAuthentication = sqlStorage.Authentications.FirstOrDefault(a => a.Type == AuthenticationType.Halo4);
                if (invalidAuthentication != null)
                {
                    invalidAuthentication.Key = null;
                    invalidAuthentication.IsValid = false;
                }

                // send glorious email!
                var text =
                    String.Format(
                        "Sup guys, {0}Halo 4's authenication failed to update. Might want to look into it. Below is the response the server recieved from the auth service: {0}{0}{1}{0}{0}Best Regards,{0}Branch",
                        Environment.NewLine, strResponse);

                new Web(new NetworkCredential(CloudConfigurationManager.GetSetting("SendGridUser"),
                    CloudConfigurationManager.GetSetting("SendGridPass"))).Deliver(
                        new SendGridMessage(new MailAddress("*****@*****.**"),
                            new[]
                            {
                                new MailAddress(CloudConfigurationManager.GetSetting("SendGridTo")),
                                new MailAddress("*****@*****.**"),
                            },
                            "[Halo 4] Authentication Failed", null, text));

                sqlStorage.SaveChanges();

                return false;
            }
        }
Пример #7
0
        public ActionResult Destroy()
        {
            using (var sqlStorage = new SqlStorage())
            {
                var sessionIdentifier = Request.Cookies["SessionIdentifier"];
                if (sessionIdentifier != null)
                {
                    var sessionGuid = Guid.Parse(sessionIdentifier.Value);
                    var session = sqlStorage.BranchSessions.Include(s => s.BranchIdentity).FirstOrDefault(s => s.Identifier == sessionGuid);
                    if (session != null)
                    {
                        sqlStorage.BranchSessions.First(s => s.Id == session.Id).Revoked = true;
                        sqlStorage.SaveChanges();
                    }
                }

                var myCookie = new HttpCookie("SessionIdentifier", "girl comes up to me and says \"what you drive?\" and i said \"BUGATTI\"")
                {
                    Expires = DateTime.UtcNow.AddDays(-69d)
                };
                Response.Cookies.Add(myCookie);

                return RedirectToRoute("Welcome");
            }
        }
Пример #8
0
        /// <summary>
        ///     Updates the stored spartan tokens used for authenticating with 343's backend api systems.
        /// </summary>
        /// <returns>A boolean saying if everything was</returns>
        public static bool UpdateAuthentication(AzureStorage storage)
        {
            using (var sqlStorage = new SqlStorage())
            {
                var everythingWentGucci = false;
                var strResponse         = "";
                var httpClient          = new HttpClient();

                // Try up to 10 times
                for (var i = 0; i < 10; i++)
                {
                    var response = httpClient.Get(CloudConfigurationManager.GetSetting("SpartanTokenApi"));

                    if (response.StatusCode == HttpStatusCode.OK && !String.IsNullOrEmpty(response.RawText.Trim()))
                    {
                        try
                        {
                            strResponse = response.RawText;

                            var waypointToken = JsonConvert.DeserializeObject <Halo4Waypoint>(response.RawText);
                            if (waypointToken != null && !String.IsNullOrWhiteSpace(waypointToken.SpartanToken))
                            {
                                var authentication = new Models.Sql.Authentication
                                {
                                    Type    = AuthenticationType.Halo4,
                                    IsValid = true,
                                    Key     = waypointToken.SpartanToken
                                };
                                sqlStorage.Authentications.AddOrUpdate(a => a.Type, authentication);
                                sqlStorage.SaveChanges();

                                everythingWentGucci = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError(ex.ToString());
                            everythingWentGucci = false;
                        }
                    }

                    if (everythingWentGucci)
                    {
                        break;
                    }
                }


                if (everythingWentGucci)
                {
                    return(true);
                }

                // make sure halo 4 auth row has been deleted
                var invalidAuthentication = sqlStorage.Authentications.FirstOrDefault(a => a.Type == AuthenticationType.Halo4);
                if (invalidAuthentication != null)
                {
                    invalidAuthentication.Key     = null;
                    invalidAuthentication.IsValid = false;
                }

                // send glorious email!
                var text =
                    String.Format(
                        "Sup guys, {0}Halo 4's authenication failed to update. Might want to look into it. Below is the response the server recieved from the auth service: {0}{0}{1}{0}{0}Best Regards,{0}Branch",
                        Environment.NewLine, strResponse);

                new Web(new NetworkCredential(CloudConfigurationManager.GetSetting("SendGridUser"),
                                              CloudConfigurationManager.GetSetting("SendGridPass"))).Deliver(
                    new SendGridMessage(new MailAddress("*****@*****.**"),
                                        new[]
                {
                    new MailAddress(CloudConfigurationManager.GetSetting("SendGridTo")),
                    new MailAddress("*****@*****.**"),
                },
                                        "[Halo 4] Authentication Failed", null, text));

                sqlStorage.SaveChanges();

                return(false);
            }
        }
Пример #9
0
        public ActionResult Index(CreateIdentityViewModel viewModel)
        {
            using (var sqlStorage = new SqlStorage())
            {
                if (!ModelState.IsValid)
                {
                    return(View(viewModel));
                }

                // Trimmin'
                viewModel.Email          = viewModel.Email.Trim();
                viewModel.FullName       = viewModel.FullName.Trim();
                viewModel.Gamertag       = viewModel.Gamertag.Trim();
                viewModel.Username       = viewModel.Username.Trim();
                viewModel.InvitationCode = viewModel.InvitationCode.Trim();

                // Validate uniqueness of Username and Email
                var user = sqlStorage.BranchIdentities
                           .FirstOrDefault(i =>
                                           i.Username.ToLower() == viewModel.Username.ToLower() ||
                                           i.Email.ToLower() == viewModel.Email.ToLower());
                if (user != null)
                {
                    ModelState.AddModelError("Username", "Either this username has already been taken, or that email has already been used.");
                    ModelState.AddModelError("Email", "Either this username has already been taken, or that email has already been used.");
                }

                // Validate Invite Code
                var invite =
                    sqlStorage.BranchIdentityInvitations.FirstOrDefault(
                        i => i.InvitationCode.ToLower() == viewModel.InvitationCode.ToLower() && !i.Used);
                if (invite == null)
                {
                    ModelState.AddModelError("InvitationCode", "This invite code has either been used or isn't valid. Sorry bae.");
                }

                // Check Password is identical
                if (viewModel.Password != viewModel.PasswordConfirm)
                {
                    ModelState.AddModelError("Password", "Your password and confirmation do not match.");
                }

                // Check Password Complexity
                var complexity = 0;
                if (Regex.IsMatch(viewModel.Password, @"\d+"))
                {
                    complexity++;
                }
                if (Regex.IsMatch(viewModel.Password, @"[a-z]+"))
                {
                    complexity++;
                }
                if (Regex.IsMatch(viewModel.Password, @"[A-Z]+"))
                {
                    complexity++;
                }
                if (Regex.IsMatch(viewModel.Password, @"[^a-zA-Z\d]+"))
                {
                    complexity++;
                }

                if (complexity < 2)
                {
                    ModelState.AddModelError("Password", "Your password is not complex enough.");
                }

                if (!ModelState.IsValid)
                {
                    viewModel.Password = viewModel.PasswordConfirm = "";
                    return(View(viewModel));
                }

                // All gucci, create Branch Identity
                var password       = Pbkdf2Crypto.ComputeHash(viewModel.Password, new Random().Next(1000, 1200));
                var branchIdentity = new BranchIdentity
                {
                    BranchRole               = sqlStorage.BranchRoles.First(r => r.Type == RoleType.User),
                    Email                    = viewModel.Email,
                    FullName                 = viewModel.FullName,
                    Username                 = viewModel.Username,
                    PasswordHash             = password.Hash,
                    PasswordIterations       = password.Iterations,
                    PasswordSalt             = password.Salt,
                    BranchIdentityInvitation = invite
                };

                // Set invite as used
// ReSharper disable once PossibleNullReferenceException
                invite.Used = true;

                // Check gamer ids
                GlobalStorage.H4Manager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                GlobalStorage.HReachManager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                var gamerIdSafe = GamerIdentity.EscapeGamerId(viewModel.Gamertag);
                var gamerId     = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamerIdSafe);
                if (gamerId != null)
                {
                    branchIdentity.GamerIdentity = gamerId;
                }
                sqlStorage.BranchIdentities.Add(branchIdentity);
                sqlStorage.SaveChanges();

                var ipAddress     = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, false);
                sqlStorage.BranchSessions.Add(branchSession);

                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return(RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username }));
            }
        }
Пример #10
0
        public ActionResult Index(CreateIdentityViewModel viewModel)
        {
            using (var sqlStorage = new SqlStorage())
            {
                if (!ModelState.IsValid) return View(viewModel);

                // Trimmin'
                viewModel.Email = viewModel.Email.Trim();
                viewModel.FullName = viewModel.FullName.Trim();
                viewModel.Gamertag = viewModel.Gamertag.Trim();
                viewModel.Username = viewModel.Username.Trim();
                viewModel.InvitationCode = viewModel.InvitationCode.Trim();

                // Validate uniqueness of Username and Email
                var user = sqlStorage.BranchIdentities
                    .FirstOrDefault(i =>
                        i.Username.ToLower() == viewModel.Username.ToLower() ||
                        i.Email.ToLower() == viewModel.Email.ToLower());
                if (user != null)
                {
                    ModelState.AddModelError("Username", "Either this username has already been taken, or that email has already been used.");
                    ModelState.AddModelError("Email", "Either this username has already been taken, or that email has already been used.");
                }

                // Validate Invite Code
                var invite =
                    sqlStorage.BranchIdentityInvitations.FirstOrDefault(
                        i => i.InvitationCode.ToLower() == viewModel.InvitationCode.ToLower() && !i.Used);
                if (invite == null)
                    ModelState.AddModelError("InvitationCode", "This invite code has either been used or isn't valid. Sorry bae.");

                // Check Password is identical
                if (viewModel.Password != viewModel.PasswordConfirm)
                    ModelState.AddModelError("Password", "Your password and confirmation do not match.");

                // Check Password Complexity
                var complexity = 0;
                if (Regex.IsMatch(viewModel.Password, @"\d+"))
                    complexity++;
                if (Regex.IsMatch(viewModel.Password, @"[a-z]+"))
                    complexity++;
                if (Regex.IsMatch(viewModel.Password, @"[A-Z]+"))
                    complexity++;
                if (Regex.IsMatch(viewModel.Password, @"[^a-zA-Z\d]+"))
                    complexity++;

                if (complexity < 2)
                    ModelState.AddModelError("Password", "Your password is not complex enough.");

                if (!ModelState.IsValid)
                {
                    viewModel.Password = viewModel.PasswordConfirm = "";
                    return View(viewModel);
                }

                // All gucci, create Branch Identity
                var password = Pbkdf2Crypto.ComputeHash(viewModel.Password, new Random().Next(1000, 1200));
                var branchIdentity = new BranchIdentity
                {
                    BranchRole = sqlStorage.BranchRoles.First(r => r.Type == RoleType.User),
                    Email = viewModel.Email,
                    FullName = viewModel.FullName,
                    Username = viewModel.Username,
                    PasswordHash = password.Hash,
                    PasswordIterations = password.Iterations,
                    PasswordSalt = password.Salt,
                    BranchIdentityInvitation = invite
                };

                // Set invite as used
            // ReSharper disable once PossibleNullReferenceException
                invite.Used = true;

                // Check gamer ids
                GlobalStorage.H4Manager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                GlobalStorage.HReachManager.GetPlayerServiceRecord(viewModel.Gamertag, true);
                var gamerIdSafe = GamerIdentity.EscapeGamerId(viewModel.Gamertag);
                var gamerId = sqlStorage.GamerIdentities.FirstOrDefault(g => g.GamerIdSafe == gamerIdSafe);
                if (gamerId != null)
                    branchIdentity.GamerIdentity = gamerId;
                sqlStorage.BranchIdentities.Add(branchIdentity);
                sqlStorage.SaveChanges();

                var ipAddress = Request.ServerVariables.Get("HTTP_CF_CONNECTING_IP") ?? Request.UserHostAddress;
                var branchSession = BranchSession.Create(ipAddress, Request.UserAgent, branchIdentity, false);
                sqlStorage.BranchSessions.Add(branchSession);

                var cookie = new HttpCookie("SessionIdentifier", branchSession.Identifier.ToString())
                {
                    Expires = branchSession.ExpiresAt
                };
                Response.SetCookie(cookie);
                sqlStorage.SaveChanges();

                return RedirectToRoute("BranchIdentityView", new { controller = "Home", action = "Index", slug = branchIdentity.Username });
            }
        }