feat: initial commit

This commit is contained in:
2022-10-03 09:59:21 +02:00
parent 35d6accafb
commit abfaf19c47
53 changed files with 2173 additions and 153 deletions

View File

@@ -0,0 +1,12 @@
package fr.itsonus.bousoleplussbackend;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,15 @@
package fr.itsonus.bousoleplussbackend.advice;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
@Data
@AllArgsConstructor
public class ErrorMessage {
private int statusCode;
private Date timestamp;
private String message;
private String description;
}

View File

@@ -0,0 +1,25 @@
package fr.itsonus.bousoleplussbackend.advice;
import fr.itsonus.bousoleplussbackend.exception.TokenRefreshException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import java.util.Date;
@RestControllerAdvice
public class TokenControllerAdvice {
@ExceptionHandler(value = TokenRefreshException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public ErrorMessage handleTokenRefreshException(TokenRefreshException ex, WebRequest request) {
return new ErrorMessage(
HttpStatus.FORBIDDEN.value(),
new Date(),
ex.getMessage(),
request.getDescription(false));
}
}

View File

@@ -0,0 +1,9 @@
package fr.itsonus.bousoleplussbackend.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@Configuration
@EnableJpaAuditing
public class PersistenceConfiguration {
}

View File

@@ -0,0 +1,15 @@
package fr.itsonus.bousoleplussbackend.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
@Configuration
public class RestConfiguration implements RepositoryRestConfigurer {
// @Override
// public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration,
// CorsRegistry cors) {
// repositoryRestConfiguration.getProjectionConfiguration()
// .addProjection(QuizWithScore.class);
// }
}

View File

@@ -0,0 +1,72 @@
package fr.itsonus.bousoleplussbackend.configuration;
import fr.itsonus.bousoleplussbackend.security.jwt.AuthEntryPointJwt;
import fr.itsonus.bousoleplussbackend.security.jwt.AuthTokenFilter;
import fr.itsonus.bousoleplussbackend.security.services.UserDetailsServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import java.util.List;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@AllArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsServiceImpl userDetailsService;
private final AuthEntryPointJwt unauthorizedHandler;
@Bean
public AuthTokenFilter authenticationJwtTokenFilter() {
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().configurationSource(request -> {
var configuration = new CorsConfiguration();
configuration.setAllowedOrigins(List.of("*"));
configuration.setAllowedMethods(List.of("GET", "POST"));
configuration.setAllowedHeaders(List.of("*"));
return configuration;
})
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/auth/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}

View File

@@ -0,0 +1,101 @@
package fr.itsonus.bousoleplussbackend.controllers;
import fr.itsonus.bousoleplussbackend.exception.TokenRefreshException;
import fr.itsonus.bousoleplussbackend.models.RefreshToken;
import fr.itsonus.bousoleplussbackend.models.User;
import fr.itsonus.bousoleplussbackend.payload.request.LogOutRequest;
import fr.itsonus.bousoleplussbackend.payload.request.LoginRequest;
import fr.itsonus.bousoleplussbackend.payload.request.SignupRequest;
import fr.itsonus.bousoleplussbackend.payload.request.TokenRefreshRequest;
import fr.itsonus.bousoleplussbackend.payload.response.JwtResponse;
import fr.itsonus.bousoleplussbackend.payload.response.MessageResponse;
import fr.itsonus.bousoleplussbackend.payload.response.TokenRefreshResponse;
import fr.itsonus.bousoleplussbackend.repositories.UserRepository;
import fr.itsonus.bousoleplussbackend.security.jwt.JwtUtils;
import fr.itsonus.bousoleplussbackend.security.services.RefreshTokenService;
import fr.itsonus.bousoleplussbackend.security.services.UserDetailsImpl;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/auth")
@AllArgsConstructor
public class AuthController {
private final AuthenticationManager authenticationManager;
private final UserRepository userRepository;
private final PasswordEncoder encoder;
private final JwtUtils jwtUtils;
private final RefreshTokenService refreshTokenService;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
var authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
var userDetails = (UserDetailsImpl) authentication.getPrincipal();
var jwt = jwtUtils.generateJwtToken(userDetails);
var refreshToken = refreshTokenService.createRefreshToken(userDetails.getId());
return ResponseEntity.ok(new JwtResponse(jwt, refreshToken.getToken(), userDetails.getId(),
userDetails.getUsername()));
}
@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
if (userRepository.existsByUsername(signUpRequest.getUsername())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken!"));
}
// Create new user's account
var user = new User();
user.setUsername(signUpRequest.getUsername());
user.setPassword(encoder.encode(signUpRequest.getPassword()));
userRepository.save(user);
return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
@PostMapping("/refreshtoken")
public ResponseEntity<?> refreshToken(@Valid @RequestBody TokenRefreshRequest request) {
String requestRefreshToken = request.getRefreshToken();
return refreshTokenService.findByToken(requestRefreshToken)
.map(refreshTokenService::verifyExpiration)
.map(RefreshToken::getUser)
.map(user -> {
String token = jwtUtils.generateTokenFromUsername(user.getUsername());
return ResponseEntity.ok(new TokenRefreshResponse(token, requestRefreshToken));
})
.orElseThrow(() -> new TokenRefreshException(requestRefreshToken,
"Refresh token is not in database!"));
}
@PostMapping("/logout")
public ResponseEntity<?> logoutUser(@Valid @RequestBody LogOutRequest logOutRequest) {
refreshTokenService.deleteByUserId(logOutRequest.getUserId());
return ResponseEntity.ok(new MessageResponse("Log out successful!"));
}
@GetMapping("/me")
public ResponseEntity<?> me() {
var authentication = SecurityContextHolder.getContext().getAuthentication();
return ResponseEntity.ok(authentication.getPrincipal());
}
}

