public void OnActionExecuting(ActionExecutingContext filterContext) { try { string cookiename = FormsAuthentication.FormsCookieName + "Teacher"; var v = filterContext.HttpContext.Request.Cookies[cookiename].Value; FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(v);//解密 string userno = authTicket.UserData; TeacherID = userno; ProjectView.Models.ProjectReviewDBEntities PRDB = new Models.ProjectReviewDBEntities(); StudentUser su = PRDB.StudentUsers.SingleOrDefault(stu => stu.StuNoUserName == userno); if (su == null) { int tid = int.Parse(userno); TeacherUser tu = PRDB.TeacherUsers.SingleOrDefault(teu => teu.TeacherID == tid); if (su == null && tu == null) { filterContext.HttpContext.Response.Redirect("~/Student/Login"); } } } catch { filterContext.HttpContext.Response.Redirect("~/Student/Login"); } }
/// <summary> /// Update student /// </summary> /// <param name="studentUpdate"></param> /// <returns></returns> public async Task <StudentDto> UpdateStudent(StudentUpdateDto studentUpdate) { StudentUser user = db.StudentsRepository.Get(a => a.Id == studentUpdate.Id).FirstOrDefault(); if (user == null) { // 404, Not found. // No reason for an exception I think return(null); } StudentsConverter.UpdateStudentsPersonalData(user, studentUpdate); var result = await db.AuthRepository.UpdateUser(user); if (!result.Succeeded) { var ex = new UserUpdateException(result.Errors.ToArray()); ex.Data.Add("IdentityResultErrors", result.Errors.ToArray()); throw ex; } var updatedUser = db.StudentsRepository.Get(a => a.Id == studentUpdate.Id).FirstOrDefault(); return(StudentsConverter.StudentToStudentDto(updatedUser)); }
public async Task <IActionResult> CreateStudentAccount(CreateStudentAccountViewModel model) { if (context.Students.Any(x => x.NumberOfStudentBook == model.NumberOfStudentBook)) { ModelState.AddModelError("", $"Student with number {model.NumberOfStudentBook} is alredy exist."); } if (ModelState.IsValid) { StudentUser student = new StudentUser() { UserName = model.FirstName + "_" + model.SecondName + "_" + model.NumberOfStudentBook, Email = model.Email, GroupID = model.GroupID, FirstName = model.FirstName, LastName = model.SecondName, NumberOfStudentBook = model.NumberOfStudentBook }; var result = await Manager.CreateAsync(student); if (result.Succeeded) { var user = await Manager.FindByEmailAsync(student.Email) as StudentUser; try { var token = await Manager.GenerateEmailConfirmationTokenAsync(user); string link = $@"{(HttpContext.Request.IsHttps?"https":"http")}://{HttpContext.Request.Host}{Url.Action("Registration", "Account", new { area = "Student", Token = token, Magic = student.Id })}"; var mailmodel = new StRgsMailModel { user = user, link = link }; var msg = MailSender.HtmlEmailMesage("EmailRegistration", mailmodel); await MailSender.SendEmailAsync(student.Email, "Registration", msg); await Manager.AddToRoleAsync(student, "Student"); return(Redirect(model.returnUrl)); } catch (Exception e) { await Manager.DeleteAsync(user); ModelState.AddModelError("", e.Message); } } else { foreach (var item in result.Errors) { ModelState.AddModelError("", item.Description); } } } return(View(model)); }
public string CalTest(string id = "") { var dataParser = new DataParser(); dataParser.ParseAllData(); List <CustomEventMonth> months = null; var rnd = new Random(); var c = (SchoolCourses)rnd.Next(1, 10); //c = SchoolCourses.Programmering; var u = new StudentUser("tordtest", c, "second"); months = DataWrapper.Instance.GetEventsWithName(u, id, true, true, true, true); var page = string.Format("{0} - {1}, {2}\n", u.UserName, u.Course, u.ClassYear); foreach (var month in months) { page += "Month: " + month.GetMonthName() + "(" + month.GetEventTypeCount(EventType.Forelesning) + ")" + "<br>"; foreach (var week in month.Weeks) { page += " -- Week: " + week.WeekName + "(" + week.GetEventTypeCount(EventType.Forelesning) + ")" + "<br>"; foreach (var evnt in week.events) { page += " ---- Evnt(" + evnt.ID + "): " + evnt.StartDateTime + " - " + evnt.Subject.Name + " (" + evnt.Subject.Code + ") - " + evnt.EventTypeLabel + " - [" + evnt.YearLabelTest + "] - " + evnt.CoursesLabel + "<br>"; } } } return(page); }
/* * -for the following: * -when user presses back button the database retrieves information based on if IsTeacherUser or IsStudentUser is true * -the database returns the value of the game mode score and stores it temp user * -then a waittime function is called to give time for the database to send and recieve before the app continues on * -if both IsTeacherUser and IsStudentUser is false then user is a guest, then no database call is made and the scene changes */ public void BackToMenu() { if (Login_Scene_Script.IsTeacherUser == true) { User1.TeacherID_3 = Login_Scene_Script.LoginId; RestClient.Get <TeacherUser>("https://blocks-b1047.firebaseio.com/" + User1.TeacherID_3 + ".json").Then(response => { T_User = response; }); } else if (Login_Scene_Script.IsStudentUser == true) { User2.StudentID_3 = Login_Scene_Script.LoginId; RestClient.Get <StudentUser>("https://blocks-b1047.firebaseio.com/" + User2.StudentID_3 + ".json").Then(response => { S_User = response; }); StartCoroutine(WaitTime()); } else { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 2); Score.scoreValue = 0; Score2.scoreValue2 = 0; Score3.scoreValue3 = 0; I_B10_Score = 0; } }
private string getToken(StudentUser user) { if (user == null) { throw new ArgumentNullException("Cannot Generate Token on a null user"); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("userId", user.Id), new Claim("sid", user.StudentId.ToString()), new Claim(ClaimTypes.Role, "Student") }), Expires = DateTime.UtcNow.AddHours(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateEncodedJwt(tokenDescriptor); return(token); }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new StudentUser { UserName = model.UnistraCardID, UnistraCardId = model.UnistraCardID, Email = model.Email, FacultyId = model.FacultyId, YearId = model.YearID, StudentNameSurname = model.StudentNameSurname }; var result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await signInManager.SignInAsync(user, isPersistent : false); return(RedirectToAction("Index", "Home")); } foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return(View(model)); }
public void Login() //when login button is pressed { LoginId = LoginIdField.text; //takes the user input and puts it in the necessary values LoginPassword = LoginPasswordField.text; user.TeacherID_3 = LoginId; user.TeacherPassword_3 = LoginPassword; user2.StudentID_3 = LoginId; user2.StudentPassword_3 = LoginPassword; //the following takes the inputed login id and searches the database for a match //the response is then saved into a temperorary user if (LoginId != "" && LoginPassword != "") // checks to make sure input fields are filled { RestClient.Get <TeacherUser>("https://blocks-b1047.firebaseio.com/" + user.TeacherID_3 + ".json").Then(response => { T_user = response; }); RestClient.Get <StudentUser>("https://blocks-b1047.firebaseio.com/" + user2.StudentID_3 + ".json").Then(response => { S_user = response; }); StartCoroutine(WaitTime()); //calls a wait function } else //output error message to error_txt_message script { Error_txt_message.ErrorTxt.text = "Input Fields Are Empty"; } }
public List <CustomEventMonth> GetEventsWithUser(StudentUser user, bool includeBeforeToday) { var months = new List <CustomEventMonth>(); CustomEventMonth month = null; CustomEventWeek week = null; var addedIDs = new HashSet <long>(); foreach (var evnt in AllEvents) { if (!addedIDs.Contains(evnt.ID) && (user.Course == SchoolCourses.VisAlt || (evnt.Courses.Contains(user.Course) && evnt.IsYear(user.ClassYear)))) { // Skip event if event if before today if (includeBeforeToday == false && evnt.StartDateTime < DateTime.Today) { continue; } var m = AddEvent(evnt, ref month, ref week); if (m != null) { months.Add(m); addedIDs.Add(evnt.ID); } } } return(months); }
/// <summary> /// Gets all keywords from AllEvents (user specific, mainly for the autocomplete) /// </summary> public List <string> GetUserKeywords(StudentUser user) { var list = new List <string>(); foreach (var evnt in AllEvents) { if ((evnt.Courses.Contains(user.Course) && evnt.IsYear(user.ClassYear)) || user.Course == SchoolCourses.VisAlt) { string[] eventWords = { evnt.Subject.Name, evnt.RoomName, evnt.Teacher, evnt.Subject.Code, evnt.eventType.ToString(), evnt.GetMonthName() }; for (var i = 0; i < eventWords.Length; i++) { if (eventWords[i] != null) { var temp = eventWords[i].ToLower(); if (!list.Contains(temp)) { list.Add(temp); } } } } } list.Add("innlevering"); list.Add("eksamen"); list.Add("forelesning"); return(list); }
public async Task <IActionResult> Register(StudentRegisterViewModel vm) { if (ModelState.IsValid) { var user = new StudentUser() { UserName = vm.Email, Email = vm.Email, }; var result = await userManager.CreateAsync(user, vm.Password); if (result.Succeeded) { //await signinManager.SignInAsync(user, false); return(RedirectToAction("Index")); } else { foreach (var item in result.Errors) { ModelState.AddModelError(item.Code, item.Description); } } } return(View(vm)); }
// GET: Students/Register public ActionResult RegisterStudent() { StudentUser su = new StudentUser(); su.ProgList = GetPrograms(); return(View(su)); }
public void BackToMenu() { if (Login_Scene_Script.IsTeacherUser == true) { User1.TeacherID_3 = Login_Scene_Script.LoginId; Debug.Log("User1:" + User1.TeacherID_3); RestClient.Get <TeacherUser>("https://blocks-b1047.firebaseio.com/" + User1.TeacherID_3 + ".json").Then(response => { T_User = response; Debug.Log("T_User:"******"User2:" + User2.StudentID_3); RestClient.Get <StudentUser>("https://blocks-b1047.firebaseio.com/" + User2.StudentID_3 + ".json").Then(response => { S_User = response; Debug.Log("S_User:" + S_User.StudentID_3); }); StartCoroutine(WaitTime()); } else { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 6); AddScore5_25.scoreValue = 0; AddScore5_5.scoreValue2 = 0; AddScore5_1.scoreValue3 = 0; A_B5_Score = 0; } }
public StudentDataDto(StudentUser user) { Location = user.Location; Name = user.Name; Surname = user.Surname; Email = user.Email; }
public IActionResult StuMain() { IAppOperator appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); appOperator = StudentUser.GetOperator(); if (appOperator.IsLogined()) { ViewBag.LoginStatus = "已登录"; } else { ViewBag.LoginStatus = "未登录"; } ViewBag.User = LibHelper.JSON.Serialize(appOperator); //这是登录用户 return(View()); }
public StudentDataDto(StudentUser user) { Location = user.Location; Name = user.Name; Surname = user.Surname; Email = user.Email; }
public void Update() { /* * -the following determines what kind of account is using the app: student, teacher, or guest * -if either IsTeacherUser or IsStudentUser == true then database is accessed and users id is displayed * -if both IsTeacherUser or IsStudentUSer == false then "Guest" is displayed */ if (Login_Scene_Script.IsTeacherUser == true) { User1.TeacherID_3 = Login_Scene_Script.LoginId; RestClient.Get <TeacherUser>("https://blocks-b1047.firebaseio.com/" + User1.TeacherID_3 + ".json").Then(response => { T_User = response; }); ID_Text_Script.ID_text.text = T_User.TeacherID_3; //displays to text field } else if (Login_Scene_Script.IsStudentUser == true) { User2.StudentID_3 = Login_Scene_Script.LoginId; RestClient.Get <StudentUser>("https://blocks-b1047.firebaseio.com/" + User2.StudentID_3 + ".json").Then(response => { S_User = response; }); ID_Text_Script.ID_text.text = "Hello " + S_User.StudentID_3; //displays to text field } else { ID_Text_Script.ID_text.text = "Hello Guest"; } }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new StudentUser { UserName = Input.Email, Email = Input.Email, Name = Input.Name }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { if (!await _roleManager.RoleExistsAsync(SD.AdminUser)) { await _roleManager.CreateAsync(new IdentityRole(SD.AdminUser)); } // Add user in role await _userManager.AddToRoleAsync(user, SD.AdminUser); _logger.LogInformation("User created a new account with password."); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl }, 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>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public ActionResult DeleteConfirmed(string id) { StudentUser studentUser = db.Users.Find(id) as StudentUser; db.Users.Remove(studentUser); db.SaveChanges(); return(RedirectToAction("Index")); }
/// <summary> // 获取用户名 /// </summary> /// <returns></returns> public StudentUser GetUserNameForSerVice(string Josn) { StudentUser user = new StudentUser(); user = Newtonsoft.Json.JsonConvert.DeserializeObject <StudentUser>(Josn); return(user); }
[HttpPost] //form post request from StudentInfo view public async Task <IActionResult> StudentInfo(StudentUser su) { if (ModelState.IsValid) { //get current user object, set new form data to fields AppUser appUser = await GetCurrentUserAsync(); appUser.UserName = su.FirstName[0] + su.LastName; appUser.WctcID = su.WctcID; appUser.FirstName = su.FirstName; appUser.LastName = su.LastName; appUser.Email = su.Email; appUser.Gender = su.Gender; appUser.PhoneNumber = su.Phone; //update AspNetUser IdentityResult result = await userManager.UpdateAsync(appUser); //if update worked... if (result.Succeeded) { //update new student info su.UserID = appUser.Id; personContext.UpdateStudentInfo(su); if (su.TripId != null) { // Update to a redirect to AcceptedTripDetail/Trip.Id return(RedirectToAction("TripDetail", new { id = su.TripId })); } else { return(RedirectToAction("Index")); } } else { foreach (IdentityError error in result.Errors) { ModelState.AddModelError("", error.Description); } } } if (su.TripId != null) { // Update to a redirect to AcceptedTripDetail/Trip.Id return(RedirectToAction("TripDetail", new { id = su.TripId })); } else { //return RedirectToAction("Index"); //if there are errors in the student model, this is what will run //return RedirectToAction("StudentInfo"); //return View(su.TripId); return(StudentInfo(su.TripId)); } }
private async Task SignInAsync(StudentUser user, bool isPersistent) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); }
public ActionResult Edit([Bind(Include = "Id,Email,Location,Name,Surname")] StudentUser studentUser) { if (ModelState.IsValid) { db.Entry(studentUser).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(studentUser)); }
public ActionResult Create([Bind(Include = "Id,Email,Location,Name,Surname")] StudentUser studentUser) { if (ModelState.IsValid) { db.Users.Add(studentUser); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(studentUser)); }
/// <summary> /// Update full entity from dto before sending to the storage /// </summary> /// <param name="user"></param> /// <param name="dto"></param> public static void UpdateStudentsPersonalData(StudentUser user, StudentUpdateDto dto) { user.UserName = dto.UserName; user.FirstName = dto.FirstName; user.LastName = dto.LastName; user.Gender = dto.Gender; user.Email = dto.Email; user.PhoneNumber = dto.PhoneNumber; user.PlaceOfBirth = dto.PlaceOfBirth; user.DateOfBirth = dto.DateOfBirth; }
public IHttpActionResult GetStudentUser(int id) { StudentUser studentUser = db.Users.FirstOrDefault(u => u.Id == id) as StudentUser; if (studentUser == null) { return(NotFound()); } return(Ok(new StudentDataDto(studentUser))); }
protected void SetUp() { validUser = new StudentUser("spillprog2", "1234", "*****@*****.**", 2, SchoolCourses.Spillprogrammering); invalidUser = new StudentUser("spillprog2", "1", "*****@*****.**", 2, SchoolCourses.Spillprogrammering); userList = new List <StudentUser>(); userList.Add(new StudentUser("prog2", "1234", "*****@*****.**", 2, SchoolCourses.Programmering)); userList.Add(new StudentUser("prog3", "1234", "*****@*****.**", 3, SchoolCourses.Programmering)); userList.Add(new StudentUser("spillprog2", "1234", "*****@*****.**", 2, SchoolCourses.Spillprogrammering)); userList.Add(new StudentUser("spillprog3", "1234", "*****@*****.**", 3, SchoolCourses.Spillprogrammering)); }
public void LogOut() { cookie.DeleteCookies(); Session["keywords"] = null; dataParser.ParseAllData(); var user = new StudentUser("Not logged in", "", "", -1, SchoolCourses.VisAlt); var modelWrapper = CreateModelDataWrapper(DataWrapper.Instance.GetEventsWithName(user), user); CultureManager.UpdateCulture(HttpContext.Request); HttpContext.Response.Redirect(HttpContext.Request.UrlReferrer.AbsolutePath); }
private async Task LoadAsync(StudentUser user) { var email = await _userManager.GetEmailAsync(user); Email = email; Input = new InputModel { NewEmail = email, }; IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user); }
// GET: StaticStudent public ActionResult Index() { StudentUser studentUser = db.Users.OfType <StudentUser>().FirstOrDefault(su => su.Email == User.Identity.Name); if (studentUser != null) { List <GeneralUser> otherTypeOfUsers = studentUser is StudentUser?db.Users.OfType <ProviderUser>().Cast <GeneralUser>().ToList() : db.Users.OfType <StudentUser>().Cast <GeneralUser>().ToList(); ViewBag.Recommendations = new ProviderMatcher(studentUser).GetMatchingProvider(otherTypeOfUsers); } return(View(studentUser)); }
/// <summary> /// Retrieve a student by Id, another version /// </summary> /// <param name="studentId"></param> /// <returns></returns> public StudentDto GetStudentByIdDto(int studentId) { logger.Info("Service received request for returning a student by Id {studentId}", studentId); StudentUser student = GetStudentById(studentId); if (student == null) { return(null); } return(Converters.StudentsConverter.StudentToStudentDto(student)); }