public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                if (model.AcceptTerms)
                {
                    var user = new ApplicationUser {
                        UserName = model.UserName, Email = model.Email, Register = DateTime.Now, SlotForCompanion = 0
                    };
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                        // Send an email with this link
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                        await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                                                          $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");

                        // await _signInManager.SignInAsync(user, isPersistent: false);
                        _logger.LogInformation(3, "User created a new account with password.");

                        // Setup Gold
                        Gold gold = new Gold()
                        {
                            UserId = user.Id,
                            Number = 0
                        };

                        // Setup Artifacts
                        Artifacts artifact = new Artifacts()
                        {
                            UserId = user.Id,
                            Number = 10
                        };

                        using (var context = new SiteDbContext())
                        {
                            context.Add(artifact);
                            context.Add(gold);
                            await context.SaveChangesAsync();
                        }

                        // Redirect
                        return(RedirectToLocal(returnUrl));
                    }
                    AddErrors(result);
                }
                else
                {
                    ModelState.AddModelError("AcceptTerms", "You must accept the Terms of Use");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #2
0
        public async Task <bool> CreateAsync(CustomerEntity customer)
        {
            _context.Add(customer);
            await _context.SaveChangesAsync();

            return(true);
        }
        public async Task <IActionResult> Create([Bind("Id,Name")] SecurityGroup securityGroup)
        {
            if (ModelState.IsValid)
            {
                _context.Add(securityGroup);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(securityGroup));
        }
        public async Task <bool> CreateAsync(SiteEntity siteEntity)
        {
            if (!IsIDExistsAsync(siteEntity.SiteID).Result)
            {
                _context.Add(siteEntity);
                await _context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
        public async Task <IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = model.Username, Email = model.Email, Register = DateTime.Now, SlotForCompanion = 0
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);

                        // Setup Artifacts
                        Artifacts artifact = new Artifacts()
                        {
                            UserId = user.Id,
                            Number = 10
                        };

                        using (var context = new SiteDbContext())
                        {
                            context.Add(artifact);
                            await context.SaveChangesAsync();
                        }

                        // Redirect
                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
        // POST: AjaxRedeemGift
        public IActionResult AjaxRedeemGift(string id)
        {
            try
            {
                string jsonString = "[";
                using (var context = new SiteDbContext())
                {
                    var now = DateTime.Now;

                    Gifts gift = context.Gifts
                                 .Where(r => r.Code.Replace("-", "") == id && r.Active == true)
                                 .Select(r => r).SingleOrDefault();

                    if (gift == null)
                    {
                        throw new InvalidCastException("Your code is incorrect or has already been used.");
                    }
                    if (!(now >= gift.Start && now <= gift.End))
                    {
                        throw new InvalidCastException("Your code has expired or is not active yet.");
                    }

                    if (!gift.SinglePerAccount)
                    {
                        gift.Active = false;
                    }

                    // SinglePerAccount
                    if (gift.SinglePerAccount)
                    {
                        var AccountAlreadyUseIt = context.Deals_statistics
                                                  .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier) && r.Code.Replace("-", "") == id)
                                                  .Count();
                        if (AccountAlreadyUseIt > 0)
                        {
                            throw new InvalidCastException("The code already used by your account.");
                        }
                    }

                    Deals_statistics stats = new Deals_statistics()
                    {
                        UserId       = User.FindFirstValue(ClaimTypes.NameIdentifier),
                        Date         = DateTime.Now,
                        Code         = gift.Code,
                        Price        = 0,
                        Nb_Artifacts = (int)gift.Artifacts,
                        PaymentType  = "Gift Code",
                    };
                    context.Deals_statistics.Add(stats);

                    if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                    {
                        jsonString += "{ \"Success\" : \"true\",\"Title\" : \"Bravo\",\"Msg\" : \"Vous venez de valider votre code cadeau, les bonus ont été ajoutés à votre compte !\" }";
                    }
                    else
                    {
                        jsonString += "{ \"Success\" : \"true\",\"Title\" : \"Bravo\",\"Msg\" : \"You just validate your gift code, the bonuses have been added to your account !\" }";
                    }

                    // Artifacts
                    if (gift.Artifacts != null)
                    {
                        if (gift.Artifacts > 0)
                        {
                            Artifacts artifact = context.Artifacts
                                                 .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier))
                                                 .Select(r => r).FirstOrDefault();

                            artifact.Number += (int)gift.Artifacts;
                            context.Update(artifact);

                            if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                            {
                                jsonString += ",{\"Title\":\"Artefacts\", \"Text\":\"Vous obtenez " + gift.Artifacts + " artefats.\", \"Img\":\"/images/Game/artifact.svg\"}";
                            }
                            else
                            {
                                jsonString += ",{\"Title\":\"Artifacts\", \"Text\":\"You obtain " + gift.Artifacts + " artifacts.\", \"Img\":\"/images/Game/artifact.svg\"}";
                            }
                        }
                    }

                    // Xp
                    if (gift.Experiences != null)
                    {
                        if (gift.Experiences > 0)
                        {
                            Characters player = context.Characters
                                                .Where(r => r.UserId == User.FindFirstValue(ClaimTypes.NameIdentifier))
                                                .Select(r => r).FirstOrDefault();

                            player.Xp += (int)gift.Experiences;
                            context.Update(player);

                            if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                            {
                                jsonString += ",{\"Title\":\"Expérience\", \"Text\":\"Vous obtenez " + gift.Experiences + " d'expériences\", \"Img\":\"/images/Game/gold.svg\"}";
                            }
                            else
                            {
                                jsonString += ",{\"Title\":\"Experience\", \"Text\":\"You obtain " + gift.Experiences + " experiences.\", \"Img\":\"/images/Game/gold.svg\"}";
                            }
                        }
                    }

                    // Items
                    if (gift.Items != null)
                    {
                        IList <string> items = gift.Items.Split(',').ToList();
                        foreach (string item in items)
                        {
                            var itemExist = context.Items
                                            .Where(r => r.Id == Int32.Parse(item))
                                            .Select(r => r).FirstOrDefault();

                            if (itemExist != null)
                            {
                                Inventory inventory = new Inventory()
                                {
                                    UserId = User.FindFirstValue(ClaimTypes.NameIdentifier),
                                    ItemId = Int32.Parse(item)
                                };

                                if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                                {
                                    jsonString += ",{\"Title\":\"" + itemExist.TitleFr + "\", \"Text\":\"Vous trouverez l'objet dans votre inventaire.\", \"Img\":\"/uploads/game/cards/items/" + itemExist.Id + ".fr.svg\"}";
                                }
                                else
                                {
                                    jsonString += ",{\"Title\":\"" + itemExist.TitleEn + "\", \"Text\":\"You will find the item in your inventory.\", \"Img\":\"/uploads/game/cards/items/" + itemExist.Id + ".en.svg\"}";
                                }

                                context.Add(inventory);
                            }
                        }
                    }

                    context.Update(gift);
                    context.SaveChanges();
                }

                jsonString += "]";
                return(Json(JsonConvert.DeserializeObject(jsonString)));
            }
            catch (InvalidCastException e)
            {
                string jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Error\",\"Msg\" : \"" + e.Message + "\" }]";
                if (CultureInfo.CurrentCulture.TwoLetterISOLanguageName == "fr")
                {
                    if (e.Message == "Your code has expired or is not active yet.")
                    {
                        jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Erreur\",\"Msg\" : \"Votre code a expiré ou n'est pas encore actif.\" }]";
                    }
                    else if (e.Message == "Your code is incorrect or has already been used.")
                    {
                        jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Erreur\",\"Msg\" : \"Votre code est incorrect ou a déjà été utilisé.\" }]";
                    }
                    else if (e.Message == "The code already used by your account.")
                    {
                        jsonString = "[{ \"Success\" : \"false\",\"Title\" : \"Erreur\",\"Msg\" : \"Le code à déjà utilisé par votre compte.\" }]";
                    }
                }

                return(Json(JsonConvert.DeserializeObject(jsonString)));
            }
        }
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                string item;
                using (var context = new SiteDbContext())
                {
                    item = context.Conf
                           .Where(r => r.Id == 1)
                           .Select(r => r.Value).First();
                }

                if (item == "1" || item == "2")
                {
                    ApplicationUser userData = await _userManager.FindByNameAsync(model.UserName);

                    if (!await _userManager.IsInRoleAsync(userData, "Administrator"))
                    {
                        ModelState.AddModelError(string.Empty, Util.LanguageSelection("The site is currently under maintenance.", "Le site est actuellement en maintenance."));
                        return(View(model));
                    }
                }

                var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    ApplicationUser userData = await _userManager.FindByNameAsync(model.UserName);

                    Connections_statistics loginStat = new Connections_statistics()
                    {
                        UserId = userData.Id,
                        Date   = DateTime.Now
                    };

                    using (var context = new SiteDbContext())
                    {
                        context.Add(loginStat);
                        await context.SaveChangesAsync();
                    }

                    _logger.LogInformation(1, "User logged in.");

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction(nameof(GameController.Index), "Game"));
                    }
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning(2, "User account locked out.");
                    return(View("Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View(model));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }