public override void CreateOrUpdateOrganization(RmUnifyOrganization organization, Source source)
        {
            using (var context = new UsersContext())
            {
                // Get the school (if it exists)
                School school = (from s in context.Schools
                              where s.RmUnifyOrganizationId == organization.Id
                              select s).SingleOrDefault();

                if (school == null)
                {
                    // School does not exist - create
                    school = new School()
                    {
                        RmUnifyOrganizationId = organization.Id,
                        DisplayName = organization.Name
                    };
                    context.Schools.Add(school);
                    context.SaveChanges();
                }
                else
                {
                    // School exists - update
                    if (school.Deleted != null || school.RmUnifyOrganizationId != organization.Id)
                    {
                        school.Deleted = null;
                        school.RmUnifyOrganizationId = organization.Id;
                        context.SaveChanges();
                    }
                }
            }
        }
        private void CreateOrUpdateUserData(RmUnifyUser rmUser)
        {
            using (var context = new UsersContext())
            {
                // Get the user (if they exist)
                UserProfile user = (from u in context.UserProfiles
                                    where u.UserName == rmUser.Id
                                    select u).SingleOrDefault();

                if (user == null)
                {
                    // User does not exist - create
                    School school = (from s in context.Schools
                                     where s.RmUnifyOrganizationId == rmUser.Organization.Id
                                     select s).SingleOrDefault();
                    var userdata = new
                    {
                        DisplayName = rmUser.DisplayName,
                        SchoolId = school.Id,
                        LastLogin = DateTime.Now
                    };
                    WebSecurity.CreateUserAndAccount(rmUser.Id, Guid.NewGuid().ToString(), userdata);
                }
                else
                {
                    // User exists - update
                    // We don't need to worry about the user moving school as we are using rmUser.Id
                    // (which will change if the user moves school) rather than rmUser.PersonId (which may not)
                    if (rmUser.DisplayName != user.DisplayName)
                    {
                        user.DisplayName = rmUser.DisplayName;
                    }
                    if (user.Deleted != null)
                    {
                        user.Deleted = null;
                    }
                    user.LastLogin = DateTime.Now;
                    context.SaveChanges();
                }
            }
        }
        private void PurgeUsers()
        {
            DateTime minLastLogin = DateTime.Now.AddMonths(-3);
            DateTime minDeleted = DateTime.Now.AddMonths(-12);
            DateTime now = DateTime.Now;

            using (var context = new UsersContext())
            {
                var toDelete = from u in context.UserProfiles
                               where u.Deleted == null && u.LastLogin != null && u.LastLogin < minLastLogin
                               select u;
                if (toDelete.Count() > 0)
                {
                    foreach (var user in toDelete)
                    {
                        user.Deleted = now;
                    }
                    context.SaveChanges();
                }

                var toPurge = from u in context.UserProfiles
                              where u.Deleted != null && u.Deleted < minDeleted
                              select u;
                if (toPurge.Count() > 0)
                {
                    var rolesProvider = (SimpleRoleProvider)Roles.Provider;
                    var membershipProvider = (SimpleMembershipProvider)Membership.Provider;
                    foreach (var user in toPurge)
                    {
                        // TODO: delete any associated data in the app
                        rolesProvider.RemoveUsersFromRoles(new string[] { user.UserName }, rolesProvider.GetRolesForUser(user.UserName));
                        membershipProvider.DeleteUser(user.UserName, true);
                    }
                }
            }
        }
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }