Search in sources :

Example 61 with Post

use of de.tum.in.www1.artemis.domain.metis.Post in project ArTEMiS by ls1intum.

the class GradingScaleResource method createGradingScaleForCourse.

/**
 * POST /courses/{courseId}/grading-scale : Create grading scale for course
 *
 * @param courseId the course to which the grading scale belongs
 * @param gradingScale the grading scale which will be created
 * @return ResponseEntity with status 201 (Created) with body the new grading scale if no such exists for the course
 *         and if it is correctly formatted and 400 (Bad request) otherwise
 */
@PostMapping("/courses/{courseId}/grading-scale")
@PreAuthorize("hasRole('INSTRUCTOR')")
public ResponseEntity<GradingScale> createGradingScaleForCourse(@PathVariable Long courseId, @RequestBody GradingScale gradingScale) throws URISyntaxException {
    log.debug("REST request to create a grading scale for course: {}", courseId);
    Course course = courseRepository.findByIdElseThrow(courseId);
    Optional<GradingScale> existingGradingScale = gradingScaleRepository.findByCourseId(courseId);
    authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, course, null);
    validateGradingScale(existingGradingScale, gradingScale);
    if (!Objects.equals(gradingScale.getCourse().getMaxPoints(), course.getMaxPoints())) {
        course.setMaxPoints(gradingScale.getCourse().getMaxPoints());
        courseRepository.save(course);
    }
    gradingScale.setCourse(course);
    GradingScale savedGradingScale = gradingScaleService.saveGradingScale(gradingScale);
    return ResponseEntity.created(new URI("/api/courses/" + courseId + "/grading-scale/")).headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, "")).body(savedGradingScale);
}
Also used : GradingScale(de.tum.in.www1.artemis.domain.GradingScale) Course(de.tum.in.www1.artemis.domain.Course) URI(java.net.URI) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 62 with Post

use of de.tum.in.www1.artemis.domain.metis.Post in project ArTEMiS by ls1intum.

the class GradingScaleResource method createGradingScaleForExam.

/**
 * POST /courses/{courseId}/exams/{examId}grading-scale : Create grading scale for exam
 *
 * @param courseId the course to which the exam belongs
 * @param examId the exam to which the grading scale belongs
 * @param gradingScale the grading scale which will be created
 * @return ResponseEntity with status 201 (Created) with body the new grading scale if no such exists for the course
 *         and if it is correctly formatted and 400 (Bad request) otherwise
 */
@PostMapping("/courses/{courseId}/exams/{examId}/grading-scale")
@PreAuthorize("hasRole('INSTRUCTOR')")
public ResponseEntity<GradingScale> createGradingScaleForExam(@PathVariable Long courseId, @PathVariable Long examId, @RequestBody GradingScale gradingScale) throws URISyntaxException {
    log.debug("REST request to create a grading scale for exam: {}", examId);
    Course course = courseRepository.findByIdElseThrow(courseId);
    Optional<GradingScale> existingGradingScale = gradingScaleRepository.findByExamId(examId);
    authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, course, null);
    validateGradingScale(existingGradingScale, gradingScale);
    Exam exam = examRepository.findByIdElseThrow(examId);
    if (gradingScale.getExam().getMaxPoints() != exam.getMaxPoints()) {
        exam.setMaxPoints(gradingScale.getExam().getMaxPoints());
        examRepository.save(exam);
    }
    gradingScale.setExam(exam);
    GradingScale savedGradingScale = gradingScaleService.saveGradingScale(gradingScale);
    return ResponseEntity.created(new URI("/api/courses/" + courseId + "/exams/" + examId + "/grading-scale/")).headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, "")).body(savedGradingScale);
}
Also used : GradingScale(de.tum.in.www1.artemis.domain.GradingScale) Course(de.tum.in.www1.artemis.domain.Course) URI(java.net.URI) Exam(de.tum.in.www1.artemis.domain.exam.Exam) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 63 with Post

use of de.tum.in.www1.artemis.domain.metis.Post in project ArTEMiS by ls1intum.

the class LectureResource method createLecture.

