public async Task Invoke(HttpContext context, LoginService loginService, LanguageService languageService, AppDatabase database)
        {
            var newRoleCode = context.Request.Query["role"].ToString();

            if (!Enum.TryParse <GroupType>(newRoleCode, out var newRole))
            {
                await _next(context);

                return;
            }

            var currentUser  = loginService.GetCurrentLoggedInUser(context);
            var newRoleGroup = currentUser?.Groups?.SingleOrDefault(g => g.GroupType == newRole);

            if (newRoleGroup != null)
            {
                currentUser.CurrentRole = newRoleGroup;
                database.SaveChanges();

                var url = new Uri($"{context.Request.Scheme}://{context.Request.Host}{loginService.GetStartingPage(currentUser)}{context.Request.QueryString}");
                context.Response.Redirect(url.RemoveQueryStringByKey("role"));
            }
            else
            {
                await _next(context);
            }
        }
Esempio n. 2
0
        public Transfer Post([FromBody] Transfer transfer)
        {
            var newTransfer = database.TransfersList.Add(transfer).Entity;

            database.SaveChanges();
            return(newTransfer);
        }
Esempio n. 3
0
        public ActionResult DeleteEntry([FromForm] int id)
        {
            var entry = EntrySet.SingleOrDefault(u => u.Id == id);

            if (entry == null)
            {
                return(BadRequest(new
                {
                    Error = true,
                    Message = "This user doesn't exist anymore."
                }));
            }

            if (entry is User && entry.Id == loginService.GetCurrentLoggedInUser(HttpContext).Id)
            {
                return(BadRequest(new
                {
                    Error = true,
                    Message = "Cannot delete the current user."
                }));
            }

            EntrySet.Remove(entry);
            database.SaveChanges();

            return(Ok());
        }
        public IActionResult UpdateNumbers(
            [FromServices] AppDatabase db,
            [FromBody] SportEventViewModel viewModel,
            [FromQuery, FromForm] long?id = null
            )
        {
            long queryId = id ?? (long)viewModel.Id;

            SportEvent model = db.Events.Where(x => x.Id == queryId).FirstOrDefault();

            if (model is null)
            {
                return(NotFound());
            }

            model.AwayTeamOdds = viewModel.AwayTeamOdds;
            model.HomeTeamOdds = viewModel.HomeTeamOdds;
            model.DrawOdds     = viewModel.DrawOdds;

            model.AwayTeamScore = viewModel.AwayTeamScore;
            model.HomeTeamScore = viewModel.HomeTeamScore;

            db.SaveChanges();

            return(Ok());
        }
Esempio n. 5
0
        public IActionResult Upload([FromServices] AppDatabase db)
        {
            IFormFile jsonFile = Request.Form.Files.SingleOrDefault(
                x =>
                x.Name == "export" &&
                Path.HasExtension(x.FileName) &&
                Path.GetExtension(x.FileName).Trim('.').ToLower() == "json"
                );

            if (jsonFile is null)
            {
                return(BadRequest(
                           error: "Request does not contain a single json file in 'export.'"
                           ));
            }

            string fileContent;

            using (var reader = new StreamReader(jsonFile.OpenReadStream(), Encoding.UTF8))
            {
                fileContent = reader.ReadToEnd();
            }

            SportEventViewModel[] eventViewModels =
                JsonConvert.DeserializeObject <SportEventViewModel[]>(fileContent);

            Upload_ClearDatabase(db);
            Upload_InsertData(db, eventViewModels);
            db.SaveChanges();

            return(Ok());
        }
Esempio n. 6
0
        public IHttpActionResult Post(Message message)
        {
            dbContext.Messages.Add(message);
            dbContext.SaveChanges();

            var m = dbContext.Messages.Count();

            return(Created(new Uri(Request.RequestUri + "/" + message.Id), message));
        }
