Esempio n. 1
0
        // GET: Student
        public async Task <IActionResult> Index()
        {
            ApplicationUserCourse actCourse = null;
            Course course   = null;
            var    courseId = 0;

            var currentUser = await _userManager.GetUserAsync(HttpContext.User);

            if (currentUser != null)
            {
                actCourse = _context.UserCourse.FirstOrDefault(c => c.ApplicationUserId == currentUser.Id);
            }

            if (actCourse != null)
            {
                courseId = actCourse.CourseId;
                course   = await _context.Course
                           .Include(m => m.Modules)
                           .ThenInclude(ma => ma.ModuleActivities)
                           .ThenInclude(ma => ma.ActivityType)
                           .Include(au => au.ApplicationUsers)
                           .FirstOrDefaultAsync(m => m.Id == courseId);

                ViewData["Rubrik"] = course.Name;
            }
            else
            {
                ViewData["Rubrik"] = "Du verkar inte gå på någon kurs - kontakta din lärare eller skolan";
            }

            return(View(course));
        }
        // GET: Courses
        public async Task <IActionResult> CourseStudents()
        {
            ApplicationUser currentUser = await _userManager.GetUserAsync(HttpContext.User);

            ApplicationUserCourse actCourse = _context.UserCourse.FirstOrDefault(c => c.ApplicationUserId == currentUser.Id);
            Course classMates;

            classMates = await _context
                         .Course
                         .Include(aus => aus.ApplicationUsers)
                         .ThenInclude(au => au.ApplicationUser)
                         .FirstOrDefaultAsync(c => c.Id == _context
                                              .UserCourse
                                              .FirstOrDefault(u => u.ApplicationUserId == _userManager
                                                              .GetUserId(HttpContext.User)
                                                              .ToString())
                                              .CourseId);

            if (classMates != null)
            {
                ViewData["Rubrik"] = "Klasskompisar på";
            }
            else
            {
                ViewData["Rubrik"] = "Du verkar inte gå på någon kurs - kontakta din lärare eller skolan";
            }

            return(View(classMates));
        }
Esempio n. 3
0
        /// <summary>
        /// if a user purchase this course, then enroll this user to the course
        /// </summary>
        public void Enroll(ApplicationUser user, Order order)
        {
            // add user purchase record
            var purchasedCourse = ApplicationUserCourse.Create(user, order);

            UserPurchases.Add(purchasedCourse);
            // increse enrollment
            EnrollmentCount += 1;
        }
Esempio n. 4
0
        public async Task RegisterUser(string userId, int courseId)
        {
            var applicationUserForCourse = new ApplicationUserCourse()
            {
                ApplicationUserId = userId,
                CourseId          = courseId
            };

            this.applicationUsersForCourses.Add(applicationUserForCourse);
            await this.applicationUsersForCourses.SaveChangesAsync();
        }
Esempio n. 5
0
        public Boolean CourseHandling(ApplicationUserCourse actCourse, string userId, int newCourseId)
        {
            Boolean success = false;

            // Boolean error = false;

            if (userId != "" && newCourseId >= 0)
            {
                if (actCourse == null)
                {
                    var newCourse = new ApplicationUserCourse
                    {
                        ApplicationUserId = userId,
                        CourseId          = newCourseId
                    };

                    _context.Add(newCourse);  // koppla till kurs
                    _context.SaveChanges();
                }
                else
                {
                    _context.Remove(actCourse);  // remove, update
                    _context.SaveChanges();

                    if (newCourseId > 0)    // bara update
                    {
                        actCourse.CourseId = newCourseId;
                        _context.Add(actCourse);
                        _context.SaveChanges();
                    }
                }
            }

            // if (error == false)
            success = true;

            return(success);
        }
Esempio n. 6
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    Name = Input.Name, UserName = Input.Email, Email = Input.Email
                };

                if (user != null)
                {
                    // Skapa användaren
                    var result = await _userManager.CreateAsync(user, Input.Password);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                        // Koppla användaren till en roll
                        var svar = await _userManager.AddToRoleAsync(user, Input.Role);

                        if (!svar.Succeeded)
                        {
                            throw new Exception(string.Join("\n", svar.Errors));
                        }

                        #region SendEmail
                        //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                        //var callbackUrl = Url.Page(
                        //    "/Account/ConfirmEmail",
                        //    pageHandler: null,
                        //    values: new { userId = user.Id, code = code },
                        //    protocol: Request.Scheme);

                        //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        // await _signInManager.SignInAsync(user, isPersistent: false);
                        #endregion

                        if (Input.CourseId > 0)  // Koppla användare till kurs
                        {
                            // Koppla användare till en kurs
                            var newCourse = new ApplicationUserCourse
                            {
                                ApplicationUserId = user.Id,
                                CourseId          = Input.CourseId
                            };

                            _context.Add(newCourse);
                            _context.SaveChanges();
                        }

                        if (returnUrl == "" || returnUrl == null)
                        {
                            string roll = "";
                            if (Input.Role == "Teacher")
                            {
                                roll = "lärare";
                            }
                            else
                            {
                                roll = "elev";
                            }

                            TempData["newUser"]     = "******" + roll;
                            TempData["newUserData"] = Input.Name + " (" + Input.Email + ")";

                            returnUrl = "/Identity/Account/Details?userEmail=" + Input.Email;
                        }
                        else
                        {
                            TempData["newUserData"] = "Skapade ny elev på kursen: " + Input.Name + " (" + Input.Email + ")";

                            returnUrl = returnUrl + "/" + Input.CourseId;  //  courseId=2&returnUrl=/Courses/Details
                        }

                        return(LocalRedirect(returnUrl));
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }

            // Skapa data vid fel
            if (Input.CourseId > 0)
            {
                // Bara student
                Input.Roles = new SelectList(_roleManager.Roles.Where(r => r.Name == "Student").ToList(), "Name", "Name", "Student");  // , "Student"
                // Bara rätt kurs i listan
                Input.Courses = new SelectList(_context.Course.Where(c => c.Id == Input.CourseId).ToList(), "Id", "Name", Input.CourseId);
                // Kursens namn
                CourseName = _context.Course.Where(c => c.Id == Input.CourseId).SingleOrDefault().Name.ToString();
            }
            else
            {
                // Lista roller
                Input.Roles = new SelectList(_roleManager.Roles, "Name", "Name");
                // Lista kurser
                Input.Courses = new SelectList(_context.Course.ToList(), "Id", "Name", Input.CourseId);
            }


            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 7
