Example #1
0
        // GET: Game
        public async Task <ActionResult> Index(Guid moduleId)
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var module = ModuleManager.GetModuleById(moduleId);

            if (moduleId == Guid.Empty)
            {
                ViewBag.errorMessage = "Could not find any in progress games, please begin a new game.";
                return(View("Error"));
            }

            var moduleVM = Mapper.Map <Module, ModuleViewModels>(module, opt =>
            {
                opt.Items["userId"]   = user?.Id ?? "";
                opt.Items["username"] = user?.UserName ?? "guest";
            });

            if (user == null)
            {
                moduleVM.Log    = CookieWrapper.GuestLog;
                moduleVM.Outbox = ParseLogEmails(CookieWrapper.GuestLog).Select(e => Mapper.Map <UserModuleEmailsViewModels>(e)).ToList();
            }
            else
            {
                ModuleManager.UpdateStatusById(ModuleManager.GetUserModuleByModuleAndUserId(module.Id, user.Id).Id, "In Progress");
            }

            return(View(moduleVM));
        }
        private async Task <OptionsViewModel> CreateOptions()
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var optionsVM = new OptionsViewModel();

            if (user != null)
            {
                optionsVM.Volume = user.MusicVolume ?? 50;
                optionsVM.Style  = user.MusicStyle ?? "mute";
            }
            else
            {
                int volume;
                try
                {
                    volume = System.Convert.ToInt32(CookieWrapper.MusicVolume);
                }
                catch
                {
                    volume = 50;
                }

                optionsVM.Volume = volume;
                optionsVM.Style  = CookieWrapper.MusicStyle ?? "mute";
            }

            return(optionsVM);
        }
        public async Task <bool> RegisterUser(SymHackUser user, string password, bool isTeacher, ModelStateDictionary modelState)
        {
            var result = await UserManager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                // Comment the following line to prevent log in until the user is confirmed.
                //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                                  + "before you can log in.";

                foreach (var module in ModuleManager.GetAllModules())
                {
                    ModuleManager.AddUserModuleByModuleAndUser(module, user);
                }

                //await UserManager.AddToRoleAsync(user.Id, isTeacher ? "Teacher" : "Student");
                await UserManager.AddToRoleAsync(user.Id, isTeacher? "PendingTeacher" : "Student");

                return(true);
            }

            AddErrors(result, modelState);
            return(false);
        }
Example #4
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new SymHackUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #5
0
        // GET: Teacher
        public async Task <ActionResult> List(TeacherViewModel teacher)
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            teacher.Students = user.Students.Select(student => Mapper.Map <StudentViewModel>(student)).ToList();

            return(PartialView("ListStudents", teacher));
        }
Example #6
0
        public async Task <ActionResult> Resume(HomeViewModels homeVM)
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var gameModules =
                homeVM.CurrentGame.Select(m => ModuleManager.GetUserModuleByModuleAndUserId(new Guid(m), user.Id));
            var currentModule = gameModules.FirstOrDefault(m => ModuleManager.GetStatusById(m.Id).Status.Equals("In Progress"));

            return(RedirectToAction("Index", new { moduleId = currentModule?.Module?.Id ?? Guid.Empty }));
        }
        public async Task <Guid> GetInProgressModule(List <string> currentGame)
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var gameModules =
                currentGame.Select(m => ModuleManager.GetUserModuleByModuleAndUserId(new Guid(m), user.Id));
            var currentModule = gameModules.FirstOrDefault(m => ModuleManager.GetStatusById(m.Id).Status.Equals("In Progress"));

            return(currentModule?.Module?.Id ?? Guid.Empty);
        }
 public void AddUserModuleByModuleAndUser(Module module, SymHackUser user)
 {
     _context.UserModules.Add(new UserModule()
     {
         Id     = Guid.NewGuid(),
         Module = module,
         User   = user,
         Status = _context.ModuleStatus.FirstOrDefault(ms => ms.Status.Equals("Not Started")),
         Log    = ""
     });
 }
Example #9
0
        // GET: Teacher
        public async Task <ActionResult> Index()
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            TeacherViewModel teacher = new TeacherViewModel
            {
                Students         = new List <StudentViewModel>(),
                RegisterStudents = new List <StudentViewModel>()
            };

            return(View(teacher));
        }
