public ActionResult ResendActivation(ResendActivationViewModel model)
        {
            // Recaptcha challenge
            if (!ReCaptchaPassed(Request))
            {
                ModelState.AddModelError("", "Failed to pass reCaptcha challenge.");
                return(View(model));
            }

            if (!string.IsNullOrEmpty(model.Email))
            {
                var user = ApplicationUserEngine.GetApplicationUser(model.Email);
                if (user != null)
                {
                    if (!string.IsNullOrEmpty(user.ActivationKey))
                    {
                        ApplicationUserEngine.ResendActivationEmail(user.Email);
                        return(View("ResendActivationSuccess", model: model.Email));
                    }

                    ModelState.AddModelError("", "This account has already been activated.");
                }
                else
                {
                    ModelState.AddModelError("", "This email address is not registered for an account.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid email address.");
            }

            return(View(model));
        }
        public ActionResult ViewCollection(int id)
        {
            var collection             = ApplicationUserEngine.GetCollection(id, out var error);
            var scryfallRequestEngine  = new ScryfallRequestEngine();
            var tcgPlayerRequestEngine = new TcgPlayerRequestEngine();
            var displayName            = ApplicationUserEngine.GetApplicationUser(collection.ApplicationUserId).DisplayName;
            var ownerDisplayName       = $"{displayName}#{collection.ApplicationUserId}";

            if (User.Identity.IsAuthenticated)
            {
                var email = ((ClaimsIdentity)User.Identity).Claims.First(i =>
                                                                         i.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress").Value;
                var user = ApplicationUserEngine.GetApplicationUser(email);

                ViewBag.IsOwner = user.Collections.Any(i => i.CollectionId == collection.CollectionId);
            }
            else
            {
                ViewBag.IsOwner = false;
            }

            // TODO: Up the view count and add it to an audit log for tracking so the system can't be cheated
            // TODO: create an audit log, lol

            if (!string.IsNullOrEmpty(error))
            {
                TempData["AlertMsg"] = "<br /><div class=\"alert alert-danger alert-dismissible\">" +
                                       "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                       $"<strong>{error}</div>";

                return(View("Error"));
            }

            var prices         = new List <double>();
            var pricingRequest = tcgPlayerRequestEngine.CardListPriceRequest(collection);

            // Get card data and prices
            foreach (var collectionCard in collection.Cards)
            {
                var price = pricingRequest.FirstOrDefault(i =>
                                                          i.ProductId == tcgPlayerRequestEngine.ProductIdRequest(collectionCard.Name, collectionCard.SetName) &&
                                                          i.SubTypeName == (collectionCard.Foil ? "Foil" : "Normal"));
                //var price = tcgPlayerRequestEngine.CardPriceRequest(scryfallList[index]?.Name, scryfallList[index]?.SetName)?.First(i =>
                //    collectionCard.Foil ? i.SubTypeName == "Foil" : i.SubTypeName == "Normal");
                prices.Add(price?.MidPrice ?? 0);
            }

            var model = new ViewCollectionModel
            {
                Collection       = collection,
                ScryfallList     = scryfallRequestEngine.GetCardList(collection),
                Prices           = prices,
                OwnerDisplayName = ownerDisplayName,
                OwnerId          = collection.ApplicationUserId
            };

            return(View("Collection", model));
        }
        public ActionResult Manage()
        {
            var email = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(i => i.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value;
            var id    = ((ClaimsIdentity)User.Identity)?.Claims.FirstOrDefault(i => i.Type == "Id")?.Value;

            var model = new ManageViewModel
            {
                Id   = Convert.ToInt32(id),
                User = ApplicationUserEngine.GetApplicationUser(email)
            };

            return(View(model));
        }
        public ActionResult ViewProfile(int id = 0)
        {
            var user = ApplicationUserEngine.GetApplicationUser(id);

            if (user != null)
            {
                var profile = new ViewProfileViewModel
                {
                    DisplayName = $"{user.DisplayName}#{user.Id}",
                    AboutMe     = user.AboutMe,
                    CreateDate  = user.CreateDate
                };

                return(View(profile));
            }

            TempData["AlertMsg"] = "<br /><div class=\"alert alert-danger alert-dismissible\">" +
                                   "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                   "<strong>This user does not exist or has a private profile.</div>";

            return(View("Error"));
        }
        public ActionResult EditCollection(int id)
        {
            var email = ((ClaimsIdentity)User.Identity).Claims.First(i => i.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress").Value;
            var user  = ApplicationUserEngine.GetApplicationUser(email);

            if (user.Collections.Any(i => i.CollectionId == id))
            {
                var collection = user.Collections.First(i => i.CollectionId == id);
                var model      = new EditCollectionModel
                {
                    Collection = collection,
                    RawList    = CardListParsingEngine.GetCardList(collection.Cards)
                };

                return(View("EditCollection", model));
            }

            TempData["AlertMsg"] = "<br /><div class=\"alert alert-danger alert-dismissible\">" +
                                   "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                   "<strong>You are not authorized to edit this collection.</div>";

            return(View("Error"));
        }
        public ActionResult Activate(ActivateAccountViewModel model)
        {
            if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.ActivationKey))
            {
                var user = ApplicationUserEngine.GetApplicationUser(model.Email);
                if (user != null)
                {
                    if (!string.IsNullOrEmpty(user.ActivationKey))
                    {
                        if (user.ActivationKey == model.ActivationKey)
                        {
                            user.ActivationKey = "";
                            ApplicationUserEngine.ActivateUser(user.Email);
                            ApplicationUserEngine.UpdateUserInCache(user.Email);

                            return(View("ActivationSuccess"));
                        }

                        ModelState.AddModelError("", "The activation key you provided is not correct.");
                    }
                    else
                    {
                        ModelState.AddModelError("", "This account has already been activated.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Email address not associated with an account.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Please fill out both form fields.");
            }

            return(View(model));
        }
        public ActionResult Register(RegisterViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                // already logged in
                return(View("Manage"));
            }

            if (!model.AgreeToGuidelines)
            {
                ModelState.AddModelError("",
                                         "You must agree to adhere to the community guidelines in order to register.");
                return(View(model));
            }

            // Recaptcha challenge
            if (!ReCaptchaPassed(Request))
            {
                ModelState.AddModelError("", "Failed to pass reCaptcha challenge.");
                return(View(model));
            }

            if (ModelState.IsValid)
            {
                if (ApplicationUserEngine.CreateAccount(model.Email, model.Password))
                {
                    return(View("RegisterSuccess", model: model.Email));
                }

                ModelState.AddModelError("", "That email address is already associated with a Forty Life account.");
                return(View(model));
            }

            ModelState.AddModelError("", "Registration has failed, please try again.");
            return(View(model));
        }
 public static void OnStartup()
 {
     ApplicationUserEngine.Initialize();
 }
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                // already logged in
                return(View("Manage"));
            }

            if (!UserAuthenticator.IsValid(model.Email, model.Password))
            {
                // invalid username or password
                ModelState.AddModelError("", "Invalid email or password.");
                ViewBag.ReturnUrl = returnUrl;
                return(View(model));
            }

            // load the user in memory
            var user = ApplicationUserEngine.GetApplicationUser(model.Email);

            // has the user authenticated their email address?
            if (!string.IsNullOrEmpty(user.ActivationKey))
            {
                ModelState.AddModelError("", "Your account has not been activated.");
                ViewBag.ReturnUrl = returnUrl;
                return(View(model));
            }

            // create our claim
            var ident = new ClaimsIdentity(
                new[]
            {
                // adding following 2 claim just for supporting default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, model.Email),
                new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                          "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),

                // Identity stuff to personalize the site
                new Claim(ClaimTypes.Email, model.Email),
                new Claim(ClaimTypes.Name, $"{user.DisplayName}#{user.Id}"),

                // extra data
                new Claim("Id", user.Id.ToString()),

                // add a role for a basic user
                // TODO: we'll need to add more roles for users for administrative permissions
                new Claim(ClaimTypes.Role, "User")
            },
                DefaultAuthenticationTypes.ApplicationCookie);

            HttpContext.GetOwinContext().Authentication
            .SignIn(new AuthenticationProperties {
                IsPersistent = false, ExpiresUtc = DateTimeOffset.Now.AddDays(1)
            },
                    ident);

            if (!string.IsNullOrEmpty(returnUrl))
            {
                return(Redirect(returnUrl)); // auth succeed, take em to their destination
            }

            return(RedirectToAction("Index", "Home")); // auth succeed and no return url, take em home
        }
        public ActionResult SaveCollection(EditCollectionModel model)
        {
            var email           = ((ClaimsIdentity)User.Identity).Claims.First(i => i.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress").Value;
            var collectionCards = CardListParsingEngine.ParseCardList(model.RawList, out var error);

            if (string.IsNullOrEmpty(model.Collection.Name))
            {
                model.Collection.Name = "Unnamed Collection";
            }
            else
            {
                model.Collection.Name = model.Collection.Name.Trim();
            }

            if (!string.IsNullOrEmpty(error))
            {
                TempData["AlertMsg"] = "<br /><div class=\"alert alert-danger alert-dismissible\">" +
                                       "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                       $"<strong>{error}</div>";

                return(View("EditCollection", model));
            }

            if (!CardListParsingEngine.VerifyCardList(collectionCards, out collectionCards, out error))
            {
                TempData["AlertMsg"] = "<br /><div class=\"alert alert-danger alert-dismissible\">" +
                                       "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                       $"<strong>{error}</div>";

                return(View("EditCollection", model));
            }

            model.Collection.Cards = collectionCards;

            // only change the date if it's not a new collection in order to keep the dates the same for the first save
            if (model.Collection.CollectionId > 0)
            {
                model.Collection.LastEditDate = DateTime.Now;
            }

            // make a backup of the list, since we have to null the original list in AddOrUpdateUserCollection() in order to save new lists
            var cardList = new List <CollectionCard>(model.Collection.Cards);

            // Save the collection details (this method nulls the collection list)
            ApplicationUserEngine.AddOrUpdateUserCollection(email, model.Collection, out error);

            // Only attempt to save the list if nothing is wrong with saving the collection
            if (string.IsNullOrEmpty(error))
            {
                ApplicationUserEngine.AddOrUpdateUserCollectionCard(model.Collection.CollectionId, cardList, out error);
            }

            // Some error saving the collection; display it
            if (!string.IsNullOrEmpty(error))
            {
                TempData["AlertMsg"] = "<br /><div class=\"alert alert-danger alert-dismissible\">" +
                                       "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                       $"<strong>{error}</div>";

                // clean the list up (remove blank lines)
                model.RawList = Regex.Replace(model.RawList, @"^\s+$[\r\n]*", string.Empty, RegexOptions.Multiline);

                ModelState.Clear();

                return(View("EditCollection", model));
            }

            ApplicationUserEngine.UpdateUserInCache(email);

            TempData["AlertMsg"] = "<br /><div class=\"alert alert-success alert-dismissible\">" +
                                   "<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">&times;</a>" +
                                   "<strong>The Collection was saved successfully.</div>";

            return(RedirectToAction("EditCollection", new { id = model.Collection.CollectionId }));
        }