Esempio n. 7
0
        public Task <bool> SignInWithCredentials(HttpContext context, string username, string password)
        {
            var user = database.Users
                       .Include(u => u.Groups)
                       .SingleOrDefault(u => u.LoginName == username);

            if (user == null)
            {
                return(Task.FromResult(false));
            }

            var passwordHasher = new PasswordHasher <User>();

            if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password) != PasswordVerificationResult.Success)
            {
                return(Task.FromResult(false));
            }

            string returnUrl = context.Request.Form["ReturnUrl"];

            if (string.IsNullOrEmpty(returnUrl) || returnUrl.Trim(' ', '/') == "Logout" || returnUrl.Trim(' ', '/') == "Login")
            {
                returnUrl = null;
            }

            user.LastLogin = DateTime.Now;

            database.SaveChanges();

            string startPage = GetStartingPage(user);

            if (startPage == null)
            {
                Console.Out.WriteLine("This user doesn't belong to a group, can't log in");
            }

            var claimsIdentity = new ClaimsIdentity(GetClaimsForUser(user), CookieAuthenticationDefaults.AuthenticationScheme);

            return(SignInWithClaims(context, new[] { claimsIdentity }, returnUrl ?? startPage)
                   .ContinueWith(_ => true));
        }
Esempio n. 8
0
        public ActionResult LockWeek([FromForm] int year, [FromForm] int month, [FromForm] int weekFirstDay)
        {
            var entries = GetEntriesForWeek(year, month, weekFirstDay);

            foreach (var entry in entries)
            {
                entry.IsLocked = true;
            }
            database.SaveChanges();
            return(Ok());
        }
        public ActionResult CreateAbsence([FromForm] int studentId, [FromForm] int subjectId, [FromForm] string comment,
                                          [FromForm] int semester, [FromForm] DateTime date)
        {
            var teacher = loginService.GetCurrentLoggedInUser(HttpContext);
            var student = database.Users.GetById(studentId);
            var absence = new Absence
            {
                Comment  = comment,
                Date     = date,
                Semester = semester,
                Student  = student,
                Teacher  = database.Users.GetById(teacher.Id),
                Subject  = database.Subjects.GetById(subjectId)
            };

            database.Absences.Add(absence);
            database.SaveChanges();

            emailService.SendNotification(absence, true);

            return(Ok(GetSummary(student, absence.Subject)));
        }
        public ActionResult GetClass(int classId, int subjectId, string summaryProviderTypeName)
        {
            var summaryProviderType          = typeof(Program).Assembly.GetTypes().FirstOrDefault(t => t.Name == summaryProviderTypeName);
            ISummaryProvider summaryProvider = null;

            if (summaryProviderType != null)
            {
                summaryProvider = ActivatorUtilities.CreateInstance(serviceProvider, summaryProviderType) as ISummaryProvider;
            }

            var currentUser = loginService.GetCurrentLoggedInUser(HttpContext);

            var group = database.Groups
                        .Include(g => g.Users)
                        .Include(g => g.FormMaster)
                        .GetById(classId);
            var users = group.Users
                        .OrderBy(u => u.FullName)
                        .AsEnumerable()
                        .Select(u => new
            {
                Id         = u.Id,
                FullName   = u.FullName,
                LoginName  = u.LoginName,
                PlatformId = u.PlatformId,
                Summary    = summaryProvider?.GetSummary(u, database.Subjects.GetById(subjectId))
            });

            // Update history
            var historyEntries = database.TeacherClassHistory
                                 .Include(h => h.Teacher)
                                 .Include(h => h.Class)
                                 .Where(h => h.Teacher.Id == currentUser.Id && h.Class.Id == classId)
                                 .ToList();

            database.TeacherClassHistory.RemoveRange(historyEntries);
            database.TeacherClassHistory.Add(new TeacherClassHistory
            {
                Class   = database.Groups.GetById(classId),
                Teacher = currentUser
            });
            database.SaveChanges();

            return(Ok(new
            {
                Users = users,
                IsFormMaster = group.FormMaster?.Id == currentUser.Id,
                FirstAvailableSubjectId = currentUser.TaughtSubjects.FirstOrDefault()?.Id ?? -1
            }));
        }