Example #10
0
        public async Task <ActionResult> Register(TeacherViewModel teacher)
        {
            if (ModelState.IsValid)
            {
                ModelState.Clear();

                var account_controller = DependencyResolver.Current.GetService <AccountController>();
                account_controller.ControllerContext =
                    new ControllerContext(this.Request.RequestContext, account_controller);

                var registration_fail = new List <StudentViewModel>();

                foreach (var student in teacher.RegisterStudents)
                {
                    // Set the default password - add functionality to force change on first login
                    var password = Membership.GeneratePassword(8, 2);

                    // Associate teacher with new student
                    SymHackUser teacherUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());

                    var user = Mapper.Map <SymHackUser>(student, opt => { opt.Items["teacher_user"] = teacherUser; });

                    if (await account_controller.RegisterUser(user, password, false, ModelState))
                    {
                        string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        var email_link = Url.Action("ConfirmEmail", "Account",
                                                    new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                        try
                        {
                            await UserManager.SendEmailAsync(user.Id, "Confirm your account",
                                                             "Please confirm your account by clicking <a href=\"" + email_link + "\">here</a>");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    else
                    {
                        registration_fail.Add(student);
                    }
                }

                teacher.RegisterStudents = registration_fail;
            }

            return(PartialView("RegisterStudents", teacher));
        }
Example #11
0
        private async Task <bool> CheckResponsePrerequisite(ModuleDictionary dictionary, Guid moduleId)
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            String log;

            if (user == null)
            {
                log = CookieWrapper.GuestLog;
            }
            else
            {
                log = ModuleManager?.GetUserModuleById(new Guid(user.Id))?.Log;
            }

            return(Regex.IsMatch(log, Regex.Unescape(dictionary.Prerequisite)));
        }
        public async Task <ActionResult> Options(OptionsViewModel options)
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user != null)
            {
                user.MusicStyle  = options.Style;
                user.MusicVolume = options.Volume;
                await UserManager.UpdateAsync(user);
            }
            else
            {
                CookieWrapper.MusicStyle  = options.Style;
                CookieWrapper.MusicVolume = options.Volume.ToString();
            }

            return(View());
        }
        private async Task <List <List <ModuleViewModels> > > GetModuleGroups()
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            var modules = ModuleManager.GetAllModules().Select(m => Mapper.Map <ModuleViewModels>(m, opt =>
            {
                opt.Items["userId"]   = user?.Id ?? "";
                opt.Items["username"] = user?.UserName ?? "guest";
            })).ToList();

            var initials     = modules.Where(m => new Guid(m.PrerequisiteId) == Guid.Empty).ToList();
            var moduleGroups = new List <List <ModuleViewModels> >();

            foreach (var module in initials)
            {
                var next = Mapper.Map <ModuleViewModels>(ModuleManager.GetNextModuleById(module.Id), opt =>
                {
                    opt.Items["userId"]   = user?.Id ?? "";
                    opt.Items["username"] = user?.UserName ?? "guest";
                });
                var group = new List <ModuleViewModels>()
                {
                    module
                };
                while (next != null)
                {
                    group.Add(next);
                    next = Mapper.Map <ModuleViewModels>(ModuleManager.GetNextModuleById(next.Id), opt =>
                    {
                        opt.Items["userId"]   = user?.Id ?? "";
                        opt.Items["username"] = user?.UserName ?? "guest";
                    });
                }

                moduleGroups.Add(group);
            }

            return(moduleGroups);
        }
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new SymHackUser {
                    UserName = new MailAddress(model.Email).User, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

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

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

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
Example #15
0
        public async Task <ActionResult> NewGame(HomeViewModels homeVM)
        {
            SymHackUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user != null)
            {
                var gameModules =
                    homeVM.CurrentGame.Select(m => ModuleManager.GetUserModuleByModuleAndUserId(new Guid(m), user.Id))
                    .ToList();

                foreach (var module in gameModules)
                {
                    ModuleManager.UpdateStatusById(module.Id, "Not Started");
                    ModuleManager.ClearLogById(module.Id);
                    ModuleManager.DeleteUserModuleEmailsById(module.Id);
                }
            }
            else
            {
                CookieWrapper.GuestLog = "";
            }

            return(RedirectToAction("Index", new { moduleId = homeVM.CurrentGame.First() }));
        }
