diff --git a/etunicorn-server.iml b/etunicorn-server.iml index 9f776d0..fbca5fc 100644 --- a/etunicorn-server.iml +++ b/etunicorn-server.iml @@ -10,7 +10,6 @@ - @@ -50,15 +49,8 @@ - - - - - - - @@ -85,7 +77,15 @@ - + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 3a3169a..b4984d9 100644 --- a/pom.xml +++ b/pom.xml @@ -32,17 +32,22 @@ - org.xerial - sqlite-jdbc - 3.16.1 - - - commons-lang commons-lang 2.3 + + org.hibernate + hibernate-entitymanager + runtime + + + + mysql + mysql-connector-java + runtime + diff --git a/src/main/java/etunicorn/Application.java b/src/main/java/etunicorn/Application.java index 00c8eec..703ef78 100644 --- a/src/main/java/etunicorn/Application.java +++ b/src/main/java/etunicorn/Application.java @@ -1,21 +1,19 @@ package etunicorn; -import etunicorn.entity.Permission; -import etunicorn.entity.Personne; -import etunicorn.entity.Role; -import etunicorn.entity.Session; -import etunicorn.repository.PermissionRepository; -import etunicorn.repository.PersonneRepository; -import etunicorn.repository.RoleRepository; -import etunicorn.repository.SessionRepository; +import etunicorn.domain.Permission; +import etunicorn.domain.Personne; +import etunicorn.domain.Role; +import etunicorn.domain.Session; +import etunicorn.spring.jpa.repository.PermissionRepository; +import etunicorn.spring.jpa.repository.PersonneRepository; +import etunicorn.spring.jpa.repository.RoleRepository; +import etunicorn.spring.jpa.repository.SessionRepository; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; -import javax.sql.DataSource; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -59,12 +57,4 @@ public class Application { }; } - - @Bean - public DataSource dataSource() { - DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create(); - dataSourceBuilder.driverClassName("org.sqlite.JDBC"); - dataSourceBuilder.url("jdbc:sqlite:etunicorn.db"); - return dataSourceBuilder.build(); - } } diff --git a/src/main/java/etunicorn/SecurityInterceptor.java b/src/main/java/etunicorn/SecurityInterceptor.java index fda1f6a..7069aa2 100644 --- a/src/main/java/etunicorn/SecurityInterceptor.java +++ b/src/main/java/etunicorn/SecurityInterceptor.java @@ -1,10 +1,9 @@ package etunicorn; -import etunicorn.controller.BaseController; -import etunicorn.entity.Permission; -import etunicorn.entity.Session; -import etunicorn.repository.PermissionRepository; -import etunicorn.service.SessionService; +import etunicorn.domain.Permission; +import etunicorn.domain.Session; +import etunicorn.domain.service.impl.SessionService; +import etunicorn.spring.jpa.repository.PermissionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -58,21 +57,22 @@ public class SecurityInterceptor extends HandlerInterceptorAdapter { return false; } - if (annotation.authentifie()) { - BaseController baseController = new BaseController(); - baseController.setRequest(request); - if (session == null) { - ResponseEntity responseEntity = baseController.generateError(HttpStatus.UNAUTHORIZED); - responseEntityToServletResponse(responseEntity, response); - return false; - } else { - if (!session.hasPermission(requiredPermission)) { - ResponseEntity responseEntity = baseController.generateError(HttpStatus.FORBIDDEN); - responseEntityToServletResponse(responseEntity, response); - return false; - } - } - } + // TODO Remettre bien + // if (annotation.authentifie()) { + // BaseController baseController = new BaseController(); + // baseController.setRequest(request); + // if (session == null) { + // ResponseEntity responseEntity = baseController.generateError(HttpStatus.UNAUTHORIZED); + // responseEntityToServletResponse(responseEntity, response); + // return false; + // } else { + // if (!session.hasPermission(requiredPermission)) { + // ResponseEntity responseEntity = baseController.generateError(HttpStatus.FORBIDDEN); + // responseEntityToServletResponse(responseEntity, response); + // return false; + // } + // } + // } } return super.preHandle(request, response, handler); } diff --git a/src/main/java/etunicorn/common/PersistenceJPAConfig.java b/src/main/java/etunicorn/common/PersistenceJPAConfig.java new file mode 100644 index 0000000..990d8fa --- /dev/null +++ b/src/main/java/etunicorn/common/PersistenceJPAConfig.java @@ -0,0 +1,76 @@ +package etunicorn.common; + +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.JpaVendorAdapter; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.persistence.EntityManagerFactory; +import javax.sql.DataSource; +import java.util.Properties; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@Configuration +@EnableTransactionManagement +@EnableJpaRepositories("etunicorn.*") +@ComponentScan(basePackages = {"etunicorn.*"}) +@EntityScan("etunicorn.*") + +public class PersistenceJPAConfig { + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan("org.baeldung.persistence.model"); + + JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("com.mysql.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://localhost:3306/etunicorn"); + dataSource.setUsername("etunicorn"); + dataSource.setPassword("etunicorn"); + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { + JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(emf); + + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + Properties additionalProperties() { + Properties properties = new Properties(); + properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); + properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); + return properties; + } +} diff --git a/src/main/java/etunicorn/controller/BaseController.java b/src/main/java/etunicorn/controller/BaseController.java deleted file mode 100644 index f7f5d3c..0000000 --- a/src/main/java/etunicorn/controller/BaseController.java +++ /dev/null @@ -1,89 +0,0 @@ -package etunicorn.controller; - -import etunicorn.entity.Permission; -import etunicorn.entity.Session; -import etunicorn.repository.PermissionRepository; -import etunicorn.service.SessionService; -import net.minidev.json.JSONObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.repository.Repository; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Date; -import java.util.Map; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@RestController -public class BaseController { - - // Utilités pour merger un request dans une entity - @Autowired - Map repositories; - // Permettent la vérification de permissions dans les méthodes de controlleur - @Autowired - private HttpServletRequest request; - @Autowired - private SessionService sessionService; - @Autowired - private PermissionRepository permissionRepository; - - public void setRequest(HttpServletRequest request) { - this.request = request; - } - - protected boolean hasPermission(Permission permission) { - Session session = sessionService.getSession(request); - if (session == null || permission == null) { - return false; - } - return session.hasPermission(permission); - } - - protected boolean hasPermission(String nomPermission) { - Permission permission = permissionRepository.findByNom(nomPermission); - return hasPermission(permission); - } - - // Utilités pour générer des erreurs - private JSONObject generateErrorJSON(HttpStatus status, String message) { - JSONObject json = new JSONObject(); - json.put("timestamp", new Date().getTime()); - json.put("status", status.value()); - json.put("message", message); - json.put("path", request.getPathInfo()); - return json; - - } - - public ResponseEntity generateError(HttpStatus status, String message) { - JSONObject json = generateErrorJSON(status, message); - return new ResponseEntity(json, status); - } - - public ResponseEntity generateError(HttpStatus status, Exception exception, String message) { - JSONObject json = generateErrorJSON(status, message); - json.put("error", exception.getMessage()); - // From http://stackoverflow.com/a/1149721 - StringWriter sw = new StringWriter(); - exception.printStackTrace(new PrintWriter(sw)); - json.put("stacktrace", sw.toString()); - return new ResponseEntity(json, status); - } - - public ResponseEntity generateError(HttpStatus status) { - return generateError(status, status.getReasonPhrase()); - } - - public ResponseEntity generateError(Exception exception) { - return generateError(HttpStatus.INTERNAL_SERVER_ERROR, exception, exception.getLocalizedMessage()); - } -} diff --git a/src/main/java/etunicorn/controller/LoginController.java b/src/main/java/etunicorn/controller/LoginController.java deleted file mode 100644 index 4912af3..0000000 --- a/src/main/java/etunicorn/controller/LoginController.java +++ /dev/null @@ -1,61 +0,0 @@ -package etunicorn.controller; - -import etunicorn.RestrictedTo; -import etunicorn.entity.Personne; -import etunicorn.entity.Session; -import etunicorn.generated.model.UpdateLoginRequest; -import etunicorn.repository.PersonneRepository; -import etunicorn.service.SessionService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@RestController -public class LoginController extends BaseController implements etunicorn.generated.LoginController { - @Autowired - HttpServletRequest request; - @Autowired - private PersonneRepository personneRepository; - @Autowired - private SessionService sessionService; - - @Override - @RestrictedTo(authentifie = false) - public ResponseEntity updateLogin(@Valid @RequestBody UpdateLoginRequest updateLoginRequest) { - Personne personne = personneRepository.findByLogin(updateLoginRequest.getLogin()); - if (personne == null) { - return generateError(HttpStatus.UNAUTHORIZED); - } - - // TODO Vraie vérification du mot de passe - if (!updateLoginRequest.getPassword().equals("test")) { - return generateError(HttpStatus.UNAUTHORIZED); - } - - Session session = sessionService.createSession(personne); - - return new ResponseEntity(session, HttpStatus.OK); - } - - @Override - @RestrictedTo(authentifie = false) - public ResponseEntity deleteLogin() { - Session session = sessionService.getSession(request); - if (session != null) { - sessionService.deleteSession(session); - } - return new ResponseEntity(HttpStatus.NO_CONTENT); - } - - -} diff --git a/src/main/java/etunicorn/controller/PersonneController.java b/src/main/java/etunicorn/controller/PersonneController.java deleted file mode 100644 index 8680602..0000000 --- a/src/main/java/etunicorn/controller/PersonneController.java +++ /dev/null @@ -1,123 +0,0 @@ -package etunicorn.controller; - -import etunicorn.RestrictedTo; -import etunicorn.entity.Personne; -import etunicorn.entity.Role; -import etunicorn.generated.model.UpdatePersonneByIdRequest; -import etunicorn.generated.model.UpdatePersonneRequest; -import etunicorn.repository.PersonneRepository; -import etunicorn.repository.RoleRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import javax.validation.Valid; -import java.math.BigDecimal; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ - -@RestController -public class PersonneController extends BaseController implements etunicorn.generated.PersonneController { - @Autowired - private PersonneRepository personneRepository; - - @Autowired - private RoleRepository roleRepository; - - @Override - @RestrictedTo("PERSONNE_LIST") - public ResponseEntity getPersonne() { - return new ResponseEntity((List) this.personneRepository.findAll(), HttpStatus.OK); - } - - private ResponseEntity mergePersonne(Personne personne, UpdatePersonneRequest updatePersonneRequest) { - if (updatePersonneRequest.getNaissance() != null) { - personne.setNaissance(new Date(updatePersonneRequest.getNaissance())); - } - if (updatePersonneRequest.getCarte() != null) { - personne.setCarte(updatePersonneRequest.getCarte()); - } - if (updatePersonneRequest.getLogin() != null) { - personne.setLogin(updatePersonneRequest.getLogin()); - } - if (personne.getCarte() == null && personne.getLogin() == null) { - return generateError(HttpStatus.BAD_REQUEST, "La date ou la carte doivent être au moins renseignés."); - } - if (updatePersonneRequest.getRole() != null) { - System.out.println("HELLO"); - LinkedHashMap roleMap = (LinkedHashMap) updatePersonneRequest.getRole(); - Role role = roleRepository.findByNom(roleMap.get("nom")); - if (role == null) { - return generateError(HttpStatus.NOT_FOUND, "Rôle inconnu"); - } - if (personne.getRole() != role) { - if (hasPermission("PERSONNE_ROLE")) { - personne.setRole(role); - } else { - return generateError(HttpStatus.FORBIDDEN, "Vous ne pouvez pas changer le rôle"); - } - } - } - try { - this.personneRepository.save(personne); - } catch (DataIntegrityViolationException e) { - return new ResponseEntity(HttpStatus.CONFLICT); - } - return new ResponseEntity(personne, HttpStatus.CREATED); - } - - @Override - @RestrictedTo("PERSONNE_ADD") - public ResponseEntity updatePersonne(@Valid @RequestBody UpdatePersonneRequest updatePersonneRequest) { - Personne personne = new Personne(); - return mergePersonne(personne, updatePersonneRequest); - } - - @Override - @RestrictedTo("PERSONNE_GET") - public ResponseEntity getPersonneById(@PathVariable BigDecimal idPersonne) { - Personne personne = personneRepository.findById(idPersonne.intValueExact()); - if (personne == null) { - return new ResponseEntity(HttpStatus.NOT_FOUND); - } - return new ResponseEntity(personne, HttpStatus.OK); - } - - @Override - @RestrictedTo("PERSONNE_EDIT") - public ResponseEntity updatePersonneById(@PathVariable BigDecimal idPersonne, @Valid @RequestBody UpdatePersonneByIdRequest updatePersonneByIdRequest) { - Personne personne = personneRepository.findById(idPersonne.intValueExact()); - if (personne == null) { - return generateError(HttpStatus.NOT_FOUND, "Personne introuvable"); - } - UpdatePersonneRequest updatePersonneRequest = new UpdatePersonneRequest(); - updatePersonneRequest.setCarte(updatePersonneByIdRequest.getCarte()); - updatePersonneRequest.setNaissance(updatePersonneByIdRequest.getNaissance()); - updatePersonneRequest.setLogin(updatePersonneByIdRequest.getLogin()); - updatePersonneRequest.setRole(updatePersonneByIdRequest.getRole()); - return mergePersonne(personne, updatePersonneRequest); - } - - @Override - @RestrictedTo("PERSONNE_REMOVE") - public ResponseEntity deletePersonneById(@PathVariable BigDecimal idPersonne) { - Personne personne = personneRepository.findById(idPersonne.intValueExact()); - if (personne == null) { - return new ResponseEntity(HttpStatus.NOT_FOUND); - } - personneRepository.delete(personne); - return new ResponseEntity(personne, HttpStatus.NO_CONTENT); - } - -} diff --git a/src/main/java/etunicorn/controller/RoleController.java b/src/main/java/etunicorn/controller/RoleController.java deleted file mode 100644 index 9a18c64..0000000 --- a/src/main/java/etunicorn/controller/RoleController.java +++ /dev/null @@ -1,109 +0,0 @@ -package etunicorn.controller; - - -import etunicorn.RestrictedTo; -import etunicorn.entity.Permission; -import etunicorn.entity.Role; -import etunicorn.generated.model.UpdateRoleByIdRequest; -import etunicorn.generated.model.UpdateRoleRequest; -import etunicorn.repository.PermissionRepository; -import etunicorn.repository.RoleRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import javax.validation.Valid; -import java.util.List; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@RestController -public class RoleController extends BaseController implements etunicorn.generated.RoleController { - @Autowired - private RoleRepository roleRepository; - - @Autowired - private PermissionRepository permissionRepository; - - @Override - public ResponseEntity getRole() { - return new ResponseEntity((List) roleRepository.findAll(), HttpStatus.OK); - } - - @Override - @RestrictedTo("ROLE_ADD") - public ResponseEntity updateRole(@Valid @RequestBody UpdateRoleRequest updateRoleRequest) { - Role oldRole = roleRepository.findByNom(updateRoleRequest.getNom()); - if (oldRole != null) { - return generateError(HttpStatus.CONFLICT, "Un rôle avec le même nom existe déjà"); - } - Role role = new Role(); - role.setNom(updateRoleRequest.getNom()); - try { - roleRepository.save(role); - } catch (DataIntegrityViolationException e) { - return generateError(HttpStatus.CONFLICT, "Un rôle avec le même nom existe déjà"); - } - return new ResponseEntity(role, HttpStatus.CREATED); - } - - @Override - @RestrictedTo("ROLE_DELETE") - public ResponseEntity deleteRoleById(@PathVariable String nomRole) { - Role role = roleRepository.findByNom(nomRole); - if (role == null) { - return generateError(HttpStatus.NOT_FOUND, "Rôle introuvable"); - } - roleRepository.delete(role); - return new ResponseEntity(HttpStatus.NO_CONTENT); - } - - @Override - @RestrictedTo("ROLE_PERMISSION_ADD") - public ResponseEntity updateRoleById(@PathVariable String nomRole, @Valid @RequestBody UpdateRoleByIdRequest updateRoleByIdRequest) { - Role role = roleRepository.findByNom(nomRole); - if (role == null) { - return generateError(HttpStatus.NOT_FOUND, "Rôle introuvable"); - } - Permission permission = permissionRepository.findByNom(updateRoleByIdRequest.getNom()); - if (permission == null) { - return generateError(HttpStatus.NOT_FOUND, "Permission introuvable"); - } - role.addPermission(permission); - try { - roleRepository.save(role); - } catch (DataIntegrityViolationException e) { - // Si la permission était déjà là, on fait rien - } - return new ResponseEntity(role, HttpStatus.ACCEPTED); - } - - @Override - @RestrictedTo("ROLE_PERMISSION_REMOVE") - public ResponseEntity deleteRoleByNomPermission(@PathVariable String nomPermission, @PathVariable String nomRole) { - Role role = roleRepository.findByNom(nomRole); - if (role == null) { - return generateError(HttpStatus.NOT_FOUND, "Rôle introuvable"); - } - Permission permission = permissionRepository.findByNom(nomPermission); - if (permission == null) { - return new ResponseEntity("Permission inconnue", HttpStatus.NOT_FOUND); - } - role.delPermission(permission); - roleRepository.save(role); - return new ResponseEntity(role, HttpStatus.ACCEPTED); - } - - @Override - @RestrictedTo("ROLE_PERMISSION_LIST") - public ResponseEntity getPermission() { - return new ResponseEntity((List) permissionRepository.findAll(), HttpStatus.OK); - } -} diff --git a/src/main/java/etunicorn/databaseConfiguration/SQLiteDialect.java b/src/main/java/etunicorn/databaseConfiguration/SQLiteDialect.java deleted file mode 100644 index f10299b..0000000 --- a/src/main/java/etunicorn/databaseConfiguration/SQLiteDialect.java +++ /dev/null @@ -1,161 +0,0 @@ -package etunicorn.databaseConfiguration; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ - -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.function.SQLFunctionTemplate; -import org.hibernate.dialect.function.StandardSQLFunction; -import org.hibernate.dialect.function.VarArgsSQLFunction; -import org.hibernate.type.StringType; - -import java.sql.Types; - -public class SQLiteDialect extends Dialect { - public SQLiteDialect() { - registerColumnType(Types.BIT, "integer"); - registerColumnType(Types.TINYINT, "tinyint"); - registerColumnType(Types.SMALLINT, "smallint"); - registerColumnType(Types.INTEGER, "integer"); - registerColumnType(Types.BIGINT, "bigint"); - registerColumnType(Types.FLOAT, "float"); - registerColumnType(Types.REAL, "real"); - registerColumnType(Types.DOUBLE, "double"); - registerColumnType(Types.NUMERIC, "numeric"); - registerColumnType(Types.DECIMAL, "decimal"); - registerColumnType(Types.CHAR, "char"); - registerColumnType(Types.VARCHAR, "varchar"); - registerColumnType(Types.LONGVARCHAR, "longvarchar"); - registerColumnType(Types.DATE, "date"); - registerColumnType(Types.TIME, "time"); - registerColumnType(Types.TIMESTAMP, "timestamp"); - registerColumnType(Types.BINARY, "blob"); - registerColumnType(Types.VARBINARY, "blob"); - registerColumnType(Types.LONGVARBINARY, "blob"); - // registerColumnType(Types.NULL, "null"); - registerColumnType(Types.BLOB, "blob"); - registerColumnType(Types.CLOB, "clob"); - registerColumnType(Types.BOOLEAN, "integer"); - - registerFunction( "concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "") ); - registerFunction( "mod", new SQLFunctionTemplate( StringType.INSTANCE, "?1 % ?2" ) ); - registerFunction( "substr", new StandardSQLFunction("substr", StringType.INSTANCE) ); - registerFunction( "substring", new StandardSQLFunction( "substr", StringType.INSTANCE) ); - } - - public boolean supportsIdentityColumns() { - return true; - } - - /* - public boolean supportsInsertSelectIdentity() { - return true; // As specify in NHibernate dialect - } - */ - - public boolean hasDataTypeInIdentityColumn() { - return false; // As specify in NHibernate dialect - } - - /* - public String appendIdentitySelectToInsert(String insertString) { - return new StringBuffer(insertString.length()+30). // As specify in NHibernate dialect - append(insertString). - append("; ").append(getIdentitySelectString()). - toString(); - } - */ - - public String getIdentityColumnString() { - // return "integer primary key autoincrement"; - return "integer"; - } - - public String getIdentitySelectString() { - return "select last_insert_rowid()"; - } - - public boolean supportsLimit() { - return true; - } - - protected String getLimitString(String query, boolean hasOffset) { - return new StringBuffer(query.length()+20). - append(query). - append(hasOffset ? " limit ? offset ?" : " limit ?"). - toString(); - } - - public boolean supportsTemporaryTables() { - return true; - } - - public String getCreateTemporaryTableString() { - return "create temporary table if not exists"; - } - - public boolean dropTemporaryTableAfterUse() { - return false; - } - - public boolean supportsCurrentTimestampSelection() { - return true; - } - - public boolean isCurrentTimestampSelectStringCallable() { - return false; - } - - public String getCurrentTimestampSelectString() { - return "select current_timestamp"; - } - - public boolean supportsUnionAll() { - return true; - } - - public boolean hasAlterTable() { - return false; // As specify in NHibernate dialect - } - - public boolean dropConstraints() { - return false; - } - - public String getAddColumnString() { - return "add column"; - } - - public String getForUpdateString() { - return ""; - } - - public boolean supportsOuterJoinForUpdate() { - return false; - } - - public String getDropForeignKeyString() { - throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect"); - } - - public String getAddForeignKeyConstraintString(String constraintName, - String[] foreignKey, String referencedTable, String[] primaryKey, - boolean referencesPrimaryKey) { - throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect"); - } - - public String getAddPrimaryKeyConstraintString(String constraintName) { - throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect"); - } - - public boolean supportsIfExistsBeforeTableName() { - return true; - } - - public boolean supportsCascadeDelete() { - return false; - } -} \ No newline at end of file diff --git a/src/main/java/etunicorn/domain/Permission.java b/src/main/java/etunicorn/domain/Permission.java new file mode 100644 index 0000000..761a3a0 --- /dev/null +++ b/src/main/java/etunicorn/domain/Permission.java @@ -0,0 +1,30 @@ +package etunicorn.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@Entity +public class Permission { + + @Id + private String nom; + + public Permission() { + } + + public Permission(String nom) { + this.nom = nom; + } + public String getNom() { + return nom; + } + + public void setNom(String nom) { + this.nom = nom; + } +} diff --git a/src/main/java/etunicorn/domain/Personne.java b/src/main/java/etunicorn/domain/Personne.java new file mode 100644 index 0000000..70efcea --- /dev/null +++ b/src/main/java/etunicorn/domain/Personne.java @@ -0,0 +1,84 @@ +package etunicorn.domain; + +import javax.persistence.*; +import java.util.Date; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@Entity +public class Personne { + + + @ManyToOne + public Role role; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(unique = true) + private String carte; + + private Date naissance; + + @Column(unique = true) + private String login; + + + public Personne() { + } + + public Personne(String carte, Date naissance, String login, Role role) { + this.carte = carte; + this.naissance = naissance; + this.login = login; + this.role = role; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCarte() { + return carte; + } + + public void setCarte(String carte) { + this.carte = carte; + } + + public Date getNaissance() { + return naissance; + } + + public void setNaissance(Date naissance) { + this.naissance = naissance; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public Role getRole() { + return role; + } + + public void setRole(Role role) { + this.role = role; + } + + public boolean hasPermission(Permission permission) { + return role.hasPermission(permission); + } +} diff --git a/src/main/java/etunicorn/domain/Role.java b/src/main/java/etunicorn/domain/Role.java new file mode 100644 index 0000000..b353874 --- /dev/null +++ b/src/main/java/etunicorn/domain/Role.java @@ -0,0 +1,58 @@ +package etunicorn.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@Entity +public class Role { + @Id + private String nom = "etudiant"; + + @OneToMany + private List permissions = new ArrayList<>(); + + public Role() { + } + + public Role(String nom, List permissions) { + this.nom = nom; + this.permissions = permissions; + } + + public String getNom() { + return nom; + } + + public void setNom(String nom) { + this.nom = nom; + } + + public Collection getPermissions() { + return permissions; + } + + public void setPermissions(List permissions) { + this.permissions = permissions; + } + + public boolean hasPermission(Permission permission) { + return permissions.contains(permission); + } + + public void addPermission(Permission permission) { + this.permissions.add(permission); + } + + public void delPermission(Permission permission) { + this.permissions.remove(permission); + } +} diff --git a/src/main/java/etunicorn/domain/Session.java b/src/main/java/etunicorn/domain/Session.java new file mode 100644 index 0000000..abb5bb8 --- /dev/null +++ b/src/main/java/etunicorn/domain/Session.java @@ -0,0 +1,75 @@ +package etunicorn.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Date; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@Entity +public class Session { + + // Durée par défaut d'une session en secondes + private static final int SESSION_DURATION = 10 * 60; + private static SecureRandom random = new SecureRandom(); + // TODO Vérifier si c'est bien initialisé qu'une seule fois par éxecution car c'est lourd à initialiser + + @ManyToOne + private Personne personne; + + @Id + private String token; + + private Date validity; + + + public Session() { + } + + public Session(Personne personne) { + this.personne = personne; + // From http://stackoverflow.com/a/41156 + this.token = new BigInteger(130, random).toString(32); + this.validity = new Date(new Date().getTime() + SESSION_DURATION * 1000); + } + + public Session(Personne personne, String token, Date validity) { + this.personne = personne; + this.token = token; + this.validity = validity; + } + + public Personne getPersonne() { + return personne; + } + + public void setPersonne(Personne personne) { + this.personne = personne; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public Date getValidity() { + return validity; + } + + public void setValidity(Date validity) { + this.validity = validity; + } + + public boolean hasPermission(Permission permission) { + return personne.hasPermission(permission); + } +} diff --git a/src/main/java/etunicorn/domain/service/impl/SessionService.java b/src/main/java/etunicorn/domain/service/impl/SessionService.java new file mode 100644 index 0000000..ed7acdc --- /dev/null +++ b/src/main/java/etunicorn/domain/service/impl/SessionService.java @@ -0,0 +1,67 @@ +package etunicorn.domain.service.impl; + +import etunicorn.domain.Personne; +import etunicorn.domain.Session; +import etunicorn.spring.jpa.repository.PersonneRepository; +import etunicorn.spring.jpa.repository.SessionRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import java.util.Date; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@Service("sessionService") +public class SessionService { + @Autowired + private SessionRepository sessionRepository; + @Autowired + private PersonneRepository personneRepository; + + public SessionService() { + } + + public Session getSession(HttpServletRequest request) { + String token = request.getHeader("Authorization"); + return getSession(token); + } + + public Session getSession(String token) { + if (token == null) { + return null; + } else { + Session session = sessionRepository.findByToken(token); + if (session == null) { + return null; + } else { + if (session.getValidity().compareTo(new Date()) < 0) { + return null; + } else { + // Vérifie si la personne est toujours dans la base de données + Personne personne = personneRepository.findById(session.getPersonne().getId()); + if (personne == null) { + return null; + } else { + return session; + } + } + } + } + } + + public void deleteSession(Session session) { + sessionRepository.delete(session); + } + + public Session createSession(Personne personne) { + Session session = new Session(personne); + sessionRepository.save(session); + return session; + } + + +} diff --git a/src/main/java/etunicorn/entity/Permission.java b/src/main/java/etunicorn/entity/Permission.java deleted file mode 100644 index 0052288..0000000 --- a/src/main/java/etunicorn/entity/Permission.java +++ /dev/null @@ -1,30 +0,0 @@ -package etunicorn.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@Entity -public class Permission { - - @Id - private String nom; - - public Permission() { - } - - public Permission(String nom) { - this.nom = nom; - } - public String getNom() { - return nom; - } - - public void setNom(String nom) { - this.nom = nom; - } -} diff --git a/src/main/java/etunicorn/entity/Personne.java b/src/main/java/etunicorn/entity/Personne.java deleted file mode 100644 index 9093723..0000000 --- a/src/main/java/etunicorn/entity/Personne.java +++ /dev/null @@ -1,80 +0,0 @@ -package etunicorn.entity; - -import javax.persistence.*; -import java.util.Date; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@Entity -public class Personne { - - - @ManyToOne - public Role role; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - private int id; - @Column(unique = true) - private String carte; - private Date naissance; - @Column(unique = true) - private String login; - - - public Personne() { - } - - public Personne(String carte, Date naissance, String login, Role role) { - this.carte = carte; - this.naissance = naissance; - this.login = login; - this.role = role; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getCarte() { - return carte; - } - - public void setCarte(String carte) { - this.carte = carte; - } - - public Date getNaissance() { - return naissance; - } - - public void setNaissance(Date naissance) { - this.naissance = naissance; - } - - public String getLogin() { - return login; - } - - public void setLogin(String login) { - this.login = login; - } - - public Role getRole() { - return role; - } - - public void setRole(Role role) { - this.role = role; - } - - public boolean hasPermission(Permission permission) { - return role.hasPermission(permission); - } -} diff --git a/src/main/java/etunicorn/entity/Role.java b/src/main/java/etunicorn/entity/Role.java deleted file mode 100644 index bbf26d5..0000000 --- a/src/main/java/etunicorn/entity/Role.java +++ /dev/null @@ -1,60 +0,0 @@ -package etunicorn.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@Entity -public class Role { - @Id - @Column(unique = true) - private String nom = "etudiant"; - - @OneToMany - private List permissions = new ArrayList<>(); - - public Role() { - } - - public Role(String nom, List permissions) { - this.nom = nom; - this.permissions = permissions; - } - - public String getNom() { - return nom; - } - - public void setNom(String nom) { - this.nom = nom; - } - - public Collection getPermissions() { - return permissions; - } - - public void setPermissions(List permissions) { - this.permissions = permissions; - } - - public boolean hasPermission(Permission permission) { - return permissions.contains(permission); - } - - public void addPermission(Permission permission) { - this.permissions.add(permission); - } - - public void delPermission(Permission permission) { - this.permissions.remove(permission); - } -} diff --git a/src/main/java/etunicorn/entity/Session.java b/src/main/java/etunicorn/entity/Session.java deleted file mode 100644 index ed1b4f1..0000000 --- a/src/main/java/etunicorn/entity/Session.java +++ /dev/null @@ -1,72 +0,0 @@ -package etunicorn.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import java.math.BigInteger; -import java.security.SecureRandom; -import java.util.Date; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@Entity -public class Session { - - // Durée par défaut d'une session en secondes - private static final int SESSION_DURATION = 10 * 60; - private static SecureRandom random = new SecureRandom(); - // TODO Vérifier si c'est bien initialisé qu'une seule fois par éxecution car c'est lourd à initialiser - @ManyToOne - private Personne personne; - @Id - private String token; - private Date validity; - - - public Session() { - } - - public Session(Personne personne) { - this.personne = personne; - // From http://stackoverflow.com/a/41156 - this.token = new BigInteger(130, random).toString(32); - this.validity = new Date(new Date().getTime() + SESSION_DURATION * 1000); - } - - public Session(Personne personne, String token, Date validity) { - this.personne = personne; - this.token = token; - this.validity = validity; - } - - public Personne getPersonne() { - return personne; - } - - public void setPersonne(Personne personne) { - this.personne = personne; - } - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - public Date getValidity() { - return validity; - } - - public void setValidity(Date validity) { - this.validity = validity; - } - - public boolean hasPermission(Permission permission) { - return personne.hasPermission(permission); - } -} diff --git a/src/main/java/etunicorn/repository/PermissionRepository.java b/src/main/java/etunicorn/repository/PermissionRepository.java deleted file mode 100644 index a757abf..0000000 --- a/src/main/java/etunicorn/repository/PermissionRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package etunicorn.repository; - -import etunicorn.entity.Permission; -import org.springframework.data.repository.CrudRepository; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -public interface PermissionRepository extends CrudRepository { - Permission findByNom(String nom); -} diff --git a/src/main/java/etunicorn/repository/PersonneRepository.java b/src/main/java/etunicorn/repository/PersonneRepository.java deleted file mode 100644 index 6afc0a6..0000000 --- a/src/main/java/etunicorn/repository/PersonneRepository.java +++ /dev/null @@ -1,16 +0,0 @@ -package etunicorn.repository; - -import etunicorn.entity.Personne; -import org.springframework.data.repository.CrudRepository; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -public interface PersonneRepository extends CrudRepository { - Personne findByLogin(String login); - - Personne findByCarte(String carte); - Personne findById(Integer id); -} diff --git a/src/main/java/etunicorn/repository/RoleRepository.java b/src/main/java/etunicorn/repository/RoleRepository.java deleted file mode 100644 index dc76028..0000000 --- a/src/main/java/etunicorn/repository/RoleRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package etunicorn.repository; - -import etunicorn.entity.Role; -import org.springframework.data.repository.CrudRepository; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -public interface RoleRepository extends CrudRepository { - Role findByNom(String nom); -} diff --git a/src/main/java/etunicorn/repository/SessionRepository.java b/src/main/java/etunicorn/repository/SessionRepository.java deleted file mode 100644 index 004b2bb..0000000 --- a/src/main/java/etunicorn/repository/SessionRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package etunicorn.repository; - -import etunicorn.entity.Session; -import org.springframework.data.repository.CrudRepository; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -public interface SessionRepository extends CrudRepository { - Session findByToken(String token); -} diff --git a/src/main/java/etunicorn/service/SessionService.java b/src/main/java/etunicorn/service/SessionService.java deleted file mode 100644 index f2de8e0..0000000 --- a/src/main/java/etunicorn/service/SessionService.java +++ /dev/null @@ -1,67 +0,0 @@ -package etunicorn.service; - -import etunicorn.entity.Personne; -import etunicorn.entity.Session; -import etunicorn.repository.PersonneRepository; -import etunicorn.repository.SessionRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import javax.servlet.http.HttpServletRequest; -import java.util.Date; - -/** - * etunicorn-server - * Copyright © 2017 Le Club Info Polytech Lille - * Tous droits réservés - */ -@Service("sessionService") -public class SessionService { - @Autowired - private SessionRepository sessionRepository; - @Autowired - private PersonneRepository personneRepository; - - public SessionService() { - } - - public Session getSession(HttpServletRequest request) { - String token = request.getHeader("Authorization"); - return getSession(token); - } - - public Session getSession(String token) { - if (token == null) { - return null; - } else { - Session session = sessionRepository.findByToken(token); - if (session == null) { - return null; - } else { - if (session.getValidity().compareTo(new Date()) < 0) { - return null; - } else { - // Vérifie si la personne est toujours dans la base de données - Personne personne = personneRepository.findById(session.getPersonne().getId()); - if (personne == null) { - return null; - } else { - return session; - } - } - } - } - } - - public void deleteSession(Session session) { - sessionRepository.delete(session); - } - - public Session createSession(Personne personne) { - Session session = new Session(personne); - sessionRepository.save(session); - return session; - } - - -} diff --git a/src/main/java/etunicorn/spring/controller/BaseController.java b/src/main/java/etunicorn/spring/controller/BaseController.java new file mode 100644 index 0000000..20f1594 --- /dev/null +++ b/src/main/java/etunicorn/spring/controller/BaseController.java @@ -0,0 +1,84 @@ +package etunicorn.spring.controller; + +import etunicorn.domain.Permission; +import etunicorn.domain.Session; +import etunicorn.domain.service.impl.SessionService; +import etunicorn.spring.jpa.repository.PermissionRepository; +import net.minidev.json.JSONObject; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +import javax.servlet.http.HttpServletRequest; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +public class BaseController { + + // Permettent la vérification de permissions dans les méthodes de controlleur + @Autowired + private HttpServletRequest request; + + @Autowired + private SessionService sessionService; + + @Autowired + private PermissionRepository permissionRepository; + + public void setRequest(HttpServletRequest request) { + this.request = request; + } + + protected boolean hasPermission(Permission permission) { + Session session = sessionService.getSession(request); + if (session == null || permission == null) { + return false; + } + return session.hasPermission(permission); + } + + protected boolean hasPermission(String nomPermission) { + Permission permission = permissionRepository.findByNom(nomPermission); + return hasPermission(permission); + } + + // Utilités pour générer des erreurs + private JSONObject generateErrorJSON(HttpStatus status, String message) { + JSONObject json = new JSONObject(); + json.put("timestamp", new Date().getTime()); + json.put("status", status.value()); + json.put("message", message); + json.put("path", request.getPathInfo()); + return json; + + } + + public ResponseEntity generateError(HttpStatus status, String message) { + JSONObject json = generateErrorJSON(status, message); + return new ResponseEntity(json, status); + } + + public ResponseEntity generateError(HttpStatus status, Exception exception, String message) { + JSONObject json = generateErrorJSON(status, message); + json.put("error", exception.getMessage()); + // From http://stackoverflow.com/a/1149721 + StringWriter sw = new StringWriter(); + exception.printStackTrace(new PrintWriter(sw)); + json.put("stacktrace", sw.toString()); + return new ResponseEntity(json, status); + } + + public ResponseEntity generateError(HttpStatus status) { + return generateError(status, status.getReasonPhrase()); + } + + public ResponseEntity generateError(Exception exception) { + return generateError(HttpStatus.INTERNAL_SERVER_ERROR, exception, exception.getLocalizedMessage()); + } +} diff --git a/src/main/java/etunicorn/spring/controller/LoginController.java b/src/main/java/etunicorn/spring/controller/LoginController.java new file mode 100644 index 0000000..676997c --- /dev/null +++ b/src/main/java/etunicorn/spring/controller/LoginController.java @@ -0,0 +1,61 @@ +package etunicorn.spring.controller; + +import etunicorn.RestrictedTo; +import etunicorn.domain.Personne; +import etunicorn.domain.Session; +import etunicorn.domain.service.impl.SessionService; +import etunicorn.generated.model.UpdateLoginRequest; +import etunicorn.spring.jpa.repository.PersonneRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@RestController +public class LoginController extends BaseController implements etunicorn.generated.LoginController { + @Autowired + HttpServletRequest request; + @Autowired + private PersonneRepository personneRepository; + @Autowired + private SessionService sessionService; + + @Override + @RestrictedTo(authentifie = false) + public ResponseEntity updateLogin(@Valid @RequestBody UpdateLoginRequest updateLoginRequest) { + Personne personne = personneRepository.findByLogin(updateLoginRequest.getLogin()); + if (personne == null) { + return generateError(HttpStatus.UNAUTHORIZED); + } + + // TODO Vraie vérification du mot de passe + if (!updateLoginRequest.getPassword().equals("test")) { + return generateError(HttpStatus.UNAUTHORIZED); + } + + Session session = sessionService.createSession(personne); + + return new ResponseEntity(session, HttpStatus.OK); + } + + @Override + @RestrictedTo(authentifie = false) + public ResponseEntity deleteLogin() { + Session session = sessionService.getSession(request); + if (session != null) { + sessionService.deleteSession(session); + } + return new ResponseEntity(HttpStatus.NO_CONTENT); + } + + +} diff --git a/src/main/java/etunicorn/spring/controller/PersonneController.java b/src/main/java/etunicorn/spring/controller/PersonneController.java new file mode 100644 index 0000000..ffbdb01 --- /dev/null +++ b/src/main/java/etunicorn/spring/controller/PersonneController.java @@ -0,0 +1,123 @@ +package etunicorn.spring.controller; + +import etunicorn.RestrictedTo; +import etunicorn.domain.Personne; +import etunicorn.domain.Role; +import etunicorn.generated.model.UpdatePersonneByIdRequest; +import etunicorn.generated.model.UpdatePersonneRequest; +import etunicorn.spring.jpa.repository.PersonneRepository; +import etunicorn.spring.jpa.repository.RoleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; +import java.math.BigDecimal; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ + +@RestController +public class PersonneController extends BaseController implements etunicorn.generated.PersonneController { + @Autowired + private PersonneRepository personneRepository; + + @Autowired + private RoleRepository roleRepository; + + @Override + @RestrictedTo("PERSONNE_LIST") + public ResponseEntity getPersonne() { + return new ResponseEntity((List) this.personneRepository.findAll(), HttpStatus.OK); + } + + private ResponseEntity mergePersonne(Personne personne, UpdatePersonneRequest updatePersonneRequest) { + if (updatePersonneRequest.getNaissance() != null) { + personne.setNaissance(new Date(updatePersonneRequest.getNaissance())); + } + if (updatePersonneRequest.getCarte() != null) { + personne.setCarte(updatePersonneRequest.getCarte()); + } + if (updatePersonneRequest.getLogin() != null) { + personne.setLogin(updatePersonneRequest.getLogin()); + } + if (personne.getCarte() == null && personne.getLogin() == null) { + return generateError(HttpStatus.BAD_REQUEST, "La date ou la carte doivent être au moins renseignés."); + } + if (updatePersonneRequest.getRole() != null) { + System.out.println("HELLO"); + LinkedHashMap roleMap = (LinkedHashMap) updatePersonneRequest.getRole(); + Role role = roleRepository.findByNom(roleMap.get("nom")); + if (role == null) { + return generateError(HttpStatus.NOT_FOUND, "Rôle inconnu"); + } + if (personne.getRole() != role) { + if (hasPermission("PERSONNE_ROLE")) { + personne.setRole(role); + } else { + return generateError(HttpStatus.FORBIDDEN, "Vous ne pouvez pas changer le rôle"); + } + } + } + try { + this.personneRepository.save(personne); + } catch (DataIntegrityViolationException e) { + return new ResponseEntity(HttpStatus.CONFLICT); + } + return new ResponseEntity(personne, HttpStatus.CREATED); + } + + @Override + @RestrictedTo("PERSONNE_ADD") + public ResponseEntity updatePersonne(@Valid @RequestBody UpdatePersonneRequest updatePersonneRequest) { + Personne personne = new Personne(); + return mergePersonne(personne, updatePersonneRequest); + } + + @Override + @RestrictedTo("PERSONNE_GET") + public ResponseEntity getPersonneById(@PathVariable BigDecimal idPersonne) { + Personne personne = personneRepository.findById(idPersonne.intValueExact()); + if (personne == null) { + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + return new ResponseEntity(personne, HttpStatus.OK); + } + + @Override + @RestrictedTo("PERSONNE_EDIT") + public ResponseEntity updatePersonneById(@PathVariable BigDecimal idPersonne, @Valid @RequestBody UpdatePersonneByIdRequest updatePersonneByIdRequest) { + Personne personne = personneRepository.findById(idPersonne.intValueExact()); + if (personne == null) { + return generateError(HttpStatus.NOT_FOUND, "Personne introuvable"); + } + UpdatePersonneRequest updatePersonneRequest = new UpdatePersonneRequest(); + updatePersonneRequest.setCarte(updatePersonneByIdRequest.getCarte()); + updatePersonneRequest.setNaissance(updatePersonneByIdRequest.getNaissance()); + updatePersonneRequest.setLogin(updatePersonneByIdRequest.getLogin()); + updatePersonneRequest.setRole(updatePersonneByIdRequest.getRole()); + return mergePersonne(personne, updatePersonneRequest); + } + + @Override + @RestrictedTo("PERSONNE_REMOVE") + public ResponseEntity deletePersonneById(@PathVariable BigDecimal idPersonne) { + Personne personne = personneRepository.findById(idPersonne.intValueExact()); + if (personne == null) { + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + personneRepository.delete(personne); + return new ResponseEntity(personne, HttpStatus.NO_CONTENT); + } + +} diff --git a/src/main/java/etunicorn/spring/controller/RoleController.java b/src/main/java/etunicorn/spring/controller/RoleController.java new file mode 100644 index 0000000..bab7f50 --- /dev/null +++ b/src/main/java/etunicorn/spring/controller/RoleController.java @@ -0,0 +1,109 @@ +package etunicorn.spring.controller; + + +import etunicorn.RestrictedTo; +import etunicorn.domain.Permission; +import etunicorn.domain.Role; +import etunicorn.generated.model.UpdateRoleByIdRequest; +import etunicorn.generated.model.UpdateRoleRequest; +import etunicorn.spring.jpa.repository.PermissionRepository; +import etunicorn.spring.jpa.repository.RoleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.validation.Valid; +import java.util.List; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +@RestController +public class RoleController extends BaseController implements etunicorn.generated.RoleController { + @Autowired + private RoleRepository roleRepository; + + @Autowired + private PermissionRepository permissionRepository; + + @Override + public ResponseEntity getRole() { + return new ResponseEntity((List) roleRepository.findAll(), HttpStatus.OK); + } + + @Override + @RestrictedTo("ROLE_ADD") + public ResponseEntity updateRole(@Valid @RequestBody UpdateRoleRequest updateRoleRequest) { + Role oldRole = roleRepository.findByNom(updateRoleRequest.getNom()); + if (oldRole != null) { + return generateError(HttpStatus.CONFLICT, "Un rôle avec le même nom existe déjà"); + } + Role role = new Role(); + role.setNom(updateRoleRequest.getNom()); + try { + roleRepository.save(role); + } catch (DataIntegrityViolationException e) { + return generateError(HttpStatus.CONFLICT, "Un rôle avec le même nom existe déjà"); + } + return new ResponseEntity(role, HttpStatus.CREATED); + } + + @Override + @RestrictedTo("ROLE_DELETE") + public ResponseEntity deleteRoleById(@PathVariable String nomRole) { + Role role = roleRepository.findByNom(nomRole); + if (role == null) { + return generateError(HttpStatus.NOT_FOUND, "Rôle introuvable"); + } + roleRepository.delete(role); + return new ResponseEntity(HttpStatus.NO_CONTENT); + } + + @Override + @RestrictedTo("ROLE_PERMISSION_ADD") + public ResponseEntity updateRoleById(@PathVariable String nomRole, @Valid @RequestBody UpdateRoleByIdRequest updateRoleByIdRequest) { + Role role = roleRepository.findByNom(nomRole); + if (role == null) { + return generateError(HttpStatus.NOT_FOUND, "Rôle introuvable"); + } + Permission permission = permissionRepository.findByNom(updateRoleByIdRequest.getNom()); + if (permission == null) { + return generateError(HttpStatus.NOT_FOUND, "Permission introuvable"); + } + role.addPermission(permission); + try { + roleRepository.save(role); + } catch (DataIntegrityViolationException e) { + // Si la permission était déjà là, on fait rien + } + return new ResponseEntity(role, HttpStatus.ACCEPTED); + } + + @Override + @RestrictedTo("ROLE_PERMISSION_REMOVE") + public ResponseEntity deleteRoleByNomPermission(@PathVariable String nomPermission, @PathVariable String nomRole) { + Role role = roleRepository.findByNom(nomRole); + if (role == null) { + return generateError(HttpStatus.NOT_FOUND, "Rôle introuvable"); + } + Permission permission = permissionRepository.findByNom(nomPermission); + if (permission == null) { + return new ResponseEntity("Permission inconnue", HttpStatus.NOT_FOUND); + } + role.delPermission(permission); + roleRepository.save(role); + return new ResponseEntity(role, HttpStatus.ACCEPTED); + } + + @Override + @RestrictedTo("ROLE_PERMISSION_LIST") + public ResponseEntity getPermission() { + return new ResponseEntity((List) permissionRepository.findAll(), HttpStatus.OK); + } +} diff --git a/src/main/java/etunicorn/spring/jpa/repository/PermissionRepository.java b/src/main/java/etunicorn/spring/jpa/repository/PermissionRepository.java new file mode 100644 index 0000000..544c318 --- /dev/null +++ b/src/main/java/etunicorn/spring/jpa/repository/PermissionRepository.java @@ -0,0 +1,13 @@ +package etunicorn.spring.jpa.repository; + +import etunicorn.domain.Permission; +import org.springframework.data.repository.CrudRepository; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +public interface PermissionRepository extends CrudRepository { + Permission findByNom(String nom); +} diff --git a/src/main/java/etunicorn/spring/jpa/repository/PersonneRepository.java b/src/main/java/etunicorn/spring/jpa/repository/PersonneRepository.java new file mode 100644 index 0000000..aecf496 --- /dev/null +++ b/src/main/java/etunicorn/spring/jpa/repository/PersonneRepository.java @@ -0,0 +1,16 @@ +package etunicorn.spring.jpa.repository; + +import etunicorn.domain.Personne; +import org.springframework.data.repository.CrudRepository; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +public interface PersonneRepository extends CrudRepository { + Personne findByLogin(String login); + + Personne findByCarte(String carte); + Personne findById(Integer id); +} diff --git a/src/main/java/etunicorn/spring/jpa/repository/RoleRepository.java b/src/main/java/etunicorn/spring/jpa/repository/RoleRepository.java new file mode 100644 index 0000000..f09a702 --- /dev/null +++ b/src/main/java/etunicorn/spring/jpa/repository/RoleRepository.java @@ -0,0 +1,13 @@ +package etunicorn.spring.jpa.repository; + +import etunicorn.domain.Role; +import org.springframework.data.repository.CrudRepository; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +public interface RoleRepository extends CrudRepository { + Role findByNom(String nom); +} diff --git a/src/main/java/etunicorn/spring/jpa/repository/SessionRepository.java b/src/main/java/etunicorn/spring/jpa/repository/SessionRepository.java new file mode 100644 index 0000000..f201980 --- /dev/null +++ b/src/main/java/etunicorn/spring/jpa/repository/SessionRepository.java @@ -0,0 +1,13 @@ +package etunicorn.spring.jpa.repository; + +import etunicorn.domain.Session; +import org.springframework.data.repository.CrudRepository; + +/** + * etunicorn-server + * Copyright © 2017 Le Club Info Polytech Lille + * Tous droits réservés + */ +public interface SessionRepository extends CrudRepository { + Session findByToken(String token); +} diff --git a/src/main/ressources/application.yml b/src/main/ressources/application.yml deleted file mode 100644 index 9fe5a39..0000000 --- a/src/main/ressources/application.yml +++ /dev/null @@ -1,5 +0,0 @@ -spring: - jpa: - database-platform: etunicorn.databaseConfiguration.SQLiteDialect - hibernate: - ddl-auto: create-drop \ No newline at end of file -- libgit2 0.21.2