Esempio n. 11
0
        public ActionResult CreateDisciplinaryReport([FromForm] int studentId, [FromForm] int subjectId, [FromForm] string comment,
                                                     [FromForm] int points, [FromForm] int semester, [FromForm] DateTime date)
        {
            var teacher            = loginService.GetCurrentLoggedInUser(HttpContext);
            var student            = database.Users.GetById(studentId);
            var disciplinaryReport = new Disciplinary
            {
                Comment  = comment,
                Points   = points,
                Date     = date,
                Semester = semester,
                Student  = student,
                Teacher  = database.Users.GetById(teacher.Id),
                Subject  = database.Subjects.GetById(subjectId)
            };

            database.Disciplinary.Add(disciplinaryReport);
            database.SaveChanges();

            emailService.SendNotification(disciplinaryReport, true);

            return(Ok(GetSummary(student, disciplinaryReport.Subject)));
        }
        public ActionResult CreateGrade([FromForm] int studentId, [FromForm] int subjectId, [FromForm] int value, [FromForm] int semester, [FromForm] DateTime date,
                                        [FromForm] string isMidterm)
        {
            var teacher = loginService.GetCurrentLoggedInUser(HttpContext);
            var student = database.Users.GetById(studentId);
            var grade   = new Grade
            {
                Value     = value,
                Date      = date,
                Semester  = semester,
                IsMidterm = isMidterm == "on",
                Student   = student,
                Teacher   = database.Users.GetById(teacher.Id),
                Subject   = database.Subjects.GetById(subjectId)
            };

            database.Grades.Add(grade);
            database.SaveChanges();

            emailService.SendNotification(grade, true);

            return(Ok(GetSummary(student, grade.Subject)));
        }
 public void DeleteAdventure(int AdventureID)
 {
     try
     {
         var adventure = _context.Adventures.FirstOrDefault(s => s.adventureId == AdventureID);
         _context.Adventures.Remove(adventure);
         _context.SaveChanges();
         return;
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
         return;
     }
 }
Esempio n. 14
0
        static void Main(string[] args)
        {
            try
            {
                AppDatabase db     = new AppDatabase("public");
                Candle      candle = new Candle(1, "test1", "test2", DateTime.UtcNow, DateTime.UtcNow, 1, 2, 2, 1, 1, 1);
                db.Candles.Add(candle);
                int res = db.SaveChanges();
                Console.Out.Write(res);
            }
            catch (Exception e)
            {
                Console.Out.Write(e.Message);
            }

            //Class1 miCalse = new Class1();
        }
Esempio n. 15
0
        public JwtResponse Register([FromBody] User user)
        {
            //get the token
            var jwt        = new JwtSecurityToken();
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            //add user to database
            database.Users.Add(user);
            database.SaveChanges();

            //return to frontend
            return(new JwtResponse()
            {
                Token = encodedJwt
                , FirstName = user.FirstName
                , LastName = user.LastName
                , UserName = user.UserName
            });
        }
Esempio n. 16
0
        public async Task Invoke(HttpContext context, LoginService loginService, LanguageService languageService, AppDatabase database)
        {
            var newLangCode = context.Request.Query["lang"].ToString();
            var newCulture  = languageService
                              .GetAvailableCultures()
                              .FirstOrDefault(c => string.Equals(c.Name, newLangCode, StringComparison.InvariantCultureIgnoreCase));
            var currentUser = loginService.GetCurrentLoggedInUser(context);

            if (currentUser != null && newCulture != null)
            {
                currentUser.PreferredLanguage = newCulture.Name;
                database.SaveChanges();

                var url = new Uri($"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}");
                context.Response.Redirect(url.RemoveQueryStringByKey("lang"));
            }
            else
            {
                await _next(context);
            }
        }
        public void CreateNewCanvas()
        {
            var matrix = new ColorData[SIZE * SIZE];

            for (int i = 0; i < SIZE; i++)
            {
                for (int j = 0; j < SIZE; j++)
                {
                    matrix[(SIZE * i) + j] = new ColorData
                    {
                        RowIndex    = i,
                        ColumnIndex = j,
                        Hex         = "#ffffff"
                    };
                }
            }
            _context.Canvas.Add(new Canvas {
                ColorData = matrix
            });
            _context.SaveChanges();
        }