0
        public static async Task InitAsync(IServiceProvider services, string adminPW, string studentPW)
        {
            using (var context = new LMSWebContext(services.GetRequiredService <DbContextOptions <LMSWebContext> >()))
            {
                userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                roleManager = services.GetRequiredService <RoleManager <IdentityRole> >();


                fake = new Faker("sv");

                var roleNames = new[] { "Teacher", "Student" };

                foreach (var roleName in roleNames)
                {
                    if (await roleManager.RoleExistsAsync(roleName))
                    {
                        continue;
                    }

                    var role = new IdentityRole {
                        Name = roleName
                    };
                    var result = await roleManager.CreateAsync(role);

                    if (!result.Succeeded)
                    {
                        throw new Exception(string.Join("\n", result.Errors));
                    }
                }


                var TeacherEmail = "*****@*****.**";

                var foundTeacher = await userManager.FindByEmailAsync(TeacherEmail);

                if (foundTeacher != null)
                {
                    return;
                }

                var admin = new ApplicationUser
                {
                    UserName = "******",
                    Email    = TeacherEmail,
                };

                var addAdminResult = await userManager.CreateAsync(admin, adminPW);

                if (!addAdminResult.Succeeded)
                {
                    throw new Exception(string.Join("\n", addAdminResult.Errors));
                }

                var adminUser = await userManager.FindByEmailAsync(TeacherEmail);

                foreach (var role in roleNames)
                {
                    if (await userManager.IsInRoleAsync(adminUser, role))
                    {
                        continue;
                    }

                    var addToRoleResult = await userManager.AddToRoleAsync(adminUser, role);

                    if (!addToRoleResult.Succeeded)
                    {
                        throw new Exception(string.Join("\n", addToRoleResult.Errors));
                    }
                }



                var courses = new List <Course>();
                for (int i = 0; i < 5; i++)
                {
                    var date   = DateTime.Now;
                    var course = new Course
                    {
                        Title       = fake.Company.CatchPhrase(),
                        Description = fake.Hacker.Verb(),
                        StartDate   = date,
                        EndDate     = date.AddMonths(6),
                        Modules     = GetModules(10),
                        //Students = GetStudents(30)
                    };
                    courses.Add(course);
                }
                context.AddRange(courses);
                context.SaveChanges();


                var students = GetStudents(20);

                foreach (var student in students)
                {
                    var addStudentResult = await userManager.CreateAsync(student, studentPW);

                    if (!addStudentResult.Succeeded)
                    {
                        throw new Exception(string.Join("\n", addStudentResult.Errors));
                    }

                    var studentUser = await userManager.FindByEmailAsync(student.Email);

                    if (studentUser is null)
                    {
                        continue;
                    }
                    if (await userManager.IsInRoleAsync(studentUser, roleNames[1]))
                    {
                        continue;
                    }

                    var addToRoleResult = await userManager.AddToRoleAsync(studentUser, roleNames[1]);

                    if (!addToRoleResult.Succeeded)
                    {
                        throw new Exception(string.Join("\n", addToRoleResult.Errors));
                    }
                }


                var enrollist = new List <ApplicationUserCourse>();
                foreach (var s in students)
                {
                    var junktion = new ApplicationUserCourse
                    {
                        ApplicationUserId = s.Id,
                        CourseId          = courses[fake.Random.Int(0, 4)].Id
                    };
                    enrollist.Add(junktion);
                }
                context.AddRange(enrollist);
                context.SaveChanges();
                //var newStudentList = new List<ApplicationUser>();
                var randomInt = fake.Random.Int(1, 5);
                foreach (var c in courses)
                {
                    //for (int i = 0; i < 20; i++)
                    //{
                    //    var student1 = students[fake.Random.Int(0, 49)];
                    //    if (c.Students is null || !c.Students.Contains(student1))
                    //    {
                    //        newStudentList.Add(student1);
                    //    }
                    //}
                    //c.Students = newStudentList;
                    //c.Documents = GetDocuments(randomInt, c.Students.ToList());
                    c.Documents = GetDocuments(randomInt, students);
                    foreach (var m in c.Modules)
                    {
                        m.Documents = GetDocuments(randomInt, students);

                        foreach (var a in m.Activities)
                        {
                            a.Documents = GetDocuments(randomInt, students);
                        }
                    }
                }
                context.SaveChanges();
                await context.SaveChangesAsync();
            }
        }