View File

@@ -0,0 +1,58 @@
package fr.itsonus.bousoleplussbackend.controllers;
import fr.itsonus.bousoleplussbackend.models.Quiz;
import fr.itsonus.bousoleplussbackend.models.QuizScore;
import fr.itsonus.bousoleplussbackend.models.Response;
import fr.itsonus.bousoleplussbackend.payload.request.QuizRequest;
import fr.itsonus.bousoleplussbackend.repositories.QuestionRepository;
import fr.itsonus.bousoleplussbackend.repositories.QuizRepository;
import fr.itsonus.bousoleplussbackend.repositories.QuizScoreRepository;
import fr.itsonus.bousoleplussbackend.repositories.ResponseRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/quizzes")
@AllArgsConstructor
public class QuizController {
private QuizRepository quizRepository;
private ResponseRepository responseRepository;
private QuestionRepository questionRepository;
private QuizScoreRepository quizScoreRepository;
@PostMapping("batch") // TODO add to REST representation
public Quiz create(@Valid @RequestBody QuizRequest request) {
var quiz = quizRepository.save(new Quiz());
var responsesCreated = request.getResponses().stream().map(response -> {
// TODO add correct exception with correct status code
var question = questionRepository.findById(response.getQuestionId())
.orElseThrow(() -> new NoSuchElementException("No such question with id " + response.getQuestionId()));
log.info("Saving {}", response);
return responseRepository.save(
new Response()
.setScore(response.getScore())
.setComment(response.getComment())
.setQuiz(quiz)
.setQuestion(question));
}).collect(Collectors.toSet());
quiz.setResponses(responsesCreated);
return quiz;
}
@GetMapping("{id}/scores")
public Iterable<QuizScore> findScores(@PathVariable("id") Long id) {
return this.quizScoreRepository.findAllByQuizId(id);
}
}

View File

@@ -0,0 +1,14 @@
package fr.itsonus.bousoleplussbackend.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.FORBIDDEN)
public class TokenRefreshException extends RuntimeException {
private static final long serialVersionUID = 1L;
public TokenRefreshException(String token, String message) {
super(String.format("Failed for [%s]: %s", token, message));
}
}

View File

