public async Task <IdResponse> Login([FromBody] User user) { var ps = new IdResponse(); try { //find the user with this email var matchingUser = await db.Users.FirstOrDefaultAsync(u => u.Email == user.Email.ToLower()); if (matchingUser != null && PasswordHash.VerifyHashedPassword(matchingUser.Password, user.Password)) { //save the user's ID to the session -- ie. we're logged in await HttpContext.Session.LoadAsync(); HttpContext.Session.SetInt32("UserId", matchingUser.Id); await HttpContext.Session.CommitAsync(); ps.Id = matchingUser.Id; logger.LogTrace($"User {matchingUser.Id} has logged in"); } else { logger.LogWarning($"User {user.Email} failed to login " + $"{(matchingUser == null ? "no match" : "bad password")}"); ps.ResponseCodes.Add(ResponseCodes.IncorrectCredentials); } } catch (Exception ex) { logger.LogError(ex, $"Could not log in {user.Email}"); ps.ResponseCodes.Add(ResponseCodes.InternalError); } return(ps); }
private async Task ShouldSubmitFile() { //Arrange var responseObject = new IdResponse { Id = "Id" }; _apiFilesClient .Setup(x => x.Post <IdResponse>( It.IsAny <string>(), It.IsAny <SdkAuthorization>(), It.IsAny <MultipartFormDataContent>(), It.IsAny <CancellationToken>(), null ) ) .ReturnsAsync(responseObject); var response = await _accountsClient.SubmitFile(new AccountsFileRequest { File = "./Resources/checkout.jpeg", ContentType = null, Purpose = AccountsFilePurpose.Identification }); response.ShouldNotBeNull(); response.ShouldBe(responseObject); }
public async Task <IdResponse> UpdatePassword(int id, [FromBody] PasswordRequest request) { var ps = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var matchingUser = await db.Users.FirstOrDefaultAsync(u => u.Id == id); if (matchingUser != null && matchingUser.Id == userId) { if (request.OldPassword != null && PasswordHash.VerifyHashedPassword(matchingUser.Password, request.OldPassword)) { if (await PasswordCheck.IsStrong(request.NewPassword)) { matchingUser.Password = PasswordHash.HashPassword(request.NewPassword); await db.SaveChangesAsync(); ps.Id = id; logger.LogTrace($"Changed password for user {id}"); } else { logger.LogWarning($"attempt to use weak password {request.NewPassword}"); ps.ResponseCodes.Add(ResponseCodes.WeakPassword); } } else { logger.LogWarning($"incorrect password for user {id}"); ps.ResponseCodes.Add(ResponseCodes.InvalidPassword); } } else { logger.LogWarning( $"user {id} does not exist or attempt to modify another user's password by {userId}"); ps.ResponseCodes.Add(ResponseCodes.InvalidUser); } } else { logger.LogWarning("Attempt without logging in"); ps.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"failed to update password for {id}"); ps.ResponseCodes.Add(ResponseCodes.InternalError); } return(ps); }
public async Task <IdResponse> Post([FromBody] Exam exam) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { //make sure this user owns the question they want to attach a document to var ownsCourse = await doesOwnCourse(exam.CourseId, userId); if (ownsCourse && !string.IsNullOrWhiteSpace(exam.AuthenticationCode) && !string.IsNullOrWhiteSpace(exam.Name) && exam.Start > DateTime.UtcNow) { // ReSharper disable once MethodHasAsyncOverload db.Exams.Add(exam); await db.SaveChangesAsync(); resp.Id = exam.Id; logger.LogTrace($"Added exam {exam.Name} to course {exam.CourseId}"); } else { logger.LogWarning($"{userId} {(ownsCourse ? "" : "not")} owner; fields {exam}"); if (ownsCourse) { if (exam.Start < DateTime.UtcNow) { resp.ResponseCodes.Add(ResponseCodes.InvalidExamStart); } if (string.IsNullOrWhiteSpace(exam.AuthenticationCode) || string.IsNullOrWhiteSpace(exam.Name)) { resp.ResponseCodes.Add(ResponseCodes.InvalidExamFields); } } else { resp.ResponseCodes.Add(ResponseCodes.InvalidUser); } } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"Failed to add {exam.Name} to course {exam.CourseId}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public virtual IActionResult Post(string language, string sessionid, Request request) { return(this.RequestHandler(language, () => { IdResponse response = _logic.Insert(language, sessionid, request); return Ok(response); }, true)); }
// glennj 1/24/2014 // There is a similar function in the AWG classes /// <summary> /// Function operates on a given id string to decode information /// </summary> /// <param name="idString">Assumes valid Id string from an AWG</param> static IdResponse GetAwgInformation(string idString) { // idString = "TEKTRONIX,AWG70002,,FV:0.0.0045"; IdResponse idResponse = new IdResponse(); if (string.IsNullOrEmpty(idString)) { Assert.Fail("No ID string returned from AWG "); } //This is kind of cute, C# allows us to label the regex group we want with a name, instead of having to use an array index value. //Regex AwgFeatureMatcher = new Regex(@"TEKTRONIX,(?<type>AWG|HSG)(?<modelNumber>\d+)(?<class>.),(?<serial>.+),SCPI:(?<scpi>.+) FW:(?<fwVersion>.+)"); //To get the 70k to work it doesn't appear to add a SCPI field to its ID string var awgFeatureMatcher = new Regex(@"TEKTRONIX,(?<type>AWG|HSG)(?<modelNumber>\d+)(?<class>.*),(?<serial>.*),FV:(?<AppVersion>.+)"); //new Regex(@"TEKTRONIX,(?<type>AWG|HSG)(?<modelNumber>\d+)(?<class>.),(?<serial>.+),FV:(?<AppVersion>.+)"); Match match = awgFeatureMatcher.Match(idString.Trim()); //The ID Assert.IsTrue(match.Success, "The AWG ID string did not match the specified pattern. The actual value returned was: " + idString); // make sure you got a good match //Remember that since we have an instance of the AWG accessors for each one in the setup, these values are specific to that AWG idResponse.ModelNumber = match.Groups["modelNumber"].Value; idResponse.ClassLetter = match.Groups["class"].Value; idResponse.FamilyType = match.Groups["type"].Value; idResponse.SerialNumber = match.Groups["serial"].Value; idResponse.AppVersion = match.Groups["AppVersion"].Value; idResponse.ModelString = idResponse.FamilyType + idResponse.ModelNumber + idResponse.ClassLetter; var awgAppVersionMatcher = new Regex(@"(?<Major>\d+).(?<Minor>\d+).(?<Version>\d+)"); Match versionMatch = awgAppVersionMatcher.Match(idResponse.AppVersion); Assert.IsTrue(versionMatch.Success, "Unexpected version format" + idResponse.AppVersion); idResponse.AppVersionMajor = versionMatch.Groups["Major"].Value; idResponse.AppVersionMinor = versionMatch.Groups["Minor"].Value; idResponse.AppVersionVersion = versionMatch.Groups["Version"].Value; //ModelNumber is 7000 innstead of 70001 if (idResponse.ModelNumber.Length == 5) { if (idResponse.ModelNumber.Contains(Family70k)) { idResponse.Family = Family70k; // aka Pascal } else if (idResponse.ModelNumber.Contains(Family50k)) { idResponse.Family = Family50k; // aka Bode } else { idResponse.Family = "Unknown"; } } return(idResponse); }
public async Task <IdResponse> Put(int id, [FromBody] Student newStudent) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var student = await db.Students.FirstOrDefaultAsync(s => s.Id == id); if (student != null) { //make sure this user owns the question they want to attach a document to var ownsCourse = await doesOwnCourse(student.CourseId, userId); if (ownsCourse && !string.IsNullOrWhiteSpace(newStudent.Name) && !string.IsNullOrWhiteSpace(newStudent.Number)) { student.Name = newStudent.Name; student.Number = newStudent.Number; student.Email = newStudent.Email; await db.SaveChangesAsync(); resp.Id = student.Id; logger.LogTrace($"updated {id} with name {student.Name} number {student.Number}"); } else { logger.LogWarning($"{userId} {(ownsCourse ? "" : "not")} owner or invalid data {student}"); resp.ResponseCodes.Add( ownsCourse ? ResponseCodes.EmptyStudentFields : ResponseCodes.InvalidUser); } } else { logger.LogWarning($"student {id} not found"); resp.ResponseCodes.Add(ResponseCodes.EmptyStudentFields); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"failed to edit {id}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IdResponse> Put(int id, [FromBody] Document newDoc) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var doc = await db.Documents.FirstOrDefaultAsync(d => d.Id == id); if (doc != null) { //make sure this user owns the question they want to attach a document to var ownsQuestion = await doesOwnQuestion(doc.QuestionId, userId); if (ownsQuestion && !string.IsNullOrWhiteSpace(newDoc.PublicFileName)) { doc.PublicFileName = newDoc.PublicFileName; doc.Url = newDoc.Url; await db.SaveChangesAsync(); resp.Id = doc.Id; logger.LogTrace($"updated {id} with name {doc.PublicFileName}"); } else { logger.LogWarning( $"{userId} {(ownsQuestion ? "" : "not owner")} invalid new name: {newDoc.PublicFileName}"); resp.ResponseCodes.Add(string.IsNullOrWhiteSpace(newDoc.PublicFileName) ? ResponseCodes.EmptyDocumentName : ResponseCodes.InvalidUser); } } else { logger.LogWarning($"document {id} not found"); resp.ResponseCodes.Add(ResponseCodes.InvalidDocumentFields); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"failed to edit {id}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IdResponse> Put(int id, [FromBody] Question newQuestion) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var question = await db.Questions.FirstOrDefaultAsync(q => q.Id == id); if (question != null) { //make sure this user owns the question they want to attach a document to var ownsExam = await doesOwnExam(question.ExamId, userId); if (ownsExam && !string.IsNullOrWhiteSpace(newQuestion.Description)) { question.Description = newQuestion.Description; await db.SaveChangesAsync(); resp.Id = question.Id; logger.LogTrace($"updated {id} with name {question.Description}"); } else { logger.LogWarning( $"{userId} {(ownsExam ? "" : "not owner")} invalid new description: {newQuestion.Description}"); resp.ResponseCodes.Add(ownsExam ? ResponseCodes.InvalidQuestionFields : ResponseCodes.InvalidUser); } } else { logger.LogWarning($"question {id} not found"); resp.ResponseCodes.Add(ResponseCodes.InvalidQuestionFields); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"failed to edit {id}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IActionResult> GetAllSchedules() { var result = await QueryRouter.QueryAsync <SchedulesQuery, List <Schedule> >(new SchedulesQuery()); if (result == null) { return(new ObjectResult(IdResponse.Unsuccessful(""))); } return(new ObjectResult(result)); }
public async Task <IdResponse> Post([FromBody] Document document) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { //make sure this user owns the question they want to attach a document to var ownsQuestion = await doesOwnQuestion(document.QuestionId, userId); if (ownsQuestion) { if (!string.IsNullOrWhiteSpace(document.PublicFileName) && !string.IsNullOrWhiteSpace(document.Url)) { // ReSharper disable once MethodHasAsyncOverload db.Documents.Add(document); await db.SaveChangesAsync(); resp.Id = document.Id; logger.LogTrace($"Added {document.PublicFileName} to question {document.QuestionId}"); } else { logger.LogWarning($"Invalid properties in {document}"); resp.ResponseCodes.Add(ResponseCodes.InvalidDocumentFields); } } else { logger.LogWarning($"User {userId} does not own question {document.QuestionId}"); resp.ResponseCodes.Add(ResponseCodes.InvalidUser); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"Failed to add {document.PublicFileName} with link {document.Url} to question {document.QuestionId}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async ValueTask <object> Any(AsyncRedis request) { await using var redis = await GetRedisAsync(); await redis.IncrementAsync(nameof(AsyncRedis), request.Incr); var response = new IdResponse { Id = (await redis.GetAsync <int>(nameof(AsyncRedis))).ToString() }; return(response); }
public async Task <IdResponse> Put(int id, [FromBody] Course newCourse) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var course = await db.Courses.FirstOrDefaultAsync(c => c.Id == id && c.UserId == userId); if (course != null && !string.IsNullOrWhiteSpace(newCourse.Name) && newCourse.Year >= DateTime.UtcNow.Year) { course.Name = newCourse.Name; course.Semester = newCourse.Semester; course.Year = newCourse.Year; await db.SaveChangesAsync(); resp.Id = course.Id; logger.LogTrace($"Updated course {course.Id} : {course.Name}"); } else { logger.LogWarning( $"Could not find {id} or year: {newCourse.Year} and/or name: {newCourse.Name} invalid"); if (string.IsNullOrWhiteSpace(newCourse.Name)) { resp.ResponseCodes.Add(ResponseCodes.InvalidCourseName); } if (newCourse.Year < DateTime.UtcNow.Year) { resp.ResponseCodes.Add(ResponseCodes.NoEditOldCourse); } } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"Could not update {id}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IdResponse> Delete(int id) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var doc = await db.Documents.FirstOrDefaultAsync(d => d.Id == id); if (doc != null) { //make sure this user owns the question they want to attach a document to if (await doesOwnQuestion(doc.QuestionId, userId)) { //delete the record from the db db.Documents.Remove(doc); await db.SaveChangesAsync(); resp.Id = doc.Id; logger.LogTrace($"deleted {id}"); } else { logger.LogWarning($"{userId} not owner of document {id}"); resp.ResponseCodes.Add(ResponseCodes.InvalidUser); } } else { logger.LogWarning($"document {id} not found"); resp.Id = 1; } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { if (ex.InnerException is SqlException exception && exception.Number == 547) { resp.ResponseCodes.Add(ResponseCodes.DocumentInUse); logger.LogWarning("Attempt to delete record in use"); }
public async Task <IdResponse> Put(int id, [FromBody] School newSchool) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var school = await db.Schools.FirstOrDefaultAsync(s => s.Id == id); if (school != null) { if (!string.IsNullOrWhiteSpace(newSchool.Name)) { school.Name = newSchool.Name; await db.SaveChangesAsync(); resp.Id = school.Id; logger.LogTrace($"updated {id} with name {school.Name}"); } else { logger.LogWarning($"invalid data {school}"); resp.ResponseCodes.Add(ResponseCodes.InvalidSchoolFields); } } else { logger.LogWarning($"school {id} not found"); resp.ResponseCodes.Add(ResponseCodes.InvalidSchoolFields); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"failed to edit {id}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IdResponse> Delete(int id) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var student = await db.Students.FirstOrDefaultAsync(s => s.Id == id); if (student != null) { //make sure this user owns the student they want to delete if (await doesOwnCourse(student.CourseId, userId)) { db.Students.Remove(student); await db.SaveChangesAsync(); resp.Id = student.Id; logger.LogTrace($"deleted {id}"); } else { logger.LogWarning($"{userId} not owner of student {id}"); resp.ResponseCodes.Add(ResponseCodes.InvalidUser); } } else { resp.Id = 1; logger.LogWarning($"student {id} not found"); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { if (ex.InnerException is SqlException exception && exception.Number == 547) { resp.ResponseCodes.Add(ResponseCodes.StudentInUse); logger.LogWarning("Attempt to delete record in use"); }
private async Task ShouldUploadAccountsFile() { var fileRequest = new AccountsFileRequest { File = "./Resources/checkout.jpeg", ContentType = new ContentType("image/png"), Purpose = AccountsFilePurpose.Identification }; IdResponse fileResponse = await DefaultApi.AccountsClient().SubmitFile(fileRequest); fileResponse.ShouldNotBeNull(); fileResponse.Id.ShouldNotBeNull(); }
public async Task <IdResponse> UpdateEmployeeOnShift(Guid employeeId, Guid ShiftID) { using (var conn = new NpgsqlConnection(ConnectionString.GetConnectionString())) { conn.Open(); var result = conn.QueryAsync <Shift>("UPDATE shifts SET employee = WHERE id = @ShiftId"); //TODO : <-- Discuss SQL injection attack if (result.IsCompleted) { return(IdResponse.Successful(employeeId)); } return(IdResponse.Unsuccessful()); } }
public async Task <IdResponse> Post([FromBody] Question question) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { //make sure this user owns the question they want to attach a document to var ownsExam = await doesOwnExam(question.ExamId, userId); if (ownsExam && !string.IsNullOrWhiteSpace(question.Description)) { // ReSharper disable once MethodHasAsyncOverload db.Questions.Add(question); await db.SaveChangesAsync(); resp.Id = question.Id; logger.LogTrace($"Added {question.Description} to exam {question.ExamId}"); } else { logger.LogWarning($"{userId} not owner. Description: {question.Description}"); resp.ResponseCodes.Add(ownsExam ? ResponseCodes.InvalidQuestionFields : ResponseCodes.InvalidUser); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"Failed to add {question.Description} to exam {question.ExamId}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IdResponse> Post([FromBody] Student student) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { //make sure this user owns the question they want to attach a document to var ownsCourse = await doesOwnCourse(student.CourseId, userId); if (ownsCourse && !string.IsNullOrWhiteSpace(student.Name) && !string.IsNullOrWhiteSpace(student.Number)) { // ReSharper disable once MethodHasAsyncOverload db.Students.Add(student); await db.SaveChangesAsync(); resp.Id = student.Id; logger.LogTrace($"Added student {student.Name} to course {student.CourseId}"); } else { logger.LogWarning($"{userId} {(ownsCourse ? "" : "not")} owner; fields {student}"); resp.ResponseCodes.Add( ownsCourse ? ResponseCodes.EmptyStudentFields : ResponseCodes.InvalidUser); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"Failed to add {student.Name} to course {student.CourseId}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
private async Task ShouldSubmitFile() { const string filePath = "./Resources/checkout.jpeg"; var idResponse = new IdResponse(); _apiClient.Setup(apiClient => apiClient.Post <IdResponse>( "files", _authorization, It.IsAny <MultipartFormDataContent>(), CancellationToken.None, null)) .ReturnsAsync(() => idResponse); IFilesClient client = new FilesClient(_apiClient.Object, null, _configuration.Object); var response = await client.SubmitFile(filePath, "dispute_evidence"); response.ShouldNotBeNull(); }
public async Task <IdResponse> Post([FromBody] Course course) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { if (!string.IsNullOrWhiteSpace(course.Name) && course.Year >= DateTime.UtcNow.Year) { course.UserId = userId; // ReSharper disable once MethodHasAsyncOverload db.Courses.Add(course); await db.SaveChangesAsync(); resp.Id = course.Id; logger.LogTrace($"Added course {course.Id} : {course.Name}"); } else { logger.LogWarning($"Bad name {course.Name} or {course.Year}"); resp.ResponseCodes.Add(ResponseCodes.InvalidCourseFields); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"Could not add course {course.Name}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IdResponse> Delete(int id) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var school = await db.Schools.FirstOrDefaultAsync(s => s.Id == id); if (school != null) { db.Schools.Remove(school); await db.SaveChangesAsync(); resp.Id = school.Id; logger.LogTrace($"deleted {id}"); } else { resp.Id = 1; logger.LogWarning($"school {id} not found"); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { if (ex.InnerException is SqlException exception && exception.Number == 547) { resp.ResponseCodes.Add(ResponseCodes.SchoolInUse); logger.LogWarning("Attempt to delete record in use"); }
public async Task <IdResponse> Post([FromBody] School school) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { if (!string.IsNullOrWhiteSpace(school.Name)) { // ReSharper disable once MethodHasAsyncOverload db.Schools.Add(school); await db.SaveChangesAsync(); resp.Id = school.Id; logger.LogTrace($"Added school {school.Name}"); } else { logger.LogWarning("Invalid school name"); resp.ResponseCodes.Add(ResponseCodes.InvalidSchoolFields); } } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"Failed to add {school.Name}"); resp.ResponseCodes.Add(ResponseCodes.InternalError); } return(resp); }
public async Task <IdResponse> Delete(int id) { var resp = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var course = await db.Courses.FirstOrDefaultAsync(c => c.Id == id && c.UserId == userId); if (course != null) { db.Courses.Remove(course); await db.SaveChangesAsync(); logger.LogTrace($"deleted {course.Id}"); } else { logger.LogWarning("{id} not found"); } resp.Id = id; } else { logger.LogWarning("Attempt without logging in"); resp.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { if (ex.InnerException is SqlException exception && exception.Number == 547) { resp.ResponseCodes.Add(ResponseCodes.CourseInUse); logger.LogWarning("Attempt to delete record in use"); }
public async Task <IdResponse> Delete(int id) { var ps = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { if (userId == id) { var user = await db.Users.FirstOrDefaultAsync(u => u.Id == id); db.Users.Remove(user); await db.SaveChangesAsync(); ps.Id = id; } else { logger.LogWarning($"{userId} attempted to delete {id}"); ps.ResponseCodes.Add(ResponseCodes.DeleteOtherUser); } } else { logger.LogWarning("Attempt without logging in"); ps.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { if (ex.InnerException is SqlException exception && exception.Number == Util.SQL_CONSTRAINT_VIOLATION) { ps.ResponseCodes.Add(ResponseCodes.UserInUse); logger.LogWarning("Attempt to delete record in use"); }
public async Task <IdResponse> Logout() { var ps = new IdResponse(); try { await HttpContext.Session.LoadAsync(); var userId = HttpContext.Session.GetInt32("userId"); HttpContext.Session.Remove("UserId"); await HttpContext.Session.CommitAsync(); ps.Id = userId ?? 1; logger.LogTrace($"User {userId} has logged out"); } catch (Exception ex) { logger.LogError(ex, "failed to logout"); ps.ResponseCodes.Add(ResponseCodes.InternalError); } return(ps); }
public async Task <IdResponse> UpdateUser(int id, [FromBody] User user) { var ps = new IdResponse(); try { var userId = await Util.GetLoggedInUser(HttpContext); if (userId > 0) { var existingUser = await db.Users.FirstOrDefaultAsync(u => u.Id == id); if (existingUser != null && userId == existingUser.Id) { var isValidEmail = !string.IsNullOrWhiteSpace(user.Email) && new EmailAddressAttribute().IsValid(user.Email) && !db.Users.Any(u => u.Email == user.Email && u.Id != id); var isValidName = !string.IsNullOrWhiteSpace(user.Email); var isValidSchool = db.Schools.Any(s => s.Id == user.SchoolId); //check for valid fields if (isValidEmail && isValidName && isValidSchool) { //save the user existingUser.Email = user.Email; existingUser.SchoolId = user.SchoolId; existingUser.Name = user.Name; await db.SaveChangesAsync(); //let the client know that it was done successfully by returning the Id ps.Id = existingUser.Id; logger.LogTrace($"Updated user {existingUser}"); } else { logger.LogWarning($"invalid or missing info: {user}"); if (!isValidEmail) { ps.ResponseCodes.Add(ResponseCodes.InvalidEmail); } if (!isValidName) { ps.ResponseCodes.Add(ResponseCodes.InvalidName); } if (!isValidSchool) { ps.ResponseCodes.Add(ResponseCodes.InvalidSchool); } } } else { logger.LogWarning($"user {id} does not exist or attempt to modify another user by {userId}"); ps.ResponseCodes.Add(ResponseCodes.InvalidUser); } } else { logger.LogWarning("Attempt without logging in"); ps.ResponseCodes.Add(ResponseCodes.NotLoggedIn); } } catch (Exception ex) { logger.LogError(ex, $"failed to update user {user}"); ps.ResponseCodes.Add(ResponseCodes.InternalError); } return(ps); }
// Unknown 01/01/01 /// <summary> /// Instantiate the %AWG class for the session requested by the<para> /// index value by default, </para> /// create a new session unless we pass false /// </summary> /// <param name="index">Index value of the session</param> /// <returns>%AWG visa session</returns> static IAWG GetAWG(int index) { //Sharmila - 01/04/2015 //To retrieve the SourceXpress button status to decide whether connection should be with GPIB8 or not bool isSXSelected = false; if (index >= 3) { Assert.Fail("AWG index value out of range, only 4 AWGs are allowed with index 0-3."); } // If the value at the requested index is null, then a new session is created and returned, otherwise the // existing session at that index is returned and the session remains open. if (_AWGList[index] == null) { /* If the DUT configuration is completed then the DUT UI Dialog should not pop up. Hence the below check is done. * Another way of stating this is only show the UI once, gather all the information for possible user later * as what resources are used are dependent on the test being run at the moment. */ if (_testconfigcomplete != true) { var dutConfigUi = new dutui(); dutConfigUi.ShowDialog(); if (dutConfigUi.TopMost == false) //Bring to DUT Dialog to front focus { //These four lines of code have earned its writer a whole $1 coin dutConfigUi.TopMost = true; //May it be spent wisely } if (dutui.pc_pbu_state) // is true { /* If the user selects PC App then the DUT IP Address is fixed as 127.0.0.1*/ _awgConnection = "TCPIP::127.0.0.1"; } else { //Sharmila - 01/04/2015 //Retrieve the SourceXpress radio button status by deserializing the MySettings.xml //If SourceXpress is selected, establish the connection with GPIB8 isSXSelected = dutConfigUi.deserdata[0].sx_state; if (dutui.AWG1Controller_set || isSXSelected) { _connection1 = "TCPIP::localhost"; } else if (dutui.dut1_ip_name_address_selected) // is true { /* If user enters DUT IP Address then deserialized data for IP Adress is used to establish connection*/ _connection1 = dutConfigUi.deserdata[0].DUTIP; _connType = dutConfigUi.deserdata[0].AwgConnType; } else { _connection1 = dutConfigUi.deserdata[0].DutName; _connType = dutConfigUi.deserdata[0].AwgConnType; } _connection2 = dutui.dut2_ip_name_address_selected ? dutConfigUi.deserdata[1].DUTIP : dutConfigUi.deserdata[1].DutName; _connection3 = dutui.dut3_ip_name_address_selected ? dutConfigUi.deserdata[2].DUTIP : dutConfigUi.deserdata[2].DutName; _connection4 = dutui.dut4_ip_name_address_selected ? dutConfigUi.deserdata[3].DUTIP : dutConfigUi.deserdata[3].DutName; } // Setup IP for scope (if there is one) ScopeConnectionIP = dutui.scope_ip_address_name_selected ? dutConfigUi.deserdata[0].ScopeIP : dutConfigUi.deserdata[0].ScopeName; // Setup IP for external source clock (if there is one) ExtSourceConnectionIP = dutui.extsource_ip_address_name_selected ? dutConfigUi.deserdata[0].ExtSourceIP : dutConfigUi.deserdata[0].ExtSourceName; _testconfigcomplete = true; } if (dutui.pc_pbu_state) // is true { _awgConnection = "TCPIP::127.0.0.1"; } else { switch (index) { case 0: // PWH - Need this in case the test case calls out an AWG number that was not set in the dialog. I'd like for any error checks to have something like this level of detail sent back to the user on failures. //Sharmila - 01/04/2015 //If Controller or SourceXpress is selectedd in UI, establish the connection with GPIB8 Assert.AreNotEqual("", _connection1, "The connect string for VISA was empty (e.g. TCPIP::::INSTR) - check configuration dialog for correct instrument setup."); _awgConnection = (dutui.AWG1Controller_set || isSXSelected) ? "GPIB8::1" : "TCPIP" + "::" + _connection1; break; case 1: Assert.AreNotEqual("", _connection2, "The connect string for VISA was empty - check configuration dialog for correct instrument setup."); _awgConnection = "TCPIP" + "::" + _connection2; break; case 2: Assert.AreNotEqual("", _connection3, "The connect string for VISA was empty - check configuration dialog for correct instrument setup."); _awgConnection = "TCPIP" + "::" + _connection3; break; case 3: Assert.AreNotEqual("", _connection4, "The connect string for VISA was empty - check configuration dialog for correct instrument setup."); _awgConnection = "TCPIP" + "::" + _connection4; break; } } /*For Socket connection the String is as follows TCPIP::134.64.236.77::4000::SOCKET. Hence ::INSTR should be replaced with AwgConnectionType */ /*For VXI-11 connection the String is as follows TCPIP::134.64.236.77::INSTR*/ if (_connType == "SOCKET") { _awgConnection = _awgConnection + "::4001::SOCKET"; //PWH - Shouldn't this have the "TCPIP" replaced by AwgConnectionType? } else { _awgConnection = _awgConnection + "::INSTR"; } if (dutui.AWG1Controller_set) { IgnoreUi = dutui.IgnoreUI; } // Before creating an AWG, it is necessary to know the type of AWG that the // address is associated with. Try to make a connection. If the connection // is successful, then an specific AWG can be created with the just made // connection. TekVISANet.VISA visaSession = new TekVISANet.VISA(); // Try and have the visaSession make a connection to the resource bool openSuccessFul; int retry = 5; do { openSuccessFul = visaSession.Open(_awgConnection); } while ((--retry >= 0) && (!openSuccessFul)); string status = visaSession.ErrorDescription; //See if the status string contains the word "Success" Regex validatePreMatcher = new Regex(@"Success.+"); Match match = validatePreMatcher.Match(status); // Check the status string to see if the operation was sucessful if (!match.Success) { Assert.Fail("Attempt to Open connection failed: " + status); } // After a successful connection, do an *idn? query and get model id. // Once there is an model number, the correct and proper AWG can be // created and added to the list. Right? string response = null; visaSession.Query("*IDN?", out response); if (response == null) { Assert.Fail("Attempt to get ID string failed."); } // Success, right, we have an ID string. Pull it apart to determine the family IdResponse decomposed = GetAwgInformation(response); if (decomposed.Family == Family70k) { // Now create an AWG. _AWGList[index] = new AWG(visaSession); _AWGList[index].LogicalAWGNumber = (index + 1).ToString(CultureInfo.InvariantCulture); // Let the AWG know its place in the world. } else if (decomposed.Family == Family50k) { // Create the new 50K here! } else { Assert.Fail("Cannot support unknown Family " + decomposed.Family); } } // If it failed, then an assert happened, so we didn't get here. // Was this requested awg discovered? if (_AWGList[index] == null) { Assert.Fail("No AWG was found!"); } return(_AWGList[index]); }
public async Task <IdResponse> Register([FromBody] User newUser) { var ps = new IdResponse(); try { newUser.Email = newUser.Email?.ToLower(); //check if there are already users with this email if (!db.Users.Any(u => u.Email == newUser.Email)) //check for valid email { if (!string.IsNullOrWhiteSpace(newUser.Email) && !string.IsNullOrWhiteSpace(newUser.Password) && new EmailAddressAttribute().IsValid(newUser.Email)) { if (await PasswordCheck.IsStrong(newUser.Password)) { //if all good, convert the password into its hash newUser.Password = PasswordHash.HashPassword(newUser.Password); //save the user // ReSharper disable once MethodHasAsyncOverload db.Users.Add(newUser); await db.SaveChangesAsync(); //let the client know that it was done successfully by returning the Id ps.Id = newUser.Id; //save the user's ID to the session -- ie. we're logged in await HttpContext.Session.LoadAsync(); HttpContext.Session.SetInt32("UserId", newUser.Id); await HttpContext.Session.CommitAsync(); logger.LogTrace($"Created user {newUser.Id} for {newUser.Email}"); } else { logger.LogWarning($"attempt to use poor password {newUser.Password}"); ps.ResponseCodes.Add(ResponseCodes.WeakPassword); } } else { logger.LogWarning($"missing info: {newUser}"); ps.ResponseCodes.Add(ResponseCodes.InvalidCredentials); } } else { logger.LogWarning($"email {newUser.Email} already exists"); ps.ResponseCodes.Add(ResponseCodes.EmailInUse); } } catch (Exception ex) { logger.LogError(ex, $"failed to create user {newUser}"); ps.ResponseCodes.Add(ResponseCodes.InternalError); } return(ps); }