public async Task <ActionResult <Customer> > Create(Customer customer) { _context.Customers.Add(customer); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer)); }
public async Task <IActionResult> PutFolder(long id, Folder folder) { if (id != folder.Id) { return(BadRequest()); } _context.Entry(folder).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FolderExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutVaerktoejskasse(int id, Vaerktoejskasse vaerktoejskasse) { if (id != vaerktoejskasse.VTKId) { return(BadRequest()); } _context.Entry(vaerktoejskasse).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!VaerktoejskasseExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutClazz([FromRoute] string id, [FromBody] Clazz clazz) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != clazz.Id) { return(BadRequest()); } _context.Entry(clazz).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ClazzExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutAccountRole([FromRoute] int id, [FromBody] AccountRole accountRole) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != accountRole.RoleId) { return(BadRequest()); } _context.Entry(accountRole).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AccountRoleExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutGeneralInformation([FromRoute] string id, [FromBody] GeneralInformation generalInformation) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != generalInformation.AccountId) { return(BadRequest()); } _context.Entry(generalInformation).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!GeneralInformationExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutInvoiceItem([FromRoute] int id, [FromBody] InvoiceItem invoiceItem) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != invoiceItem.ID) { return(BadRequest()); } _context.Entry(invoiceItem).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!InvoiceItemExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IHttpActionResult> PutSongs(int id, Songs songs) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != songs.SongId) { return(BadRequest()); } db.Entry(songs).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SongsExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <IActionResult> PutLegalCase(long id, LegalCase legalCase) { if (id != legalCase.Id) { return(BadRequest()); } _context.Entry(legalCase).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!LegalCaseExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutHaandvaerker(int id, Haandvaerker haandvaerker) { if (id != haandvaerker.HaandvaerkerId) { return(BadRequest()); } _context.Entry(haandvaerker).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!HaandvaerkerExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> PutAccount([FromRoute] string id, [FromBody] Account account) { _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != account.Id) { return(BadRequest("ID is not correct")); } if (await _context.Account.SingleOrDefaultAsync(a => a.Id == account.Id) != null) // Kiem tra account update co ton tai khong { var currentAccount = await _context.Account.SingleOrDefaultAsync(a => a.Id == account.Id); string tokenHeader = Request.Headers["Authorization"]; var token = tokenHeader.Replace("Basic ", ""); var tokenUser = await _context.Credential.SingleOrDefaultAsync(c => c.AccessToken == token); if (tokenUser.OwnerId == currentAccount.Id || (await _context.AccountRoles.SingleOrDefaultAsync(ar => ar.AccountId == tokenUser.OwnerId)).RoleId < (await _context.AccountRoles.SingleOrDefaultAsync(ar => ar.AccountId == currentAccount.Id)).RoleId || tokenUser.OwnerId == "ADMIN" ) { if (account.Password == null) { account.Password = currentAccount.Password; account.Salt = currentAccount.Salt; } else { if (PasswordHandle.GetInstance().EncryptPassword(account.Password, currentAccount.Salt) == currentAccount.Password) //Kiểm tra mật khẩu có trùng với mật khẩu cũ không, nếu trùng thì trả về lỗi { return(BadRequest(new ResponseError("New password do not same old password", 400))); } account.Salt = PasswordHandle.GetInstance().GenerateSalt(); account.Password = PasswordHandle.GetInstance().EncryptPassword(account.Password, account.Salt); } account.UpdatedAt = DateTime.Now; _context.Entry(account).State = EntityState.Modified; _context.Entry(account.GeneralInformation).State = EntityState.Modified; await _context.SaveChangesAsync(); return(Ok(_context.Account.Include(a => a.GeneralInformation).SingleOrDefault(a => a.Id == account.Id))); } } return(BadRequest(account.Id)); }
public async Task <IActionResult> PutFolder(long folderId, FolderForUpdateDTO folderDTO) { var folder = await _context.Folders.FindAsync(folderId); if (folder == null) { return(NotFound()); } folderDTO.ApplyToEntity(folder); await _context.SaveChangesAsync(); return(NoContent()); }
public async Task <ActionResult <User> > SignUp([FromBody] User newUser) { try { var duplicatedUser = await _context.Users.FirstOrDefaultAsync(u => u.Email == newUser.Email); if (duplicatedUser == null) { _context.Users.Add(newUser); await _context.SaveChangesAsync(); return(CreatedAtAction("SignUp", new { id = newUser.Id }, new { Firstname = newUser.FirstName, LastName = newUser.LastName, email = newUser.Email })); } else { return(BadRequest("Erro ao criar o usuário, email duplicado!")); } } catch (System.Exception) { return(BadRequest("Erro ao criar o usuário!")); } }
public async Task <ActionResult> ChangeName([FromBody] ChangeNamePayload changename) { if (HttpContext.User.HasClaim(claim => claim.Type == "Id")) { long id; if (!long.TryParse(HttpContext.User.Claims.FirstOrDefault(claim => claim.Type == "Id").Value, out id)) { return(Unauthorized("TOKEN INVALID PARSE ID FAILED")); } var user = _db.Users.Find(id); if (user == null) { return(Unauthorized("User Not Found")); } if (user.FirstName == changename.Firstname && user.LastName == changename.Lastname) { return(Ok()); } else { user.FirstName = changename.Firstname; user.LastName = changename.Lastname; } await _db.SaveChangesAsync(); return(Ok()); } return(Unauthorized("TOKEN INVALID")); }
public async Task <IActionResult> OnGetAsync() { var Timelists = await _context.Time.ToListAsync(); foreach (var x in Timelists) { try { if (x.Students == null) { x.Students = new List <int>(); x.NowNum = 0; } else { x.NowNum = x.Students.Count(); } } catch (NullReferenceException e) { throw e; } } await _context.SaveChangesAsync(); return(RedirectToPage("./Index")); }
public async Task <IActionResult> PutLegalCase(long folderId, string caseId) { if (!LegalCase.IsValidCaseId(caseId) || !FolderExists(folderId)) { return(NotFound()); } var legalCase = new LegalCase { FolderId = folderId, CaseId = Int64.Parse(caseId) }; _context.Cases.Add(legalCase); await _context.SaveChangesAsync(); return(NoContent()); }
public async Task <ActionResult> AddFriend([FromBody] long id) { var currentUser = HttpContext.User; if (currentUser.HasClaim(claims => claims.Type == "Id")) { long idUser; bool re = long.TryParse((currentUser.Claims.FirstOrDefault(c => c.Type == "Id").Value), out idUser); if (!re) { return(BadRequest("Can't parse id")); } try { var me = _db.Users.Include(user => user.Friends).Where(user => user.Id == idUser).Single(); //var follow1 = me.Following.FirstOrDefault(follow => follow.fo == id); var follow2 = me.Friends.FirstOrDefault(follow => follow.User1 == id); if (follow2 != null) { return((ActionResult) await acceptFollow(id)); } var userForFollow = _db.Users.Include(user => user.Friends).Include(user => user.notifications).Where(user => user.Id == id).Single(); me.Friends.Add(new Friend { User1 = idUser, User2 = id, status = false }); userForFollow.Friends.Add(new Friend { User1 = idUser, User2 = id, status = false }); userForFollow.newNotifications++; userForFollow.notifications.Add(new Notification { message = "sended you a follow request", idReceiver = userForFollow.Id, idSender = me.Id, }); await _db.SaveChangesAsync(); await sendNotifications(id); return(new JsonResult(new { status = "true", message = "Follow request sended" })); } catch (InvalidOperationException) { return(new JsonResult(new { status = "false", message = "user not found" })); } } return(BadRequest("Id not found")); }
public async Task <IActionResult> StudentLogin(LoginInformation loginInformation) { // find 1 account with matching username in Account var ac = await _context.Account.SingleOrDefaultAsync(a => a.Username == loginInformation.Username); if (ac != null) { var isCorrectClient = ac.Id.StartsWith("STU"); if (isCorrectClient) { // check matching password if (ac.Password == PasswordHandle.GetInstance().EncryptPassword(loginInformation.Password, ac.Salt)) { // check if account is deactivated if (ac.Status != AccountStatus.Deactive) { // check if account is logged in elsewhere var cr = await _context.Credential.SingleOrDefaultAsync(c => c.OwnerId == ac.Id); var accessToken = TokenHandle.GetInstance().GenerateToken(); if (cr != null) // if account has logged in { cr.AccessToken = accessToken; // update token _context.Credential.Update(cr); await _context.SaveChangesAsync(); return(Ok(accessToken)); } // create new credential with AccountId var firstCredential = new Credential { OwnerId = ac.Id, AccessToken = accessToken }; // save token _context.Credential.Add(firstCredential); await _context.SaveChangesAsync(); return(Ok(accessToken)); } return(Forbid("Your account is deactivated. Contact managers for more information.")); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("UserName or Password is incorrect", (int)HttpStatusCode.Forbidden))); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("Client is Wrong", (int)HttpStatusCode.Forbidden))); } Response.StatusCode = (int)HttpStatusCode.Forbidden; return(new JsonResult(new ResponseError("UserName or Password is incorrect", (int)HttpStatusCode.Forbidden))); }
public async Task <IActionResult> PutDrone([FromRoute] int id, [FromBody] Drone drone) { dbContext.Entry(drone).State = EntityState.Modified; try { await dbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DroneExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } string uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; string name = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value; int rid = Record.rid; var note = new Notes(uid, name, NewNotes, rid); _context.Note.Add(note); await _context.SaveChangesAsync(); NewNotes = ""; return(await OnGetAsync(rid)); }
public async Task <IActionResult> PostSubject([FromBody] List <Mark> marks) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } List <Mark> ListMark = new List <Mark>(); foreach (var mark in marks) { ListMark.Add(new Mark(mark.MarkType, mark.Value, mark.SubjectId, mark.AccountId)); _context.Mark.Add(new Mark(mark.MarkType, mark.Value, mark.SubjectId, mark.AccountId)); } await _context.SaveChangesAsync(); //return CreatedAtAction("GetSubject", new { id = subject.Id }, subject); return(Created("", ListMark)); }
public async Task<IActionResult> Post([FromForm]string dto) { string ip = Request.Headers["X-Real-IP"].FirstOrDefault(); RecordDto aDto = JsonConvert.DeserializeObject<RecordDto>(dto); if (aDto.IsFull() == false) return Ok(ApiResponse.Error("TICKET_INFO_INCOMPLETE")); if (aDto.Check() == false) return Ok(ApiResponse.Error("TICKET_NOT_LEGEAL")); Record OldRecord = await _context.Record.Where(r => r.id_student == aDto.id_student).OrderByDescending(r=>r.addedDate).FirstOrDefaultAsync(); if (OldRecord!=null) { if(OldRecord.InterviewID > 0) return Ok(ApiResponse.Error("TICKET_ALREADY_OK")); } Record newRecord = new Record(aDto, ip); _context.Record.Add(newRecord); //send yuyueTime sms int ans = Utils.TencentSMS.SendYuYueSMS(newRecord); SMS sms = new SMS() { id_student = newRecord.id_student, sendTime = DateTime.Now, OperatorName = "傻傻的bot", Status = ans, type = "预约时间" }; _context.Sms.Add(sms); await _context.SaveChangesAsync(); // SendAccpetSMS(newRecord); return Ok(ApiResponse.Success("success")); }
public async Task <IActionResult> Post([FromBody] RegistrationViewModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var userIdentity = _mapper.Map <AppUser>(model); var result = await _userManager.CreateAsync(userIdentity, model.Password); if (!result.Succeeded) { return(new BadRequestObjectResult(Errors.AddErrorsToModelState(result, ModelState))); } await _appDbContext.Customers.AddAsync(new Customer { IdentityId = userIdentity.Id, Location = model.Location }); await _appDbContext.SaveChangesAsync(); return(new OkObjectResult("Account created")); }
public async Task <IActionResult> OnPostAsync() { int rid = Record.rid; Record record = await _context.Record.FirstOrDefaultAsync(r => r.rid == rid); if (PullResponse) { try { await GetSMSResponse(Record.id_student, Record.phone); } catch (Exception e) { throw (e); } return(RedirectToPage("./SMS", new { id = Record.rid })); } SMS sms = new SMS() { id_student = record.id_student, sendTime = DateTime.Now, OperatorName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value }; if (yuyue) { int ans = TencentSMS.SendYuYueSMS(record); sms.Status = ans; sms.type = "预约时间"; _context.Sms.Add(sms); await _context.SaveChangesAsync(); } else if (queren) { InterviewTime interview = await _context.Time.FirstOrDefaultAsync(r => r.ID == record.InterviewID); if (interview == null) { sms.Status = 0; sms.type = "未选择面试时间"; } else { int ans = TencentSMS.SendQueRenSms(record, interview); sms.Status = ans; sms.type = "确认时间"; } _context.Sms.Add(sms); await _context.SaveChangesAsync(); } else if (zuizhong) { if (record.status == Status.Pending) { sms.Status = 0; sms.type = "面试结果还未确认"; } else if (record.status == Status.Fail) { int ans = TencentSMS.SendFailSMS(record); sms.Status = ans; sms.type = "发送失败短信"; } _context.Sms.Add(sms); await _context.SaveChangesAsync(); } return(await OnGetAsync(rid)); }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } if (username == _config["ADMIN_USERNAME"] && password == _config["ADMIN_PASSWORD"]) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username)); identity.AddClaim(new Claim(ClaimTypes.Name, "纳新系统管理员")); identity.AddClaim(new Claim(ClaimTypes.Sid, "0")); identity.AddClaim(new Claim(ClaimTypes.Role, "admin")); identity.AddClaim(new Claim(EvaClaimTypes.IsManager, "true")); var Iprincipal = new ClaimsPrincipal(identity); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, Iprincipal, new AuthenticationProperties { IsPersistent = true, AllowRefresh = true } ); return(RedirectToPage("/Index")); } var NowSecret = EvaCryptoHelper.Password2Secret(password); long stuID = 0; if (!long.TryParse(username, out stuID)) { return(RedirectToPage("/Account/Denied")); } var query = from _user in _context.User where _user.stuID == stuID select _user; var user = await query.AsNoTracking().FirstOrDefaultAsync(); //need use xms login service if (user == null) { Login login_Stu = new Login(username, password); //post login information to xms.zjueva.net and receive the response with string string ansString = LoginHelp.PostMoths(LoginURL, login_Stu); JObject ansJson = (JObject)JsonConvert.DeserializeObject(ansString); //error and Denied if (ansJson["status"].ToString() == "error") { return(RedirectToPage("/Account/Denied")); } else if (ansJson["status"].ToString() == "success") { User add_user = new User() { stuID = long.Parse(ansJson["data"]["stuid"].ToString()), Name = ansJson["data"]["name"].ToString(), Secret = login_Stu.GetSHASecret(), isManager = login_Stu.isManager() }; _context.User.Add(add_user); await _context.SaveChangesAsync(); //add new user to DB and now continue to create cookie; user = add_user; //this user is correct and don't use the follow "else" } } if (user.Secret == NowSecret) { var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.Name, user.Name)); identity.AddClaim(new Claim(ClaimTypes.Sid, user.Uid)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username)); if (user.isManager) { identity.AddClaim(new Claim(EvaClaimTypes.IsManager, "true")); identity.AddClaim(new Claim(ClaimTypes.Role, "manager")); } else { identity.AddClaim(new Claim(ClaimTypes.Role, "user")); } var Iprinciple = new ClaimsPrincipal(identity); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, Iprinciple, new AuthenticationProperties { IsPersistent = true, AllowRefresh = true } ); return(RedirectToPage("/Records/Index")); } //if user change his secret in XMS else { Login login_Stu = new Login(username, password); //post login information to xms.zjueva.net and receive the response with string string ansString = LoginHelp.PostMoths(LoginURL, login_Stu); JObject ansJson = (JObject)JsonConvert.DeserializeObject(ansString); //error and Denied if (ansJson["status"].ToString() == "error") { return(RedirectToPage("/Account/Denied")); } else { //change the secret in DB user = await _context.User.FirstOrDefaultAsync(r => r.stuID == stuID); user.Secret = login_Stu.GetSHASecret(); _context.Attach(user).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { return(NotFound()); } return(RedirectToPage("/Index")); } } }