@@ -0,0 +1,52 @@
package fr.itsonus.bousoleplussbackend.models;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
public class Axe {
@Id
@GeneratedValue
private Long id;
private Integer identifier;
@NotBlank
@Size(max = 50)
private String shortTitle;
@NotBlank
@Size(max = 100)
private String title;
@NotBlank
private String color;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
Axe axe = (Axe) o;
return id != null && Objects.equals(id, axe.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}

View File

@@ -0,0 +1,65 @@
package fr.itsonus.bousoleplussbackend.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import fr.itsonus.bousoleplussbackend.security.services.UserDetailsImpl;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.PrePersist;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
public class Question {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private Axe axe;
@JsonIgnore
private Long userId;
@NotBlank
@Size(max = 200)
private String label;
@NotBlank
@Size(max = 500)
private String description;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
var question = (Question) o;
return id != null && Objects.equals(id, question.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
@PrePersist
public void prePersist() {
var userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
this.userId = userDetails.getId();
}
}

View File

@@ -0,0 +1,65 @@
package fr.itsonus.bousoleplussbackend.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import fr.itsonus.bousoleplussbackend.security.services.UserDetailsImpl;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.PrePersist;
import java.util.Date;
import java.util.Objects;
import java.util.Set;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Quiz {
@Id
@GeneratedValue
private Long id;
@Column(name = "created_date", nullable = false, updatable = false)
@CreatedDate
private Date createdDate;
@JsonIgnore
private Long userId;
@OneToMany(mappedBy = "quiz")
@ToString.Exclude
private Set<Response> responses;
@PrePersist
public void prePersist() {
var userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
this.userId = userDetails.getId();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
Quiz that = (Quiz) o;
return id != null && Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}

View File

@@ -0,0 +1,29 @@
package fr.itsonus.bousoleplussbackend.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.Immutable;
import javax.persistence.Entity;
import javax.persistence.Id;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
@Immutable
public class QuizScore {
@Id
@JsonIgnore
private Long id;
private Float scoreAvg;
private Integer axeIdentifier;
@JsonIgnore
private Long quizId;
}

View File

@@ -0,0 +1,51 @@
package fr.itsonus.bousoleplussbackend.models;
import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import java.time.Instant;
import java.util.Objects;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
public class RefreshToken {
@Id
@GeneratedValue
private Long id;
@OneToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
@Column(nullable = false, unique = true)
private String token;
@Column(nullable = false)
private Instant expiryDate;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
RefreshToken that = (RefreshToken) o;
return id != null && Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}

View File

@@ -0,0 +1,62 @@
package fr.itsonus.bousoleplussbackend.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.hibernate.Hibernate;
import org.hibernate.validator.constraints.Length;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Objects;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Accessors(chain = true)
@Entity
public class Response {
@Id
@GeneratedValue
private Long id;
@OneToOne
@JoinColumn(name = "question_id")
private Question question;
@ManyToOne
@JoinColumn(name = "quiz_id")
@JsonIgnore
private Quiz quiz;
@Min(0)
@Max(10)
private Short score;
@Length(max = 500)
private String comment;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
Response response = (Response) o;
return id != null && Objects.equals(id, response.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}

View File

@@ -0,0 +1,54 @@
package fr.itsonus.bousoleplussbackend.models;
import lombok.Data;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
@Table(name = "users",
uniqueConstraints = {
@UniqueConstraint(columnNames = "username")
})
public class User {
@Id
@GeneratedValue
private Long id;
@NotBlank
@Size(max = 20)
private String username;
@NotBlank
@Size(max = 120)
private String password;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
User user = (User) o;
return id != null && Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}

View File

@@ -0,0 +1,8 @@
package fr.itsonus.bousoleplussbackend.payload.request;
import lombok.Data;
@Data
public class LogOutRequest {
private Long userId;
}

View File

@@ -0,0 +1,14 @@
package fr.itsonus.bousoleplussbackend.payload.request;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class LoginRequest {
@NotBlank
private String username;
@NotBlank
private String password;
}

View File

@@ -0,0 +1,14 @@
package fr.itsonus.bousoleplussbackend.payload.request;
import lombok.Data;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.Set;
@Data
public class QuizRequest {
@NotEmpty
private Set<@Valid ResponseRequest> responses;
}

View File

@@ -0,0 +1,14 @@
package fr.itsonus.bousoleplussbackend.payload.request;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Data
public class ResponseRequest {
@NotNull
private Long questionId;
@NotNull
private Short score;
private String comment;
}

View File

@@ -0,0 +1,17 @@
package fr.itsonus.bousoleplussbackend.payload.request;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
@Data
public class SignupRequest {
@NotBlank
@Size(min = 3, max = 20)
private String username;
@NotBlank
@Size(min = 6, max = 40)
private String password;
}

View File

@@ -0,0 +1,11 @@
package fr.itsonus.bousoleplussbackend.payload.request;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class TokenRefreshRequest {
@NotBlank
private String refreshToken;
}

View File

@@ -0,0 +1,15 @@
package fr.itsonus.bousoleplussbackend.payload.response;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class JwtResponse {
private static String type = "Bearer";
private String token;
private String refreshToken;
private Long id;
private String username;
}

View File

@@ -0,0 +1,10 @@
package fr.itsonus.bousoleplussbackend.payload.response;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MessageResponse {
private String message;
}

View File

@@ -0,0 +1,13 @@
package fr.itsonus.bousoleplussbackend.payload.response;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class TokenRefreshResponse {
private static String tokenType = "Bearer";
private String accessToken;
private String refreshToken;
}

View File

@@ -0,0 +1,21 @@
package fr.itsonus.bousoleplussbackend.projections;
import fr.itsonus.bousoleplussbackend.models.Quiz;
import fr.itsonus.bousoleplussbackend.models.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;
import java.util.Map;
import java.util.Set;
@Projection(name = "responseWithQuestion", types = { Quiz.class })
public interface QuizWithResponses {
String getCreatedDate();
@Value("#{target.getResponses()}")
Set<ResponseWithQuestion> getResponses();
// @Value("#{target.getResponses().stream().collect(Collectors.toMap(value -> value, value -> value.length()))}")
// Map<Integer, ResponseWithQuestion> getResponses();
}

View File

@@ -0,0 +1,18 @@
package fr.itsonus.bousoleplussbackend.projections;
import fr.itsonus.bousoleplussbackend.models.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.rest.core.config.Projection;
@Projection(name = "responseWithQuestion", types = { Response.class })
public interface ResponseWithQuestion {
String getComment();
Short getScore();
@Value("#{target.getQuestion().getLabel()}")
String getQuestion();
@Value("#{target.getQuestion().getAxe().getIdentifier()}")
Integer getAxeIdentifier();
}

View File

@@ -0,0 +1,13 @@
package fr.itsonus.bousoleplussbackend.repositories;
import fr.itsonus.bousoleplussbackend.models.Axe;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.Optional;
@RepositoryRestResource
public interface AxeRepository extends CrudRepository<Axe, Long> {
Optional<Axe> findByIdentifier(Integer identifier);
}

View File

@@ -0,0 +1,17 @@
package fr.itsonus.bousoleplussbackend.repositories;
import fr.itsonus.bousoleplussbackend.models.Question;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.stereotype.Repository;
@RepositoryRestResource
public interface QuestionRepository extends CrudRepository<Question, Long> {
@RestResource(path="byAxeId", rel="byAxeId")
@Query("SELECT q FROM Question q JOIN q.axe a WHERE q.axe.id = :id AND user_id = ?#{principal.id}")
Iterable<Question> findAllByAxeId(@Param("id") final Long id);
}

View File

@@ -0,0 +1,22 @@
package fr.itsonus.bousoleplussbackend.repositories;
import fr.itsonus.bousoleplussbackend.models.Quiz;
import fr.itsonus.bousoleplussbackend.models.Response;
import fr.itsonus.bousoleplussbackend.projections.QuizWithResponses;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import java.util.Set;
@RepositoryRestResource(excerptProjection = QuizWithResponses.class)
public interface QuizRepository extends PagingAndSortingRepository<Quiz, Long> {
@RestResource(path = "me", rel = "me")
@Query("SELECT q FROM Quiz q WHERE q.userId = ?#{principal.id}")
Page<Quiz> findAllOfCurrentUser(final Pageable pageable);
}

View File

@@ -0,0 +1,11 @@
package fr.itsonus.bousoleplussbackend.repositories;
import fr.itsonus.bousoleplussbackend.models.QuizScore;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface QuizScoreRepository extends JpaRepository<QuizScore, Long> {
Iterable<QuizScore> findAllByQuizId(Long quizId);
}

View File

@@ -0,0 +1,17 @@
package fr.itsonus.bousoleplussbackend.repositories;
import fr.itsonus.bousoleplussbackend.models.RefreshToken;
import fr.itsonus.bousoleplussbackend.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
Optional<RefreshToken> findByToken(String token);
@Modifying
int deleteByUser(User user);
}

View File

@@ -0,0 +1,11 @@
package fr.itsonus.bousoleplussbackend.repositories;
import fr.itsonus.bousoleplussbackend.models.Response;
import fr.itsonus.bousoleplussbackend.projections.ResponseWithQuestion;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource(excerptProjection = ResponseWithQuestion.class)
public interface ResponseRepository extends CrudRepository<Response, Long> {
}

View File

@@ -0,0 +1,14 @@
package fr.itsonus.bousoleplussbackend.repositories;
import fr.itsonus.bousoleplussbackend.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
}

View File

@@ -0,0 +1,45 @@
package fr.itsonus.bousoleplussbackend.security.jwt;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
@Component
public class AuthEntryPointJwt implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
logger.error("Unauthorized error: {}", authException.getMessage());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
final Map<String, Object> body = new HashMap<>();
body.put("status", HttpServletResponse.SC_UNAUTHORIZED);
body.put("error", "Unauthorized");
body.put("message", authException.getMessage());
body.put("path", request.getServletPath());
final ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), body);
// response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized");
}
}