Esempio n. 8
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null, string userEmail = "")
        {
            if (returnUrl == null)
            {
                returnUrl = "";
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            ApplicationUser user = await _userManager.FindByEmailAsync(Input.OrgEmail);

            if (user == null)
            {
                // return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
                return(NotFound($"Unable to load user with ID '{_userManager.FindByEmailAsync(Input.OrgEmail)}'."));
            }

            var memEmail = user.Email;
            var tmpRoles = await _userManager.GetRolesAsync(user);

            var orgRole = tmpRoles.First();

            Boolean changedUser    = false;
            Boolean changedRole    = false;
            Boolean changeCourse   = false;
            Boolean changePassword = false;

            if (Input.Email != user.Email)
            {
                memEmail      = Input.Email; // lagra email för retur
                user.UserName = Input.Email;
                user.Email    = Input.Email;
                changedUser   = true;
            }

            if (Input.Name != user.Name)
            {
                user.Name   = Input.Name;
                changedUser = true;
            }

            if (Input.Role != orgRole)
            {
                changedRole = true;
            }

            //if ( !(Input.Password == null || Input.Password == ""))
            //{
            //    if (string.Equals(Input.Password, Input.ConfirmPassword))
            //        changePassword = true;
            //}

            ApplicationUserCourse actCourse = _context.UserCourse.FirstOrDefault(c => c.ApplicationUserId == user.Id);

            if (actCourse != null && (Input.CourseId != actCourse.CourseId) || actCourse == null && Input.CourseId > 0)
            {
                changeCourse = true;
            }

            if (changedUser || changeCourse || changedRole || changePassword)
            {
                IdentityResult updateUser = null;
                IdentityResult updateRole = null;
                // IdentityResult updateCourse = null;
                // IdentityResult updatePassword = null;

                if (changedUser)
                {
                    updateUser = await _userManager.UpdateAsync(user);

                    if (!updateUser.Succeeded)
                    {
                        throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                    }
                }

                if (changeCourse)
                {
                    if (actCourse != null && (Input.CourseId != actCourse.CourseId))  // ändra/radera elev/kurs
                    {
                        CourseHandling(actCourse, user.Id, Input.CourseId);
                    }
                    else if (actCourse == null && Input.CourseId > 0)  // koppla elev till kurs
                    {
                        CourseHandling(actCourse, user.Id, Input.CourseId);
                    }
                }

                if (changedRole)
                {
                    // Koppla User från Role
                    updateRole = await _userManager.RemoveFromRoleAsync(user, orgRole);

                    if (!updateRole.Succeeded)
                    {
                        throw new Exception(string.Join("\n", updateRole.Errors));
                    }

                    // Koppla User till ny Role
                    updateRole = await _userManager.AddToRoleAsync(user, Input.Role);

                    if (!updateRole.Succeeded)
                    {
                        throw new Exception(string.Join("\n", updateRole.Errors));
                    }
                }

                //if (changePassword)  //--- AVSTÄNGD PGA OTILLRÄCKLIG INDATAKONTROLL ---//
                //{
                //    //if (PasswordValidator != null)
                //    //{
                //    //    var passwordResult = await PasswordValidator.ValidateAsync(password);
                //    //    if (!password.Result.Success)
                //    //        return passwordResult;
                //    //}


                //    var tmp = _userManager.PasswordHasher.HashPassword(user, Input.Password);
                //    updatePassword = await _userManager.UpdateAsync(user);
                //    if (!updatePassword.Succeeded)
                //    {
                //        throw new InvalidOperationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                //    }
                //    var token = await _userManager.GeneratePasswordResetTokenAsync(user);
                //    var resultPw = await _userManager.ResetPasswordAsync(user, token, Input.Password);
                //}

                //##### FELMEDDELANDE??? #####
                // ???
                // ???

                // TempData["newUser"] = "******" + Input.Name;  //  "Skapade användaren '" + Input.Name + "' (" + Input.Role + ")";
                TempData["newUser"]     = "******";
                TempData["newUserData"] = "";  // Input.Name + " (" + Input.Email + ")";

                if (returnUrl == "")
                {
                    return(LocalRedirect("/Identity/Account/Details?userEmail=" + user.UserName));     // /Identity/Account/[email protected]
                }
            }

            //--- Bygg utdata vid reload av formuläret ---

            // Roll/Roller
            user = await _userManager.FindByIdAsync(user.Id.ToString());

            var role = "";

            var roleType = await _userManager.GetRolesAsync(user);

            if (roleType != null)
            {
                role = roleType.ElementAt(0);
            }
            Input.Roles = new SelectList(_roleManager.Roles, "Name", "Name", role);

            // Kurs/Kurser
            var actCourse2 = _context.UserCourse.FirstOrDefault(c => c.ApplicationUserId == user.Id);

            if (actCourse2 != null)
            {
                Input.CourseId = actCourse2.CourseId;
            }
            else
            {
                Input.CourseId = 0;
            }

            var allCourses = from course in _context.Course
                             select new { Id = course.Id, Name = course.Name };

            Input.CourseList = new SelectList(allCourses, "Id", "Name", Input.CourseId);

            return(Page());
        }