diff --git a/.project b/.project new file mode 100644 index 0000000..99cba16 --- /dev/null +++ b/.project @@ -0,0 +1,28 @@ + + + OAuth + + + + + + org.eclipse.ui.externaltools.ExternalToolBuilder + full,incremental, + + + LaunchConfigHandle + <project>/.externalToolBuilders/org.eclipse.jdt.core.javabuilder.launch + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/CheckStyle.xml b/CheckStyle.xml new file mode 100755 index 0000000..d68aedd --- /dev/null +++ b/CheckStyle.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CleanUp.xml b/CleanUp.xml new file mode 100644 index 0000000..9df98d2 --- /dev/null +++ b/CleanUp.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Formatter.xml b/Formatter.xml new file mode 100644 index 0000000..b775e22 --- /dev/null +++ b/Formatter.xml @@ -0,0 +1,366 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a9d1e81 --- /dev/null +++ b/LICENSE @@ -0,0 +1,6 @@ +PROPIETARY licence +================== + +Copyright at Edouard DUPIN + +you have no right \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..e2fb3ec --- /dev/null +++ b/pom.xml @@ -0,0 +1,107 @@ + + 4.0.0 + scenarium-store + scenarium-store + 0.0.1-SNAPSHOT + + 2.1 + 2.27 + 2.3.1 + 3.0.7 + + 3.1 + 14 + 14 + + 3.1.1 + + + + + + org.glassfish.jersey + jersey-bom + ${jersey.version} + pom + import + + + + + + + org.glassfish.jersey.inject + jersey-hk2 + + + org.glassfish.jersey.containers + jersey-container-grizzly2-http + + + javax.xml.bind + jaxb-api + ${jaxb.version} + + + javax.ws.rs + javax.ws.rs-api + 2.1.1 + + + com.sun.xml.bind + jaxb-impl + ${jaxb.version} + + + com.sun.istack + istack-commons-runtime + ${istack.version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + + + org.glassfish.jersey.test-framework + jersey-test-framework-core + test + + + org.glassfish.jersey.test-framework.providers + jersey-test-framework-provider-grizzly2 + test + + + mysql + mysql-connector-java + 5.1.45 + + + + + src + test/src + ${project.basedir}/out/maven/ + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.version} + + ${maven.compiler.source} + ${maven.compiler.target} + ${project.build.sourceEncoding} + + + + org.codehaus.mojo + exec-maven-plugin + 1.4.0 + + io.scenarium.oauth.WebLauncher + + + + + + \ No newline at end of file diff --git a/scenarium-oauth.iml b/scenarium-oauth.iml new file mode 100644 index 0000000..1b7c883 --- /dev/null +++ b/scenarium-oauth.iml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/io/scenarium/oauth/CORSFilter.java b/src/io/scenarium/oauth/CORSFilter.java new file mode 100644 index 0000000..e2342ff --- /dev/null +++ b/src/io/scenarium/oauth/CORSFilter.java @@ -0,0 +1,23 @@ +package io.scenarium.oauth; + +import java.io.IOException; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.ext.Provider; + +@Provider +public class CORSFilter implements ContainerResponseFilter { + + @Override + public void filter(ContainerRequestContext request, + ContainerResponseContext response) throws IOException { + response.getHeaders().add("Access-Control-Allow-Origin", "*"); + response.getHeaders().add("Access-Control-Allow-Headers", + "origin, content-type, accept, authorization"); + response.getHeaders().add("Access-Control-Allow-Credentials", "true"); + response.getHeaders().add("Access-Control-Allow-Methods", + "GET, POST, PUT, DELETE, OPTIONS, HEAD"); + } +} + diff --git a/src/io/scenarium/oauth/UserResource.java b/src/io/scenarium/oauth/UserResource.java new file mode 100755 index 0000000..70cf5a2 --- /dev/null +++ b/src/io/scenarium/oauth/UserResource.java @@ -0,0 +1,426 @@ +package io.scenarium.oauth; + +import io.scenarium.oauth.db.DBEntry; +import io.scenarium.oauth.model.*; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Random; + +/** + * @author Mickael BARON (baron.mickael@gmail.com) + */ +@Path("/users") +@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) +public class UserResource { + + public UserResource() { + } + // curl http://localhost:9993/api/users + @GET + public List getUsers() { + System.out.println("getUsers"); + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + List out = new ArrayList<>(); + String query = "SELECT * FROM user"; + try { + Statement st = entry.connection.createStatement(); + ResultSet rs = st.executeQuery(query); + System.out.println ("List of user:"); + while (rs.next()) { + out.add(new User(rs)); + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + entry.disconnect(); + entry = null; + return out; + } + + // curl http://localhost:9993/api/users/3 + @GET + @Path("{id}") + public User getUser(@PathParam("id") long userId) { + System.out.println("getUser " + userId); + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + String query = "SELECT * FROM user WHERE id = ?"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setLong(1, userId); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + User out = new User(rs); + entry.disconnect(); + return out; + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + entry.disconnect(); + return null; + } + + public UserSmall getUserSmall(long userId) { + System.out.println("getUser " + userId); + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + String query = "SELECT id, login, email, authorisationLevel FROM user WHERE id = ?"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setLong(1, userId); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + UserSmall out = new UserSmall(rs); + entry.disconnect(); + // Admin is just for OAuth interface management + if (out.authorisationLevel == State.ADMIN) { + out.authorisationLevel = State.USER; + } + return out; + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + entry.disconnect(); + return null; + } + // curl -d '{"id":3,"login":"HeeroYui","password":"bouloued","email":"yui.heero@gmail.com","emailValidate":0,"newEmail":null,"authorisationLevel":"ADMIN"}' -H "Content-Type: application/json" -X POST http://localhost:9993/api/users + @POST + public Response createUser(User user) { + System.out.println("getUser " + user); + /* + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + String query = "SELECT * FROM user WHERE id = ?"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setLong(1, userId); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + User out = new User(rs); + entry.disconnect(); + return out; + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + entry.disconnect(); + entry = null; + return null; + */ + String result = "User saved ... : " + user; + return Response.status(201).entity(result).build(); + } + + @GET + @Path("/check_login") + public Response checkLogin(@QueryParam("login") String login) { + System.out.println("checkLogin: " + login ); + + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + String query = "SELECT COUNT(*) FROM user WHERE login = ?"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setString(1, login); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + int count = rs.getInt(1); + entry.disconnect(); + if (count >= 1) { + return Response.ok().build(); + } + return Response.status(404).build(); + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + entry.disconnect(); + return Response.status(500).build(); + } + @GET + @Path("/check_email") + public Response checkEmail(@QueryParam("email") String email) { + System.out.println("checkEmail: " + email ); + + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + String query = "SELECT COUNT(*) FROM user WHERE email = ?"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setString(1, email); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + int count = rs.getInt(1); + entry.disconnect(); + if (count >= 1) { + return Response.ok().build(); + } + return Response.status(404).build(); + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + entry.disconnect(); + return Response.status(500).build(); + } + + // Clean all old tokens... + public void clanToken(DBEntry entry) { + String query = "DELETE FROM token WHERE endValidityTime <= now()"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.executeQuery(); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + } + + + @GET + @Path("/check_token") + public Response checkToken(@QueryParam("id") long id, @QueryParam("token") String token) { + System.out.println("checkToken: " + id + " tokk=" + token ); + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + clanToken(entry); + String query = "SELECT * FROM token WHERE userId = ? AND token = ?"; + try { + System.out.println("try ..." ); + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setLong(1, id); + ps.setString(2, token); + ResultSet rs = ps.executeQuery(); + System.out.println("query done ..." ); + if (rs.next()) { + System.out.println("have create a token" ); + Token tok = new Token(rs); + // TODO check time of token !!!! ==> can not be possible, cleaned before ... + if (true) { + UserSmall ret = getUserSmall(id); + if (ret.authorisationLevel != State.USER) { + return Response.status(401).build(); + } + return Response.ok(ret).build(); + } + // Token expired ... + return Response.status(498).build(); + } else { + System.out.println(" error check" ); + // No token available !!! + entry.disconnect(); + return Response.status(404).build(); + } + } catch (SQLException ex) { + ex.printStackTrace(); + } + entry.disconnect(); + return Response.status(500).build(); + } + // curl -d '{"login": "qsdfqsdfqsdfqsdqs", "method": "v1", "time": "10-02-2020 12:31:25 1025", "password": "82c8493f1670fbc1906f371bf3a4f0f9522c374dfc92766cc1a02e0f81523f731b9514be42b7a039d2094f78bf6fac3ddae891b7f0ebc97d6498d9dfc44f441f"}' -H "Content-Type: application/json" -X POST http://localhost:9993/api/users/get_token + + // I do not understand why angular request option before, but this is needed.. + @OPTIONS + @Path("/get_token") + public Response getTokenOption(){ + return Response.ok() + .header("Allow", "POST") + .header("Allow", "OPTIONS") + .build(); + } + + @POST + @Path("/get_token") + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + public Response getToken(DataGetToken data) { + System.out.println("login: " + data.login ); + // check good version: + if (!data.method.contentEquals("v1")) { + String result = "Authentiocate-method-error (wrong version: '" + data.method + "')"; + System.out.println(" result: " + result); + return Response.status(403).entity(result).build(); + } + // verify login or email is correct: + if (data.login.length() < 6) { + String result = "Authentiocate-method-error (email or login too small: '" + data.login + "')"; + System.out.println(" result: " + result); + return Response.status(403).entity(result).build(); + } + // email or login? + String query = "SELECT * FROM user WHERE login = ?"; + if (data.login.contains("@")) { + System.out.println("Check with email"); + query = "SELECT * FROM user WHERE email = ?"; + } else { + System.out.println("Check with login"); + } + User user = null; + // get the user password: + DBEntry entry = new DBEntry(WebLauncher.dbConfig); + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setString(1, data.login); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + user = new User(rs); + } + } catch (SQLException ex) { + ex.printStackTrace(); + String result = "SERVER Internal error"; + System.out.println(" result: " + result); + entry.disconnect(); + return Response.status(500).entity(result).build(); + } + if (user == null || user.id <= 0) { + entry.disconnect(); + String result = "Authentiocate-wrong email/login '" + data.login + "')"; + System.out.println(" result: " + result); + entry.disconnect(); + return Response.status(404).entity(result).build(); + } + // Check the password: + String passwodCheck = getSHA512("login='" + data.login + "';pass='" + user.password + "';date='" + data.time + "'"); + if (!passwodCheck.contentEquals(data.password)) { + String result = "Password error ..."; + System.out.println(" result: " + result); + entry.disconnect(); + return Response.status(403).entity(result).build(); + } + if (user.authorisationLevel != State.USER && user.authorisationLevel != State.ADMIN) { + // unauthorized + return Response.status(401).build(); + } + // Create a token in the BDD + System.out.println("All is good: " + user); + // create token: + String tok = randomString(128); + long idToken = -1; + query = "INSERT INTO `token` (`userId`, `token`, `createTime`, `endValidityTime`) VALUES (?, ?, now(), ADDTIME(now(),'23:45:0'));"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); + ps.setLong(1, user.id); + ps.setString(2, tok); + int insertDone = ps.executeUpdate(); + if (insertDone != 0) { + ResultSet rs = ps.getGeneratedKeys(); + if(rs.next()) { + idToken = rs.getLong(1); + } + //Token token = new Token(rs); + System.out.println("generated_value=" + idToken); + } + } catch (SQLException ex) { + ex.printStackTrace(); + String result = "SERVER Internal error can not create token"; + System.out.println(" result: " + result); + entry.disconnect(); + return Response.status(500).entity(result).build(); + } + if (idToken == -1) { + String result = "SERVER cat not generate token"; + System.out.println(" result: " + result); + entry.disconnect(); + return Response.status(500).entity(result).build(); + } + + query = "SELECT * FROM token WHERE id = ?"; + try { + PreparedStatement ps = entry.connection.prepareStatement(query); + ps.setLong(1, idToken); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + Token out = new Token(rs); + entry.disconnect(); + return Response.status(201).entity(out).build(); + } + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + entry.disconnect(); + String result = "SOME error ???"; + + return Response.status(403).entity(result).build(); + + //return Response.status(500).build(); + } +/* + @Path("/bookings") + public TrainBookingResource getTrainBookingResource() { + System.out.println("TrainResource.getTrainBookingResource()"); + + return new TrainBookingResource(); + } + + */ + + + + + + public String getSHA512(String passwordToHash){ + try { + MessageDigest md = MessageDigest.getInstance("SHA-512"); + byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for(int i=0; i< bytes.length ;i++){ + sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return null; + } + + private static String randomString(int count) { + Random rand = new Random(System.nanoTime()); + String s = new String(); + int nbChar = count; + for (int i = 0; i < nbChar; i++) { + char c = (char) rand.nextInt(); + while ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9')) + c = (char) rand.nextInt(); + s = s + c; + } + return s; + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/io/scenarium/oauth/WebLauncher.java b/src/io/scenarium/oauth/WebLauncher.java new file mode 100755 index 0000000..3710615 --- /dev/null +++ b/src/io/scenarium/oauth/WebLauncher.java @@ -0,0 +1,62 @@ + +package io.scenarium.oauth; + +import io.scenarium.oauth.db.DBConfig; +import io.scenarium.oauth.db.DBEntry; +import org.glassfish.grizzly.http.server.HttpServer; +import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; +import org.glassfish.jersey.logging.LoggingFeature; +import org.glassfish.jersey.server.ResourceConfig; + +import javax.ws.rs.core.UriBuilder; +import java.lang.System.Logger.Level; +import java.net.URI; +import java.sql.SQLException; + + +public class WebLauncher { + private WebLauncher() {} + public static final URI BASE_URI = getBaseURI(); + public static DBConfig dbConfig; + private static URI getBaseURI() { + return UriBuilder.fromUri("http://localhost/oauth/api/").port(17080).build(); + } + + public static void main(String[] args) { + ResourceConfig rc = new ResourceConfig(); + // remove cors ==> all time called by an other system... + rc.register(new CORSFilter()); + // add default resource: + rc.registerClasses(UserResource.class); + rc.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName()); + + dbConfig = new DBConfig("localhost", + 15306, + "root", + "klkhj456gkgtkhjgvkujfhjgkjhgsdfhb3467465fgdhdesfgh", + "oauth"); + /* + DBEntry entry = new DBEntry(dbConfig); + try { + entry.test(); + } catch (SQLException throwables) { + throwables.printStackTrace(); + } + entry.disconnect(); + entry = null; + */ + try { + HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, rc); + server.start(); + + System.out.println(String.format( + "Jersey app started at " + "%s\nHit enter to stop it...", + BASE_URI, BASE_URI)); + + System.in.read(); + server.shutdownNow(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/io/scenarium/oauth/db/DBConfig.java b/src/io/scenarium/oauth/db/DBConfig.java new file mode 100644 index 0000000..8cc6502 --- /dev/null +++ b/src/io/scenarium/oauth/db/DBConfig.java @@ -0,0 +1,49 @@ +package io.scenarium.oauth.db; + +public class DBConfig { + private final String hostname; + private final int port; + private final String login; + private final String password; + private final String dbName; + + public DBConfig(String hostname, Integer port, String login, String password, String dbName) { + if (hostname == null) { + this.hostname = "localhost"; + } else { + this.hostname = hostname; + } + if (port == null) { + this.port = 3306; + } else { + this.port = port; + } + this.login = login; + this.password = password; + this.dbName = dbName; + } + + public String getHostname() { + return hostname; + } + + public int getPort() { + return port; + } + + public String getLogin() { + return login; + } + + public String getPassword() { + return password; + } + + public String getDbName() { + return dbName; + } + + public String getUrl() { + return "jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.dbName + "?useSSL=false&serverTimezone=UTC"; + } +} diff --git a/src/io/scenarium/oauth/db/DBEntry.java b/src/io/scenarium/oauth/db/DBEntry.java new file mode 100644 index 0000000..6e56c7f --- /dev/null +++ b/src/io/scenarium/oauth/db/DBEntry.java @@ -0,0 +1,43 @@ +package io.scenarium.oauth.db; + +import io.scenarium.oauth.model.User; + +import java.sql.*; + +public class DBEntry { + public DBConfig config; + public Connection connection; + + public DBEntry(DBConfig config) { + this.config = config; + connect(); + } + + public void connect() { + try { + connection = DriverManager.getConnection(config.getUrl(), config.getLogin(), config.getPassword()); + } catch (SQLException ex) { + ex.printStackTrace(); + } + + } + + public void disconnect() { + try { + //connection.commit(); + connection.close(); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + public void test() throws SQLException { + String query = "SELECT * FROM user"; + Statement st = connection.createStatement(); + ResultSet rs = st.executeQuery(query); + System.out.println ("List of user:"); + if (rs.next()) { + User user = new User(rs); + System.out.println( " - " + user); + } + } +} diff --git a/src/io/scenarium/oauth/internal/Log.java b/src/io/scenarium/oauth/internal/Log.java new file mode 100644 index 0000000..f099f6b --- /dev/null +++ b/src/io/scenarium/oauth/internal/Log.java @@ -0,0 +1,60 @@ +package io.scenarium.oauth.internal; + +//import io.scenarium.logger.LogLevel; +//import io.scenarium.logger.Logger; + +public class Log { +// private static final String LIB_NAME = "logger"; +// private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME); +// private static final boolean PRINT_CRITICAL = Logger.getNeedPrint(LIB_NAME, LogLevel.CRITICAL); +// private static final boolean PRINT_ERROR = Logger.getNeedPrint(LIB_NAME, LogLevel.ERROR); +// private static final boolean PRINT_WARNING = Logger.getNeedPrint(LIB_NAME, LogLevel.WARNING); +// private static final boolean PRINT_INFO = Logger.getNeedPrint(LIB_NAME, LogLevel.INFO); +// private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG); +// private static final boolean PRINT_VERBOSE = Logger.getNeedPrint(LIB_NAME, LogLevel.VERBOSE); +// private static final boolean PRINT_TODO = Logger.getNeedPrint(LIB_NAME, LogLevel.TODO); +// private static final boolean PRINT_PRINT = Logger.getNeedPrint(LIB_NAME, LogLevel.PRINT); +// +// private Log() {} +// +// public static void print(String data) { +// if (PRINT_PRINT) +// Logger.print(LIB_NAME_DRAW, data); +// } +// +// public static void todo(String data) { +// if (PRINT_TODO) +// Logger.todo(LIB_NAME_DRAW, data); +// } +// +// public static void critical(String data) { +// if (PRINT_CRITICAL) +// Logger.critical(LIB_NAME_DRAW, data); +// } +// +// public static void error(String data) { +// if (PRINT_ERROR) +// Logger.error(LIB_NAME_DRAW, data); +// } +// +// public static void warning(String data) { +// if (PRINT_WARNING) +// Logger.warning(LIB_NAME_DRAW, data); +// } +// +// public static void info(String data) { +// if (PRINT_INFO) +// Logger.info(LIB_NAME_DRAW, data); +// } +// +// public static void debug(String data) { +// if (PRINT_DEBUG) +// Logger.debug(LIB_NAME_DRAW, data); +// } +// +// public static void verbose(String data) { +// if (PRINT_VERBOSE) +// Logger.verbose(LIB_NAME_DRAW, data); +// } + +} diff --git a/src/io/scenarium/oauth/model/Application.java b/src/io/scenarium/oauth/model/Application.java new file mode 100644 index 0000000..7db2e98 --- /dev/null +++ b/src/io/scenarium/oauth/model/Application.java @@ -0,0 +1,49 @@ +package io.scenarium.oauth.model; + +/* + +CREATE TABLE `application` ( + `id` bigint NOT NULL COMMENT 'Unique ID of the application' AUTO_INCREMENT PRIMARY KEY, + `description` text COMMENT 'description of the application', + `token` varchar(128) COLLATE 'latin1_bin' NOT NULL COMMENT 'Token (can be not unique)' +) AUTO_INCREMENT=10; + +*/ + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class Application { + public long id; + public String description; + public String token; + + public Application() { + } + + public Application(long id, String description, String token) { + this.id = id; + this.description = description; + this.token = token; + } + + public Application(ResultSet rs) { + int iii = 1; + try { + this.id = rs.getLong(iii++); + this.description = rs.getString(iii++); + this.token = rs.getString(iii++); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + @Override + public String toString() { + return "Application{" + + "id=" + id + + ", description='" + description + '\'' + + ", token='" + token + '\'' + + '}'; + } +} diff --git a/src/io/scenarium/oauth/model/DataGetToken.java b/src/io/scenarium/oauth/model/DataGetToken.java new file mode 100644 index 0000000..774bf45 --- /dev/null +++ b/src/io/scenarium/oauth/model/DataGetToken.java @@ -0,0 +1,8 @@ +package io.scenarium.oauth.model; + +public class DataGetToken { + public String login; + public String method; + public String time; + public String password; +} diff --git a/src/io/scenarium/oauth/model/State.java b/src/io/scenarium/oauth/model/State.java new file mode 100644 index 0000000..383c3b4 --- /dev/null +++ b/src/io/scenarium/oauth/model/State.java @@ -0,0 +1,12 @@ +package io.scenarium.oauth.model; + +public enum State { + // User has remove his account + REMOVED, + // User has been blocked his account + BLOCKED, + // generic user + USER, + // Administrator + ADMIN +} diff --git a/src/io/scenarium/oauth/model/Token.java b/src/io/scenarium/oauth/model/Token.java new file mode 100644 index 0000000..62dd5a0 --- /dev/null +++ b/src/io/scenarium/oauth/model/Token.java @@ -0,0 +1,57 @@ +package io.scenarium.oauth.model; + +import java.sql.ResultSet; +import java.sql.SQLException; + +/* +CREATE TABLE `token` ( + `id` bigint NOT NULL COMMENT 'Unique ID of the TOKEN' AUTO_INCREMENT PRIMARY KEY, + `userId` bigint NOT NULL COMMENT 'Unique ID of the user', + `token` varchar(128) COLLATE 'latin1_bin' NOT NULL COMMENT 'Token (can be not unique)', + `createTime` datetime NOT NULL COMMENT 'Time the token has been created', + `endValidityTime` datetime NOT NULL COMMENT 'Time of the token end validity' +) AUTO_INCREMENT=10; + + */ +public class Token { + public Long id; + public Long userId; + public String token; + public String createTime; + public String endValidityTime; + + public Token() { + } + + public Token(long id, long userId, String token, String createTime, String endValidityTime) { + this.id = id; + this.userId = userId; + this.token = token; + this.createTime = createTime; + this.endValidityTime = endValidityTime; + } + + public Token(ResultSet rs) { + int iii = 1; + try { + this.id = rs.getLong(iii++); + this.userId = rs.getLong(iii++); + this.token = rs.getString(iii++); + this.createTime = rs.getString(iii++); + this.endValidityTime = rs.getString(iii++); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + + @Override + public String toString() { + return "Token{" + + "id=" + id + + ", userId=" + userId + + ", token='" + token + '\'' + + ", createTime=" + createTime + + ", endValidityTime=" + endValidityTime + + '}'; + } +} diff --git a/src/io/scenarium/oauth/model/User.java b/src/io/scenarium/oauth/model/User.java new file mode 100644 index 0000000..8f3f834 --- /dev/null +++ b/src/io/scenarium/oauth/model/User.java @@ -0,0 +1,85 @@ +package io.scenarium.oauth.model; + +/* +CREATE TABLE `user` ( + `id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY, + `login` varchar(128) COLLATE 'utf8_general_ci' NOT NULL COMMENT 'login of the user', + `password` varchar(128) COLLATE 'latin1_bin' NOT NULL COMMENT 'password of the user hashed (sha512)', + `email` varchar(512) COLLATE 'utf8_general_ci' NOT NULL COMMENT 'email of the user', + `emailValidate` bigint COMMENT 'date of the email validation', + `newEmail` varchar(512) COLLATE 'utf8_general_ci' COMMENT 'email of the user if he want to change', + `authorisationLevel` enum("REMOVED", "BLOCKED", "USER", "ADMIN") NOT NULL DEFAULT 'USER' COMMENT 'user level of authorization' +) AUTO_INCREMENT=10; + + */ + + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Optional; + +public class User { + public Long id; + public String login; + public String password; + public String email; + public Long emailValidate; // time of validation + public String newEmail; + public State authorisationLevel; + + public User() {} + + public User(long id, String login, String password, String email, long emailValidate, String newEmail, State authorisationLevel) { + this.id = id; + this.login = login; + this.password = password; + this.email = email; + this.emailValidate = emailValidate; + this.newEmail = newEmail; + this.authorisationLevel = authorisationLevel; + } + + public User(ResultSet rs) { + int iii = 1; + try { + this.id = rs.getLong(iii++); + this.login = rs.getString(iii++); + this.password = rs.getString(iii++); + this.email = rs.getString(iii++); + this.emailValidate = rs.getLong(iii++); + this.newEmail = rs.getString(iii++); + this.authorisationLevel = State.valueOf(rs.getString(iii++)); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + /* + public void serialize(ResultSet rs) { + int iii = 1; + try { + this.id = rs.getLong(iii++); + this.login = rs.getString(iii++); + this.password = rs.getString(iii++); + this.email = rs.getString(iii++); + this.emailValidate = rs.getLong(iii++); + this.newEmail = rs.getString(iii++); + this.authorisationLevel = State.valueOf(rs.getString(iii++)); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + */ + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", login='" + login + '\'' + + ", password='" + password + '\'' + + ", email='" + email + '\'' + + ", emailValidate=" + emailValidate + + ", newEmail='" + newEmail + '\'' + + ", authorisationLevel=" + authorisationLevel + + '}'; + } +} diff --git a/src/io/scenarium/oauth/model/UserSmall.java b/src/io/scenarium/oauth/model/UserSmall.java new file mode 100644 index 0000000..706d8b9 --- /dev/null +++ b/src/io/scenarium/oauth/model/UserSmall.java @@ -0,0 +1,72 @@ +package io.scenarium.oauth.model; + +/* +CREATE TABLE `user` ( + `id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY, + `login` varchar(128) COLLATE 'utf8_general_ci' NOT NULL COMMENT 'login of the user', + `password` varchar(128) COLLATE 'latin1_bin' NOT NULL COMMENT 'password of the user hashed (sha512)', + `email` varchar(512) COLLATE 'utf8_general_ci' NOT NULL COMMENT 'email of the user', + `emailValidate` bigint COMMENT 'date of the email validation', + `newEmail` varchar(512) COLLATE 'utf8_general_ci' COMMENT 'email of the user if he want to change', + `authorisationLevel` enum("REMOVED", "USER", "ADMIN") NOT NULL COMMENT 'user level of authorization' +) AUTO_INCREMENT=10; + + */ + + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class UserSmall { + public long id; + public String login; + public String email; + public State authorisationLevel; + + public UserSmall() {} + + public UserSmall(long id, String login, String email, State authorisationLevel) { + this.id = id; + this.login = login; + this.email = email; + this.authorisationLevel = authorisationLevel; + } + + public UserSmall(ResultSet rs) { + int iii = 1; + try { + this.id = rs.getLong(iii++); + this.login = rs.getString(iii++); + this.email = rs.getString(iii++); + this.authorisationLevel = State.valueOf(rs.getString(iii++)); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + /* + public void serialize(ResultSet rs) { + int iii = 1; + try { + this.id = rs.getLong(iii++); + this.login = rs.getString(iii++); + this.password = rs.getString(iii++); + this.email = rs.getString(iii++); + this.emailValidate = rs.getLong(iii++); + this.newEmail = rs.getString(iii++); + this.authorisationLevel = State.valueOf(rs.getString(iii++)); + } catch (SQLException ex) { + ex.printStackTrace(); + } + } + */ + + @Override + public String toString() { + return "UserSmall{" + + "id='" + id + '\'' + + ", login='" + login + '\'' + + ", email='" + email + '\'' + + ", authorisationLevel=" + authorisationLevel + + '}'; + } +} diff --git a/src/io/scenarium/oauth/old/Group.java b/src/io/scenarium/oauth/old/Group.java new file mode 100644 index 0000000..df54359 --- /dev/null +++ b/src/io/scenarium/oauth/old/Group.java @@ -0,0 +1,10 @@ +package io.scenarium.oauth.old; + +public class Group { + // Unique ID of the group + public long id; + // Unique ID of the parent group + public long parentGroupId = -1; + // Name of the group (Must be unique) + public String groupName; +} diff --git a/src/io/scenarium/oauth/old/Package.java b/src/io/scenarium/oauth/old/Package.java new file mode 100644 index 0000000..647d459 --- /dev/null +++ b/src/io/scenarium/oauth/old/Package.java @@ -0,0 +1,21 @@ +package io.scenarium.oauth.old; + +public class Package { + // Unique ID of the package/module + public long id; + // name of the package + public String name; + // version of the package + public String version; + // current coverage of the package + public double coverage; + // have module deployed + public long refBinary; + // have test deployed + public long refTest; + // have source deployed + public long refSource; + // have java-doc deployed + public long refJavaDoc; + +} diff --git a/test/src/test/scenarium/oauth/TrainBookingResourceIntegrationTest.java b/test/src/test/scenarium/oauth/TrainBookingResourceIntegrationTest.java new file mode 100644 index 0000000..23a8178 --- /dev/null +++ b/test/src/test/scenarium/oauth/TrainBookingResourceIntegrationTest.java @@ -0,0 +1,139 @@ +package test.scenarium.oauth; + +import java.util.List; +import java.util.logging.Level; + +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Application; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.logging.LoggingFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Assert; +import org.junit.Test; + +/** + * @author Mickael BARON (baron.mickael@gmail.com) + */ +public class TrainBookingResourceIntegrationTest extends JerseyTest { +/* + @Override + protected Application configure() { + ResourceConfig resourceConfig = new ResourceConfig(TrainResource.class, TrainBookingResource.class); + resourceConfig.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName()); + return resourceConfig; + } + + @Test + public void createTrainBookingTest() { + // Given + TrainBooking trainBooking = new TrainBooking(); + trainBooking.setNumberPlaces(3); + trainBooking.setTrainId("TR123"); + Assert.assertNull(trainBooking.getId()); + + // When + Response response = target("/trains/bookings").request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.entity(trainBooking, MediaType.APPLICATION_JSON)); + + // Then + Assert.assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + TrainBooking readEntity = response.readEntity(TrainBooking.class); + Assert.assertNotNull(readEntity); + Assert.assertNotNull(readEntity.getId()); + } + + @Test + public void createTrainBookingWithBadTrainIdTest() { + // Given + TrainBooking trainBooking = new TrainBooking(); + trainBooking.setNumberPlaces(3); + trainBooking.setTrainId("BADTR123"); + + // When + Response response = target("/trains/bookings").request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.entity(trainBooking, MediaType.APPLICATION_JSON)); + + // Then + Assert.assertEquals("Http Response should be 404: ", Status.NOT_FOUND.getStatusCode(), response.getStatus()); + } + + private TrainBooking createTrainBooking(String trainId, int numberPlaces) { + TrainBooking trainBooking = new TrainBooking(); + trainBooking.setNumberPlaces(numberPlaces); + trainBooking.setTrainId(trainId); + Response response = target("/trains/bookings").request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(trainBooking, MediaType.APPLICATION_JSON)); + Assert.assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + + return response.readEntity(TrainBooking.class); + } + + @Test + public void getTrainBookingsTest() { + // Given + TrainBooking currentTrainBooking = createTrainBooking("TR123", 3); + + // When + Response response = target("/trains/bookings").request(MediaType.APPLICATION_JSON_TYPE).get(); + + // Then + Assert.assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + List trainBookings = response.readEntity(new GenericType>() {}); + Assert.assertEquals(1, trainBookings.size()); + Assert.assertEquals(currentTrainBooking.getTrainId(), trainBookings.get(0).getTrainId()); + } + + @Test + public void getTrainBookingTest() { + // Given + TrainBooking currentTrainBooking = createTrainBooking("TR123", 3); + + // When + Response response = target("/trains/bookings").path(currentTrainBooking.getId()).request(MediaType.APPLICATION_JSON_TYPE).get(); + + // Then + Assert.assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void getTrainBookingWithBadTrainBookingIdTest() { + // Given + String trainBookingId = "FAKETRAINBOOKINGID"; + + // When + Response response = target("/trains/bookings").path(trainBookingId).request(MediaType.APPLICATION_JSON_TYPE).get(); + + // Then + Assert.assertEquals("Http Response should be 404: ", Status.NOT_FOUND.getStatusCode(), response.getStatus()); + } + + @Test + public void removeTrainBookingTest() { + // Given + TrainBooking currentTrainBooking = createTrainBooking("TR123", 3); + + // When + Response response = target("/trains/bookings").path(currentTrainBooking.getId()).request(MediaType.APPLICATION_JSON_TYPE).delete(); + + // Then + Assert.assertEquals("Http Response should be 204: ", Status.NO_CONTENT.getStatusCode(), response.getStatus()); + } + + @Test + public void removeTrainBookingWithBadTrainBookingIdTest() { + // Given + String trainBookingId = "FAKETRAINBOOKINGID"; + + // When + Response response = target("/trains/bookings").path(trainBookingId).request(MediaType.APPLICATION_JSON_TYPE).delete(); + + // Then + Assert.assertEquals("Http Response should be 204: ", Status.NO_CONTENT.getStatusCode(), response.getStatus()); + } + + */ +} diff --git a/test/src/test/scenarium/oauth/TrainResourceIntegrationTest.java b/test/src/test/scenarium/oauth/TrainResourceIntegrationTest.java new file mode 100644 index 0000000..a77968f --- /dev/null +++ b/test/src/test/scenarium/oauth/TrainResourceIntegrationTest.java @@ -0,0 +1,86 @@ +package test.scenarium.oauth; + +import java.util.List; +import java.util.logging.Level; + +import javax.ws.rs.core.Application; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.logging.LoggingFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Assert; +import org.junit.Test; + +/** + * @author Mickael BARON (baron.mickael@gmail.com) + */ +public class TrainResourceIntegrationTest extends JerseyTest { +/* + @Override + protected Application configure() { + ResourceConfig resourceConfig = new ResourceConfig(TrainResource.class); + resourceConfig.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName()); + return resourceConfig; + } + + @Test + public void getTrainsTest() { + // Given + + // When + Response response = target("/trains").request(MediaType.APPLICATION_JSON_TYPE).get(); + + // Then + Assert.assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + List readEntities = response.readEntity(new GenericType>() { + }); + Assert.assertNotNull(readEntities); + Assert.assertEquals(3, readEntities.size()); + Assert.assertTrue(readEntities.stream().anyMatch(current -> "TR123".equals(current.getId()))); + } + + @Test + public void getTrainTest() { + // Given + String trainId = "TR123"; + + // When + Response response = target("/trains").path("trainid-" + trainId).request(MediaType.APPLICATION_JSON_TYPE) + .get(); + + // Then + Assert.assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + Assert.assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType()); + Train readEntity = response.readEntity(Train.class); + Assert.assertNotNull(readEntity); + Assert.assertEquals("Poitiers", readEntity.getDeparture()); + } + + @Test + public void searchTrainsByCriteriaTest() { + // Given + String departure = "Poitiers"; + String arrival = "Paris"; + String departureTime = "1710"; + + // When + Response response = target("/trains").path("search").queryParam("departure", departure) + .queryParam("arrival", arrival).queryParam("departure_time", departureTime) + .request(MediaType.APPLICATION_JSON_TYPE).get(); + + // Then + Assert.assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus()); + Assert.assertEquals(departure, response.getHeaderString("departure")); + Assert.assertEquals(arrival, response.getHeaderString("arrival")); + Assert.assertEquals(departureTime, response.getHeaderString("departure_time")); + List readEntities = response.readEntity(new GenericType>() {}); + Assert.assertNotNull(readEntities); + Assert.assertEquals(2, readEntities.size()); + } + + */ +}