View File

@@ -0,0 +1,57 @@
package fr.itsonus.bousoleplussbackend.security.jwt;
import fr.itsonus.bousoleplussbackend.security.services.UserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class AuthTokenFilter extends OncePerRequestFilter {
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
var jwt = parseJwt(request);
if (jwt != null && jwtUtils.validateJwtToken(jwt)) {
String username = jwtUtils.getUserNameFromJwtToken(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception e) {
log.error("Cannot set user authentication: {}", e.getMessage());
}
filterChain.doFilter(request, response);
}
private String parseJwt(HttpServletRequest request) {
var headerAuth = request.getHeader("Authorization");
if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
return headerAuth.substring(7);
}
return null;
}
}

View File

@@ -0,0 +1,62 @@
package fr.itsonus.bousoleplussbackend.security.jwt;
import fr.itsonus.bousoleplussbackend.security.services.UserDetailsImpl;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component
public class JwtUtils {
private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
@Value("${app.jwtSecret}")
private String jwtSecret;
@Value("${app.jwtExpirationMs}")
private int jwtExpirationMs;
public String generateJwtToken(UserDetailsImpl userPrincipal) {
return generateTokenFromUsername(userPrincipal.getUsername());
}
public String generateTokenFromUsername(String username) {
return Jwts.builder().setSubject(username).setIssuedAt(new Date())
.setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)).signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public String getUserNameFromJwtToken(String token) {
return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
}
public boolean validateJwtToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}

