public JsonResult ChangePassword(PasswordModel passwordModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    TenantOrganiserDbContext ctx = new TenantOrganiserDbContext();

                    User user = ctx.Users.Where(u => u.Email == User.Identity.Name).SingleOrDefault();

                    user.Password = passwordModel.Password;

                    ctx.SaveChanges();
                }
                catch (Exception e)
                {
                    return Json(new { errors = e });
                }
            }
            else
            {
                return Json(new { errors = GetErrorsFromModelState() });
            }

            // If we get this far, it was successful
            return Json(true);
        }
        public JsonResult ChangeEmail(string newEmail)
        {
            if (ModelState.IsValid)
            {
                string origEmail = User.Identity.Name;

                TenantOrganiserDbContext ctx = new TenantOrganiserDbContext();
                User user = ctx.Users.Where(p => p.Email == origEmail).SingleOrDefault();

                bool emailExists = ctx.Users.Where(p => p.Email == newEmail).Count() > 0;

                if (emailExists)
                    return Json(false);

                user.Email = newEmail;

                ctx.SaveChanges();

                return Login(newEmail, user.Password);
            }

            // If we got this far, something failed
            // return Json(new { errors = GetErrorsFromModelState() });
            return Json(false);
        }
 public SimpleMembershipInitializer()
 {
     try
     {
         TenantOrganiserDbContext ctx = new TenantOrganiserDbContext();
         WebSecurity.InitializeDatabaseConnection("TenantOrganiser", "User", "Id", "Email", autoCreateTables: false);
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
     }
 }
        public override bool ValidateUser(string email, string password)
        {
            try
            {
                User user = new TenantOrganiserDbContext().Users.Where(u => u.Email == email && u.Password == password).SingleOrDefault();

                // Facebook users cannot log in this way
                if (user.IsFacebookUser)
                    return false;

                if (user != null)
                    return true;
            }
            catch(Exception)
            {
                // Exception thrown so user does not exist
                return false;
            }

            // If we get this far, a user was not found
            return false;
        }
        public JsonResult FacebookLogin(string token)
        {
            String data = "";

            try
            {
                WebClient client = new WebClient();
                data = client.DownloadString("https://graph.facebook.com/me?access_token=" + token);
            }
            catch (Exception e)
            {
                return Json(false);
            }

            JObject jArray = JObject.Parse(data);

            // If the token was invalid or the facebook user had no email, return false
            if (jArray["error"] != null || jArray["email"] == null)
            {
                return Json(false);
            }

            // Get facebook user data
            String id = jArray["id"].ToString();
            String email = jArray["email"].ToString();
            String firstName = jArray["first_name"].ToString();
            String lastName = jArray["last_name"].ToString();

            // If email exists in database, set auth cookie
            TenantOrganiserDbContext ctx = new TenantOrganiserDbContext();

            User existingUser = ctx.Users.Where(u => u.Email == email).SingleOrDefault();

            // If user exists in the db but signed up manually
            if (existingUser != null && !existingUser.IsFacebookUser)
                return Json(false);

            // If the email already exists set auth token
            if (existingUser != null)
            {
                FormsAuthentication.SetAuthCookie(email, false);
                return Json(true);
            }

            using (WebClient Client = new WebClient())
            {
                Client.DownloadFile(
                    "https://graph.facebook.com/" + id + "/picture?type=large",
                    Server.MapPath("~/Content/images/profile_pictures/" + id + ".jpg"));
            }

            // Else register a new account with IsFacebookUser true and empty password
            User newUser = new User
            {
                Email = email,
                Password = "",
                FirstName = firstName,
                LastName = lastName,
                EmailNotifications = true,
                UserSettings = new UserSettings(),
                IsFacebookUser = true,
                DisplayPictureFileName = id.ToString() + ".jpg"
            };

            ctx.Users.Add(newUser);
            ctx.SaveChanges();

            FormsAuthentication.SetAuthCookie(email, false);

            return Json(true);
        }
        /// <summary>
        /// Create a new user in the database.
        /// </summary>
        /// <param name="user">Object representing the registering user.</param>
        private static void CreateNewUser(RegisterUser user, bool isFacebookUser)
        {
            TenantOrganiserDbContext ctx = new TenantOrganiserDbContext();

            // If the email already exists
            if (ctx.Users.Any(u => u.Email == user.Email))
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateEmail);
            }

            User newUser = new User
            {
                Email = user.Email,
                Password = user.Password,
                FirstName = user.FirstName,
                LastName = user.LastName,
                UserSettings = new UserSettings(),
                IsFacebookUser = isFacebookUser,
                EmailNotifications = true
            };

            ctx.Users.Add(newUser);
            ctx.SaveChanges();
        }
        public JsonResult UserSession()
        {
            string email = User.Identity.Name.ToString();

            User loggedInUser = null;

            // If session exists
            if (!String.IsNullOrEmpty(email))
            {
                loggedInUser = new TenantOrganiserDbContext().Users.Where(p => p.Email == email).SingleOrDefault();
                loggedInUser.Password = "";

                // Return logged in user as JSON object
                return Json(loggedInUser, JsonRequestBehavior.AllowGet);
            }

            // If we get this far, no session exists so return false
            return Json(false, JsonRequestBehavior.AllowGet);
        }
        public JsonResult UploadUrlPicture(string url)
        {
            using (WebClient Client = new WebClient())
            {
                try
                {
                    string loggedInUsername = User.Identity.Name.ToString();
                    TenantOrganiserDbContext ctx = new TenantOrganiserDbContext();
                    User user = ctx.Users.Where(p => p.Email == loggedInUsername).SingleOrDefault();

                    string emailHash = Utility.EmailToMd5Hash(user.Email);

                    try
                    {
                        // Download the new profile picture
                        Image img = Utility.ResizeImage(
                            Utility.DownloadImageFromUrl(url),
                            new Size(PROFILE_PIC_WIDTH, PROFILE_PIC_HEIGHT));

                        if (img == null)
                            return Json(false);

                        img.Save(Server.MapPath("~/Content/images/profile_pictures/" + emailHash + ".jpg"));

                        // If user already has a profile picture, delete it
                        if (user.DisplayPictureFileName != null)
                            System.IO.File.Delete(@Server.MapPath("~/Content/images/profile_pictures/" + user.DisplayPictureFileName + ".jpg"));

                        // Set db reference to the downloaded file
                        user.DisplayPictureFileName = emailHash + ".jpg";
                        ctx.SaveChanges();

                        return Json(true);
                    }
                    catch (Exception e) { }
                }
                catch (Exception e) { }
            }

            // If we got this far, something failed
            // return Json(new { errors = GetErrorsFromModelState() });
            return Json(false);
        }
        public JsonResult UploadFilePicture()
        {
            string loggedInUsername = User.Identity.Name.ToString();
            TenantOrganiserDbContext ctx = new TenantOrganiserDbContext();
            User user = ctx.Users.Where(p => p.Email == loggedInUsername).SingleOrDefault();

            string emailHash = Utility.EmailToMd5Hash(user.Email);

            try
            {
                HttpPostedFileBase hpf = Request.Files[0];

                if (hpf.ContentType != "image/jpeg")
                    return Json(false);

                // Download the new profile picture
                Image img = Utility.ResizeImage(Utility.CropImage(Image.FromStream(hpf.InputStream, true, true)), new Size(PROFILE_PIC_WIDTH, PROFILE_PIC_HEIGHT));

                img.Save(Server.MapPath("~/Content/images/profile_pictures/" + emailHash + ".jpg"));

                // If user already has a profile picture, delete it
                if (user.DisplayPictureFileName != null)
                    System.IO.File.Delete(@Server.MapPath("~/Content/images/profile_pictures/" + user.DisplayPictureFileName + ".jpg"));

                // Set db reference to the downloaded file
                user.DisplayPictureFileName = emailHash + ".jpg";
                ctx.SaveChanges();

                return Json(true);
            }
            catch (Exception e) { }

            return Json(false);
        }