/**
 * POST /lectures : Create a new lecture.
 *
 * @param lecture the lecture to create
 * @return the ResponseEntity with status 201 (Created) and with body the new lecture, or with status 400 (Bad Request) if the lecture has already an ID
 * @throws URISyntaxException if the Location URI syntax is incorrect
 */
@PostMapping("/lectures")
@PreAuthorize("hasRole('EDITOR')")
public ResponseEntity<Lecture> createLecture(@RequestBody Lecture lecture) throws URISyntaxException {
    log.debug("REST request to save Lecture : {}", lecture);
    if (lecture.getId() != null) {
        throw new BadRequestAlertException("A new lecture cannot already have an ID", ENTITY_NAME, "idexists");
    }
    authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.EDITOR, lecture.getCourse(), null);
    Lecture result = lectureRepository.save(lecture);
    return ResponseEntity.created(new URI("/api/lectures/" + result.getId())).headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())).body(result);
}
Also used : BadRequestAlertException(de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException) Lecture(de.tum.in.www1.artemis.domain.Lecture) URI(java.net.URI) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 64 with Post

use of de.tum.in.www1.artemis.domain.metis.Post in project ArTEMiS by ls1intum.

the class LtiResource method launch.

/**
 * POST lti/launch/:exerciseId : Launch the exercise app using request by a LTI consumer. Redirects the user to the exercise on success.
 *
 * @param launchRequest the LTI launch request (ExerciseLtiConfigurationDTO)
 * @param exerciseId    the id of the exercise the user wants to open
 * @param request       HTTP request
 * @param response      HTTP response
 * @throws IOException If an input or output exception occurs
 */
@PostMapping(value = "lti/launch/{exerciseId}", produces = MediaType.APPLICATION_JSON_VALUE)
public void launch(@ModelAttribute LtiLaunchRequestDTO launchRequest, @PathVariable("exerciseId") Long exerciseId, HttpServletRequest request, HttpServletResponse response) throws IOException {
    log.info("/lti/launch/{} with launch request: {}", exerciseId, launchRequest);
    if (this.LTI_OAUTH_SECRET.isEmpty() || this.LTI_ID.isEmpty() || this.LTI_OAUTH_KEY.isEmpty()) {
        String message = "LTI not configured on this Artemis server. Cannot launch exercise " + exerciseId + ". " + "Please contact an admin or try again.";
        log.warn(message);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, message);
        return;
    }
    log.debug("Request header X-Forwarded-Proto: {}", request.getHeader("X-Forwarded-Proto"));
    log.debug("Request header X-Forwarded-For: {}", request.getHeader("X-Forwarded-For"));
    if (!request.getRequestURL().toString().startsWith("https")) {
        log.error("The request url {} does not start with 'https'. Verification of the request will most probably fail. Please double check your loadbalancer (e.g. nginx) " + "configuration and your Spring configuration (e.g. application.yml) with respect to proxy_set_header X-Forwarded-Proto and forward-headers-strategy: " + "native", request.getRequestURL().toString());
    }
    log.debug("Try to verify LTI Oauth Request");
    // Verify request
    String error = ltiService.verifyRequest(request);
    if (error != null) {
        log.warn("Failed verification for launch request : {}", launchRequest);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, error + ". Cannot launch exercise " + exerciseId + ". " + "Please contact an admin or try again.");
        return;
    }
    log.debug("Oauth Verification succeeded");
    // Check if exercise ID is valid
    Optional<Exercise> optionalExercise = exerciseRepository.findById(exerciseId);
    if (optionalExercise.isEmpty()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Exercise not found");
        return;
    }
    Exercise exercise = optionalExercise.get();
    log.debug("found exercise {}", exercise.getTitle());
    // Handle the launch request using LtiService
    try {
        ltiService.handleLaunchRequest(launchRequest, exercise);
    } catch (InternalAuthenticationServiceException ex) {
        log.error("Error during LTI launch request of exercise " + exercise.getTitle() + " for launch request: " + launchRequest, ex);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        return;
    } catch (Exception ex) {
        log.error("Error during LTI launch request of exercise " + exercise.getTitle() + " for launch request: " + launchRequest, ex);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
        return;
    }
    log.debug("handleLaunchRequest done");
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String jwt = tokenProvider.createToken(authentication, true);
    log.debug("created jwt token: {}", jwt);
    // Note: The following redirect URL has to match the URL in user-route-access-service.ts in the method canActivate(...)
    UriComponentsBuilder redirectUrlComponentsBuilder = UriComponentsBuilder.newInstance().scheme(request.getScheme()).host(request.getServerName());
    if (request.getServerPort() != 80 && request.getServerPort() != 443) {
        redirectUrlComponentsBuilder.port(request.getServerPort());
    }
    redirectUrlComponentsBuilder.pathSegment("courses").pathSegment(exercise.getCourseViaExerciseGroupOrCourseMember().getId().toString()).pathSegment("exercises").pathSegment(exercise.getId().toString());
    User user = userRepository.getUser();
    if (!user.getActivated()) {
        redirectUrlComponentsBuilder.queryParam("initialize", "");
    }
    if (!SecurityUtils.isAuthenticated()) {
        redirectUrlComponentsBuilder.queryParam("login", "");
    }
    redirectUrlComponentsBuilder.queryParam("jwt", jwt);
    String redirectUrl = redirectUrlComponentsBuilder.build().toString();
    log.info("redirect to url: {}", redirectUrl);
    response.sendRedirect(redirectUrl);
}
Also used : Exercise(de.tum.in.www1.artemis.domain.Exercise) User(de.tum.in.www1.artemis.domain.User) Authentication(org.springframework.security.core.Authentication) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) IOException(java.io.IOException) AccessForbiddenException(de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException)