View File

@@ -0,0 +1,57 @@
package fr.itsonus.bousoleplussbackend.security.services;
import fr.itsonus.bousoleplussbackend.exception.TokenRefreshException;
import fr.itsonus.bousoleplussbackend.models.RefreshToken;
import fr.itsonus.bousoleplussbackend.repositories.RefreshTokenRepository;
import fr.itsonus.bousoleplussbackend.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;
@Service
public class RefreshTokenService {
@Value("${app.jwtRefreshExpirationMs}")
private Long refreshTokenDurationMs;
private final RefreshTokenRepository refreshTokenRepository;
private final UserRepository userRepository;
public RefreshTokenService(final RefreshTokenRepository refreshTokenRepository, final UserRepository userRepository) {
this.refreshTokenRepository = refreshTokenRepository;
this.userRepository = userRepository;
}
public Optional<RefreshToken> findByToken(String token) {
return refreshTokenRepository.findByToken(token);
}
public RefreshToken createRefreshToken(Long userId) {
RefreshToken refreshToken = new RefreshToken();
refreshToken.setUser(userRepository.findById(userId).get());
refreshToken.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
refreshToken.setToken(UUID.randomUUID().toString());
refreshToken = refreshTokenRepository.save(refreshToken);
return refreshToken;
}
public RefreshToken verifyExpiration(RefreshToken token) {
if (token.getExpiryDate().compareTo(Instant.now()) < 0) {
refreshTokenRepository.delete(token);
throw new TokenRefreshException(token.getToken(), "Refresh token was expired. Please make a new signin request");
}
return token;
}
@Transactional
public int deleteByUserId(Long userId) {
return refreshTokenRepository.deleteByUser(userRepository.findById(userId).get());
}
}

View File