Example #16
0
        public static PlayerStatsViewModel GetPlayerModel(SymHackUser user, ModuleManager moduleManager)
        {
            var player = new PlayerStatsViewModel()
            {
                Email = user.Email,
                Name  = user.FirstName + " " + user.LastName,
                Stats = new List <ModuleGroupViewModel>()
            };

            var modules  = moduleManager.GetAllModules();
            var initials = modules.Where(m => m.Prerequisite == null).ToList();

            var    moduleGroups = new List <OrderedDictionary>();
            string type         = "";

            foreach (var module in initials)
            {
                type = module.Type.Name;
                var next   = moduleManager.GetNextModuleById(module.Id);
                var group  = new OrderedDictionary();
                var status = moduleManager.GetUserModuleByModuleAndUserId(module.Id, user.Id).Status.Status;
                group.Add(module.Title, status.Equals("Not Started") ? -0.1 : (status.Equals("In Progress") ? 1 : 2));
                while (next != null)
                {
                    status = moduleManager.GetUserModuleByModuleAndUserId(next.Id, user.Id).Status.Status;
                    group.Add(next.Title, status.Equals("Not Started") ? -0.1 : (status.Equals("In Progress") ? 1 : 2));
                    next = moduleManager.GetNextModuleById(next.Id);
                }
                moduleGroups.Add(group);
            }

            int index = 0;

            foreach (var moduleGroup in moduleGroups)
            {
                var labels = moduleGroup.Keys;
                var data   = moduleGroup.Values;

                string[] colourList = new string[moduleGroup.Count],
                backgroundColours = new string[moduleGroup.Count],
                borderColours     = new string[moduleGroup.Count];
                for (int i = 0; i < moduleGroup.Count; i++)
                {
                    colourList[i]        = ChartColouring.ColourList[i % ChartColouring.ColourList.Length];
                    backgroundColours[i] =
                        ChartColouring.BackgroundColour[i % ChartColouring.BackgroundColour.Length];
                    borderColours[i] = ChartColouring.BorderColour[i % ChartColouring.BorderColour.Length];
                }

                player.Stats.Add(new ModuleGroupViewModel()
                {
                    Id               = index++,
                    Type             = type,
                    Labels           = labels.Cast <string>().ToArray(),
                    Data             = data.Cast <double>().ToArray(),
                    ColourList       = colourList,
                    BackgroundColour = backgroundColours,
                    BorderColour     = borderColours
                });
            }

            return(player);
        }
Example #17
0
        // Method shell from https://code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97
        private void CreateUsersAndRoles()
        {
            SymHackContext context = new SymHackContext();

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var userManager = new UserManager <SymHackUser>(new UserStore <SymHackUser>(context));


            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin role
                var role = new IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);

                //Here we create a Admin super user who will maintain the website
                var user = new SymHackUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";

                string userPWD = "Mohawk1234!";

                var chkUser = userManager.Create(user, userPWD);

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    var result1 = userManager.AddToRole(user.Id, "Admin");
                }
            }

            // Creating teacher role
            if (!roleManager.RoleExists("Teacher"))
            {
                var role = new IdentityRole();
                role.Name = "Teacher";
                roleManager.Create(role);

                // Create default teacher - in future move to a request admin must confirm
                var user = new SymHackUser();
                user.UserName = "";
                user.Email    = "*****@*****.**";

                string userPWD = "Mohawk1234!";

                var chkUser = userManager.Create(user, userPWD);

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    var result1 = userManager.AddToRole(user.Id, "Admin");
                }
            }

            // Creating student role
            if (!roleManager.RoleExists("Student"))
            {
                var role = new IdentityRole();
                role.Name = "Student";
                roleManager.Create(role);
            }

            // Creating pending teacher role
            if (!roleManager.RoleExists("PendingTeacher"))
            {
                var role = new IdentityRole();
                role.Name = "PendingTeacher";
                roleManager.Create(role);
            }
        }