Example 65 with Post

use of de.tum.in.www1.artemis.domain.metis.Post in project ArTEMiS by ls1intum.

the class ModelingExerciseResource method exportSubmissions.

/**
 * POST modeling-exercises/:exerciseId/export-submissions : sends exercise submissions as zip
 *
 * @param exerciseId the id of the exercise to get the repos from
 * @param submissionExportOptions the options that should be used for the export
 * @return ResponseEntity with status
 */
@PostMapping("modeling-exercises/{exerciseId}/export-submissions")
@PreAuthorize("hasRole('TA')")
public ResponseEntity<Resource> exportSubmissions(@PathVariable long exerciseId, @RequestBody SubmissionExportOptionsDTO submissionExportOptions) {
    ModelingExercise modelingExercise = modelingExerciseRepository.findByIdElseThrow(exerciseId);
    authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, modelingExercise, null);
    // TAs are not allowed to download all participations
    if (submissionExportOptions.isExportAllParticipants()) {
        authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, modelingExercise.getCourseViaExerciseGroupOrCourseMember(), null);
    }
    File zipFile = modelingSubmissionExportService.exportStudentSubmissionsElseThrow(exerciseId, submissionExportOptions);
    return ResponseUtil.ok(zipFile);
}
Also used : ModelingExercise(de.tum.in.www1.artemis.domain.modeling.ModelingExercise) File(java.io.File) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Aggregations

Post (de.tum.in.www1.artemis.domain.metis.Post)155 WithMockUser (org.springframework.security.test.context.support.WithMockUser)150 Test (org.junit.jupiter.api.Test)136 AbstractSpringIntegrationBambooBitbucketJiraTest (de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest)118 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)97 User (de.tum.in.www1.artemis.domain.User)88 AnswerPost (de.tum.in.www1.artemis.domain.metis.AnswerPost)87 URI (java.net.URI)63 BadRequestAlertException (de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException)56 Course (de.tum.in.www1.artemis.domain.Course)52 Transactional (org.springframework.transaction.annotation.Transactional)37 Reaction (de.tum.in.www1.artemis.domain.metis.Reaction)36 Test (org.junit.Test)36 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)36 Exercise (de.tum.in.www1.artemis.domain.Exercise)35 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 Exam (de.tum.in.www1.artemis.domain.exam.Exam)20 Lecture (de.tum.in.www1.artemis.domain.Lecture)16 ProgrammingExercise (de.tum.in.www1.artemis.domain.ProgrammingExercise)16 SortingOrder (de.tum.in.www1.artemis.domain.enumeration.SortingOrder)16