@@ -0,0 +1,76 @@
package fr.itsonus.bousoleplussbackend.security.services;
import com.fasterxml.jackson.annotation.JsonIgnore;
import fr.itsonus.bousoleplussbackend.models.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
@Data
@AllArgsConstructor
public class UserDetailsImpl implements UserDetails {
private Long id;
private String username;
@JsonIgnore
private String password;
public static UserDetailsImpl build(User user) {
return new UserDetailsImpl(
user.getId(),
user.getUsername(),
user.getPassword());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of();
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}

View File

@@ -0,0 +1,25 @@
package fr.itsonus.bousoleplussbackend.security.services;
import fr.itsonus.bousoleplussbackend.repositories.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
private final UserRepository userRepository;
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
var user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username));
return UserDetailsImpl.build(user);
}
}

View File

@@ -0,0 +1,16 @@
server.error.include-message=always
app.jwtSecret=generateSecretKey
app.jwtExpirationMs=3600000
app.jwtRefreshExpirationMs=86400000
spring.datasource.url=jdbc:h2:file:${DATABASE_PATH:./data/pluss}
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
logging.level.org.springframework.jdbc.core.StatementCreatorUtils=TRACE

View File

@@ -0,0 +1,69 @@
CREATE SEQUENCE hibernate_sequence START WITH 1 INCREMENT BY 1;
CREATE TABLE users
(
id INTEGER NOT NULL,
username VARCHAR(20) NOT NULL,
password VARCHAR(120) NOT NULL,
CONSTRAINT pk_user PRIMARY KEY (id),
CONSTRAINT uc_user_username UNIQUE (username)
);
CREATE TABLE refresh_token
(
id INTEGER NOT NULL,
expiry_date DATE NOT NULL,
token VARCHAR(500) NOT NULL,
user_id INTEGER NOT NULL,
CONSTRAINT pk_refresh_token PRIMARY KEY (id)
);
CREATE TABLE axe
(
id INTEGER NOT NULL,
identifier INTEGER NOT NULL,
short_title VARCHAR(100) NOT NULL,
title VARCHAR(200) NOT NULL,
color VARCHAR(7) NOT NULL,
CONSTRAINT pk_axe PRIMARY KEY (id),
CONSTRAINT uc_axe_identifier UNIQUE (identifier, title, short_title)
);
CREATE TABLE question
(
id INTEGER NOT NULL,
axe_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
label VARCHAR(200) NOT NULL,
description VARCHAR(500),
CONSTRAINT question_quiz PRIMARY KEY (id)
);
CREATE TABLE quiz
(
id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
created_date TIMESTAMP NOT NULL,
CONSTRAINT pk_quiz PRIMARY KEY (id)
);
CREATE TABLE response
(
id INTEGER NOT NULL,
question_id INTEGER NOT NULL,
quiz_id INTEGER NOT NULL,
score SMALLINT NOT NULL,
comment VARCHAR(500),
CONSTRAINT pk_response PRIMARY KEY (id)
);
-- FIXME id may be wrong
CREATE VIEW quiz_score AS
SELECT
r.quiz_id + a.identifier AS id
,a.identifier AS axe_identifier
,r.quiz_id as quiz_id
,AVG(r.score) as score_avg
FROM response r
INNER JOIN QUESTION q ON q.id = r.question_id
INNER JOIN AXE a ON a.id = q.axe_id
GROUP BY r.quiz_id, a.identifier;

View File