Esempio n. 18
0
        public ActionResult CreateOrUpdateNote([FromForm] int studentId, [FromForm] int subjectId, [FromForm] string text)
        {
            var teacher = loginService.GetCurrentLoggedInUser(HttpContext);
            var note    = database.Notes
                          .Include(n => n.Student)
                          .Include(n => n.Subject)
                          .Include(n => n.Teacher)
                          .SingleOrDefault(n => n.Student.Id == studentId && n.Teacher.Id == teacher.Id && n.Subject.Id == subjectId)
                          ?? new Note();

            note.Text    = text;
            note.Student = database.Users.GetById(studentId);
            note.Teacher = database.Users.GetById(teacher.Id);
            note.Subject = database.Subjects.GetById(subjectId);
            if (!database.Notes.Contains(note))
            {
                database.Notes.Add(note);
            }
            database.SaveChanges();
            return(Ok());
        }
Esempio n. 19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AppDatabase database, EmailService emailService)
        {
            HostEnvironment = env;

            app.UseLiveReload();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.Use(async(context, next) =>
            {
                await next();
                if (context.Response.StatusCode >= 400 && context.Response.StatusCode <= 499 && !context.Response.HasStarted)
                {
                    context.Request.Path = "/Error";
                    await next();
                }
            });
            app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    context.Context.Response.Headers.Add("Cache-Control", "no-cache, no-store");
                    context.Context.Response.Headers.Add("Expires", "-1");
                }
            });
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSession();
            app.UseRequestLocalization(app.ApplicationServices.GetService <IOptions <RequestLocalizationOptions> >().Value);
            app.UseMiddleware <LanguageChangeMiddleware>();
            app.UseMiddleware <EnsureSubjectMiddleware>();
            app.UseMiddleware <SubjectChangeMiddleware>();
            app.UseMiddleware <RoleChangeMiddleware>();
            app.UseMiddleware <PhpRedirectMiddleware>();
            app.UseMiddleware <AuthCookieTimeoutMiddleware>();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });

            database.Database.EnsureDeleted();
            database.Database.EnsureCreated();

            var gradeLevelKG = database.GradeLevels.Add(new GradeLevel
            {
                Name = "Kindergarten",
                RegistryConfiguration = new RegistryConfiguration
                {
                    StartTime = TimeSpan.FromHours(8),
                    Slots     = Enumerable.Range(0, 2).Select(_ => new RegistryTimeSlot
                    {
                        Duration = 1,
                        HasClass = true,
                        HasText  = true
                    }).Concat(new[]
                    {
                        new RegistryTimeSlot
                        {
                            Duration = 2,
                            HasClass = true,
                            HasText  = true
                        }
                    }).Concat(Enumerable.Range(0, 1).Select(_ => new RegistryTimeSlot
                    {
                        Duration = 1,
                        HasClass = true,
                        HasText  = true
                    })).Concat(new[]
                    {
                        new RegistryTimeSlot
                        {
                            Duration = 2,
                            HasClass = true,
                            HasText  = true
                        }
                    }).Concat(new[]
                    {
                        new RegistryTimeSlot
                        {
                            Duration = 2,
                            HasClass = true,
                            HasText  = true
                        }
                    }).Concat(new[]
                    {
                        new RegistryTimeSlot
                        {
                            Duration    = 3,
                            HasClass    = true,
                            HasText     = true,
                            CustomLabel = "Others"
                        }
                    }).ToList()
                }
            }).Entity;
            var gradeElementaryStep = database.GradeLevels.Add(new GradeLevel
            {
                Name = "Elementary (step)",
                RegistryConfiguration = new RegistryConfiguration
                {
                    StartTime = TimeSpan.FromHours(8),
                    Slots     = Enumerable.Range(0, 2).Select(_ => new RegistryTimeSlot
                    {
                        Duration = 1,
                        HasClass = true,
                        HasText  = true
                    }).Concat(new[]
                    {
                        new RegistryTimeSlot
                        {
                            Duration = 3,
                            HasClass = true,
                            HasText  = true
                        }
                    }).Concat(Enumerable.Range(0, 5).Select(_ => new RegistryTimeSlot
                    {
                        Duration = 1,
                        HasClass = true,
                        HasText  = true
                    })).ToList()
                }
            }).Entity;
            var gradeElementary = database.GradeLevels.Add(new GradeLevel
            {
                Name = "Elementary",
                RegistryConfiguration = new RegistryConfiguration
                {
                    StartTime = TimeSpan.FromHours(8),
                    Slots     = Enumerable.Range(0, 10).Select(_ => new RegistryTimeSlot
                    {
                        Duration   = 1,
                        HasClass   = true,
                        HasSubject = true,
                        HasText    = true
                    }).ToList()
                },
                EmailOnGradeAdded          = true,
                EmailOnGradeDeleted        = true,
                EmailOnAbsenceAdded        = true,
                EmailOnAbsenceDeleted      = true,
                EmailOnDisciplinaryAdded   = true,
                EmailOnDisciplinaryDeleted = true
            }).Entity;
            var gradeMiddle = database.GradeLevels.Add(new GradeLevel
            {
                Name = "Middle",
                RegistryConfiguration = new RegistryConfiguration
                {
                    StartTime = TimeSpan.FromHours(7),
                    Slots     = Enumerable.Range(0, 11).Select(_ => new RegistryTimeSlot
                    {
                        Duration   = 1,
                        HasClass   = true,
                        HasSubject = true,
                        HasText    = true,
                        HasPCO     = true
                    }).ToList()
                }
            }).Entity;

            database.SaveChanges();

            var adminGroup = database.Groups.Add(new Group {
                GroupType = GroupType.Admin, Name = "Administrators"
            });
            var teacherGroup = database.Groups.Add(new Group {
                GroupType = GroupType.Teacher, Name = "Teachers"
            });
            var adminUser = database.Users.Add(new User
            {
                FullName          = "Administrator",
                LoginName         = "admin",
                PasswordHash      = "AQAAAAEAACcQAAAAEBFsY1RMVJIl9QZM2pFvdjhJQbC/OwzYV+j3JaP2hXCnhaPIyHDBPXrF3Ye3tHxAmA==",
                LastLogin         = DateTime.Now,
                TeacherGradeLevel = gradeLevelKG
            });

            adminUser.Entity.Groups = new List <Group> {
                adminGroup.Entity, teacherGroup.Entity
            };
            var teacherUser = database.Users.Add(new User
            {
                FullName          = "Test Teacher",
                LoginName         = "tteacher1",
                PasswordHash      = "AQAAAAEAACcQAAAAEBFsY1RMVJIl9QZM2pFvdjhJQbC/OwzYV+j3JaP2hXCnhaPIyHDBPXrF3Ye3tHxAmA==",
                LastLogin         = DateTime.Now,
                TeacherGradeLevel = gradeElementary
            });

            teacherUser.Entity.Groups = new List <Group> {
                teacherGroup.Entity
            };

            var classGroup1 = database.Groups.Add(new Group {
                GroupType = GroupType.Class, GradeLevel = gradeElementary, Name = "IV.A"
            });
            var classGroup2 = database.Groups.Add(new Group {
                GroupType = GroupType.Class, GradeLevel = gradeMiddle, Name = "VII.B"
            });

            var s1 = database.Subjects.Add(new Subject {
                Name = "Programming", RegistryName = "I.T.", HasMidterm = true
            }).Entity;
            var s2 = database.Subjects.Add(new Subject {
                Name = "English", RegistryName = "Foreign language"
            }).Entity;

            s1.Classes = new List <Group> {
                classGroup1.Entity, classGroup2.Entity
            };
            s1.Teachers = new List <User> {
                adminUser.Entity
            };
            s2.Teachers = new List <User> {
                adminUser.Entity
            };

            adminUser.Entity.TaughtClasses = new List <Group> {
                classGroup1.Entity, classGroup2.Entity
            };
            teacherUser.Entity.TaughtClasses = new List <Group> {
                classGroup1.Entity, classGroup2.Entity
            };
            teacherUser.Entity.TaughtSubjects = new List <Subject> {
                s1, s2
            };

            classGroup1.Entity.FormMaster = adminUser.Entity;
            classGroup1.Entity.Subjects   = new List <Subject> {
                s1, s2
            };
            classGroup2.Entity.Subjects = new List <Subject> {
                s1, s2
            };

            database.SaveChanges();

            var student = database.Users.Add(new User
            {
                FullName          = $"Student_1",
                LoginName         = $"s1",
                PasswordHash      = "AQAAAAEAACcQAAAAEBFsY1RMVJIl9QZM2pFvdjhJQbC/OwzYV+j3JaP2hXCnhaPIyHDBPXrF3Ye3tHxAmA==",
                NotificationEmail = "*****@*****.**"
            }).Entity;

            student.Groups = new List <Group> {
                classGroup1.Entity
            };

            var rand = new Random();

            for (int i = 0; i < 20; i++)
            {
                database.Grades.Add(new Grade
                {
                    Student  = student,
                    Semester = rand.Next(0, 2) == 0 ? 1 : 2,
                    Teacher  = adminUser.Entity,
                    Value    = rand.Next(1, 10),
                    Date     = DateTime.Today - TimeSpan.FromDays(rand.Next(1, 230)),
                    Subject  = rand.Next(0, 2) == 0 ? s1 : s2
                });
                database.Absences.Add(new Absence
                {
                    Student  = student,
                    Semester = rand.Next(0, 2) == 0 ? 1 : 2,
                    Teacher  = adminUser.Entity,
                    Date     = DateTime.Today - TimeSpan.FromDays(rand.Next(1, 230)),
                    Subject  = rand.Next(0, 2) == 0 ? s1 : s2,
                    Comment  = Guid.NewGuid().ToString(),
                    Verified = rand.Next(0, 3) == 0
                });
                database.Disciplinary.Add(new Disciplinary
                {
                    Student  = student,
                    Semester = rand.Next(0, 2) == 0 ? 1 : 2,
                    Teacher  = adminUser.Entity,
                    Date     = DateTime.Today - TimeSpan.FromDays(rand.Next(1, 230)),
                    Subject  = rand.Next(0, 2) == 0 ? s1 : s2,
                    Comment  = Guid.NewGuid().ToString(),
                    Points   = 0 - rand.Next(1, 11)
                });
            }

            database.DisciplinaryPresets.Add(new DisciplinaryPreset {
                Text = "stupid", Value = -1
            });
            database.DisciplinaryPresets.Add(new DisciplinaryPreset {
                Text = "dumb f**k", Value = -10
            });

            database.RegistryEntries.Add(new RegistryEntry
            {
                Class      = classGroup1.Entity,
                Subject    = s1,
                Teacher    = adminUser.Entity,
                Text       = "asdasdasd",
                EntryDate  = DateTime.Now,
                ModifyDate = DateTime.Now,
                Date       = DateTime.Parse("2021-03-09 08:00:00")
            });
            database.RegistryEntries.Add(new RegistryEntry
            {
                Class      = classGroup1.Entity,
                Subject    = s1,
                Teacher    = adminUser.Entity,
                Text       = "qwe",
                EntryDate  = DateTime.Now,
                ModifyDate = DateTime.Now,
                Date       = DateTime.Parse("2021-03-10 09:00:00")
            });

            var properties = new DatabaseProperties(database);

            database.SaveChanges();

            emailService.TryConnecting();
        }
 public void Update(ApplicationUserentity entity)
 {
     _context.Entry(entity).State = EntityState.Modified;
     _context.SaveChanges();
 }