@@ -0,0 +1,101 @@
INSERT INTO axe (id, identifier, short_title, title, color)
VALUES
(nextval('hibernate_sequence'), '1', 'Pouvoir d''agir', 'AGIR en (re)donnant du pouvoir dagir aux territoires et à leurs habitants', '#CA8AE8'),
(nextval('hibernate_sequence'), '2', 'Multi-secteur', 'AGIR sur tous les secteurs de léconomie et lensemble des chaînes de valeur', '#22B9A6');
INSERT INTO users (id, username, password)
VALUES
(nextval('hibernate_sequence'), 'demo', '$2a$10$z83Y96vADEMbDytv4O1h.eBPGcVy2KgvuG8Ftk1t3eGuaDGexrhEW');
INSERT INTO question (id, axe_id, user_id, label, description)
VALUES
(nextval('hibernate_sequence'), 1, 3, 'Le projet favorise-t-il la montée en compétence des parties prenantes?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
(nextval('hibernate_sequence'), 1, 3, 'Le projet permet-il la participation active des parties prenantes?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
(nextval('hibernate_sequence'), 1, 3, 'Le projet est il accessible à différentes parties prenantes?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
(nextval('hibernate_sequence'), 1, 3, 'Le projet a-t-il une animation des liens sociaux?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
(nextval('hibernate_sequence'), 1, 3, 'Le projet favorise-t-il l''inclusion? la mixité sociale? les liens sociaux?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
(nextval('hibernate_sequence'), 2, 3, 'Les ressources locales sont-elles prises en compte?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
(nextval('hibernate_sequence'), 2, 3, 'Plusieurs filières ou thématiques sont-elles abordées dans le projet?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
(nextval('hibernate_sequence'), 2, 3, 'Quel est le degré d''indépendance du projet vis à vis des ressources extèrieures?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.');
-- INSERT INTO axe (id, identifier, title, color)
-- VALUES
-- (nextval('hibernate_sequence'), '1', 'Pouvoir d'agir', 'AGIR en (re)donnant du pouvoir dagir aux territoires et à leurs habitants', '#CA8AE8'),
-- (nextval('hibernate_sequence'), '2', 'Multi-secteur', 'AGIR sur tous les secteurs de léconomie et lensemble des chaînes de valeur', '#22B9A6'),
-- (nextval('hibernate_sequence'), '3', 'Local global', 'AGIR localement en pensant globalement', '#E7E145'),
-- (nextval('hibernate_sequence'), '4', 'Utilité (sociale et écologique)', 'AGIR de manière utile et sobre socialement et écologiquement', '#F39345'),
-- (nextval('hibernate_sequence'), '5', 'Communs', 'AGIR pour préserver et se réapproprier les communs', '#9FCC8B'),
-- (nextval('hibernate_sequence'), '6', 'Démocratie', 'AGIR démocratiquement', '#FDA6C5'),
-- (nextval('hibernate_sequence'), '7', 'Coopération', 'AGIR en encourageant la coopération à tous les niveaux', '#7E91F1'),
-- (nextval('hibernate_sequence'), '8', 'Finances', 'AGIR pour maîtriser les outils de production', '#F37665'),
-- (nextval('hibernate_sequence'), '9', 'Moyens de production', 'AGIR sur les instruments financiers', '#E9D280'),
-- (nextval('hibernate_sequence'), '10','Travail', 'AGIR pour redonner au travail sa valeur véritable', '#7BD1F5');
--
-- INSERT INTO users (id, username, password)
-- VALUES
-- (nextval('hibernate_sequence'), 'demo', '$2a$10$z83Y96vADEMbDytv4O1h.eBPGcVy2KgvuG8Ftk1t3eGuaDGexrhEW');
--
-- INSERT INTO question (id, axe_id, user_id, label, description)
-- VALUES
-- (nextval('hibernate_sequence'), 1, 11, 'Le projet favorise-t-il la montée en compétence des parties prenantes?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 1, 11, 'Le projet permet-il la participation active des parties prenantes?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 1, 11, 'Le projet est il accessible à différentes parties prenantes?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 1, 11, 'Le projet a-t-il une animation des liens sociaux?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 1, 11, 'Le projet favorise-t-il l''inclusion? la mixité sociale? les liens sociaux?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 2, 11, 'Les ressources locales sont-elles prises en compte?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 2, 11, 'Plusieurs filières ou thématiques sont-elles abordées dans le projet?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 2, 11, 'Quel est le degré d''indépendance du projet vis à vis des ressources extèrieures?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 3 ,11, 'Êtes-vous en lien avec des écosystèmes locaux?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 3 ,11, 'Le projet contribue-t-il au développement économique d''autres acteurs du territoire?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 3 ,11, 'Le projet contribue-t-il au rééquilibrage territorial?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 3 ,11, 'Les parties prenantes du projet contribuent-elles à essaimer les bonnes pratiques liées au projet?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 4 ,11, 'Les besoins auxquels répond le projet ont-ils été définis collectivement?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 4 ,11, 'Avez-vous une politique d''achat responsable?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 4 ,11, 'Le projet cherche-t-il à réduire les impacts environnementaux négatifs?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 4 ,11, 'Le projet contribue-t-il à une boucle d''économie circulaire?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 5 ,11, 'Existe-t-il autour du projet une(des) ressource(s) partageable(s) préexistante(s) ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 5 ,11, 'Le projet va-t-il produire une(des) ressource(s) partageable(s) ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 5 ,11, 'Le projet est-il considéré lui-même comme une ressource partageable ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 5 ,11, 'Existe-t-il autour du projet une communauté souhaitant s''occuper de cette ressource partageable ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 5 ,11, 'Existe-t-il des règles d''accès et/ou d''usage à ces ressources ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 6 ,11, 'Existe t-il des lieux et des temps d''expression et de débat ouverts autour du projet ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 6 ,11, 'Les phases essentielles de développement et d''évaluation du projet sont elles soumises au débat ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 6 ,11, 'Tous les groupes représentatifs sont ils invités au débat: élu.e.s, producteur.ices, consommateur.ices, bénéficiaires, chargé.e.s de projet, encadrant.e.s, ....', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 6 ,11, 'Le droit à la parole est-il équitable lors des débats ? (ou les moyens mobilisés permettent-ils l''expression de chacun.e de manière équitable ?)', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 6 ,11, 'La gouvernance permet-elle une prise de décision partagée avec tous les groupes de parties prenantes ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 6 ,11, 'L''accès à la gouvernance par chacun.e est-il lisible et accessible ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 7 ,11, 'Le projet prend-il en compte les contraintes des différentes parties prenantes?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 7 ,11, 'La prise en compte des contraintes des parties prenantes fait-elle évoluer le projet ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 7 ,11, 'La coopération des acteurs permet-elle d''identifier les ressources matérielles et immatérielles locales mobilisables ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 7 ,11, 'La coopération permet-elle de réintégrer les externalités négatives du projet ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 7 ,11, 'La coopération permet-elle le financement des externalités positives du projet de manière monétaire ou non monétaire ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 7 ,11, 'Le processus de coopération fait-il évoluer la façon de travailler de chacun.e ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 7 ,11, 'Existe t-il un processus de partage et de transmission de l''information qui favorise la coopération?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 8 ,11, 'Existe-t-il une réflexion autour de la propriété du foncier/l''immobilier utile au projet ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 8 ,11, 'Existe-t-il une réflexion autour de la propriété des machines et des équipements utiles au projet ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 8 ,11, 'Existe-t-il une réflexion autour de la propriété des process de production et d''innovation ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 8 ,11, 'Êtes-vous libre de décider de l''emploi des outils de production nécessaires au projet ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 8 ,11, 'Êtes-vous libre de décider quel est le niveau souhaitable de productivité du projet ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 8 ,11, 'Un processus d''acquisition en propriété collective est-il à l''œuvre ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 8 ,11, 'Vous sentez vous protégé contre d''éventuelles opérations de délocalisation ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 8 ,11, 'Le projet contribue-t-il à une reprise en main de l''économie locale ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 9 ,11, 'Le projet mobilise-t-il du financement solidaire et/ou participatif (épargne solidaire, crowdfunding, ...) ?','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 9 ,11, 'Le projet mobilise-t-il des financements locaux (micro-crédit, capital-risque solidaire, clubs d''investisseurs locaux, ...) ?','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 9 ,11, 'Le projet intègre-t-il le recours à des boucles locales d''échanges (monnaie complémentaire, troc inter-entreprise, système d''échange local, ...) ?','Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 9 ,11, 'Le projet mobilise-t-il du soutien auprès de fondations ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 9 ,11, 'Le projet cherche-t-il à favoriser la création d''une fondation territoriale ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
--
-- (nextval('hibernate_sequence'), 10 ,11, 'Le projet valorise-t-il les ressources immatérielles (intentions, initiatives, compétences, savoir-faire) des contributeur.ices ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 10 ,11, 'Le projet contribue-t-il à développer les ressources immatérielles des contributeur.ices? (formation, santé, bien-être, confiance) ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 10 ,11, 'Le projet mobilise-t-il différentes formes de contribution : bénévolat, insertion, salariat, ... ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 10 ,11, 'Le projet mobilise-t-il différentes formes de rétribution des contributions : salariat., rétribution contributive,échanges, ...', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.'),
-- (nextval('hibernate_sequence'), 10 ,11, 'La rémunération juste des parties prenantes est-elle prise en compte ?', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quam elementum pulvinar etiam non quam lacus suspendisse faucibus.')

View File

@@ -0,0 +1,13 @@
package fr.itsonus.bousoleplussbackend;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApplicationTests {
@Test
void contextLoads() {
}
}