[DEV] extract model base for access to be BDD
This commit is contained in:
parent
d330d623d9
commit
62da0f878c
@ -74,6 +74,6 @@ COPY --from=buildFront /tmp/dist /application/karusic/
|
||||
|
||||
WORKDIR /application/
|
||||
|
||||
EXPOSE 17080
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["java", "-Xms64M", "-Xmx1G", "-cp", "/application/application.jar", "org.kar.karusic.WebLauncher"]
|
||||
|
86
back/pom.xml
86
back/pom.xml
@ -4,10 +4,6 @@
|
||||
<artifactId>karusic</artifactId>
|
||||
<version>0.1.0</version>
|
||||
<properties>
|
||||
<jaxrs.version>2.1</jaxrs.version>
|
||||
<jersey.version>2.32</jersey.version>
|
||||
<jaxb.version>2.3.1</jaxb.version>
|
||||
<istack.version>3.0.7</istack.version>
|
||||
|
||||
<maven.compiler.version>3.1</maven.compiler.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
@ -16,87 +12,11 @@
|
||||
<maven.dependency.version>3.1.1</maven.dependency.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey</groupId>
|
||||
<artifactId>jersey-bom</artifactId>
|
||||
<version>${jersey.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-multipart -->
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-multipart</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.inject</groupId>
|
||||
<artifactId>jersey-hk2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.containers</groupId>
|
||||
<artifactId>jersey-container-grizzly2-http</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.xml.bind</groupId>
|
||||
<artifactId>jaxb-api</artifactId>
|
||||
<version>${jaxb.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
<version>2.1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.xml.bind</groupId>
|
||||
<artifactId>jaxb-impl</artifactId>
|
||||
<version>${jaxb.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.sun.istack</groupId>
|
||||
<artifactId>istack-commons-runtime</artifactId>
|
||||
<version>${istack.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
|
||||
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.45</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.glassfish.jersey.media</groupId>
|
||||
<artifactId>jersey-media-json-jackson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.8.10</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
<version>3.0.1</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains</groupId>
|
||||
<artifactId>annotations</artifactId>
|
||||
<version>RELEASE</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.nimbusds</groupId>
|
||||
<artifactId>nimbus-jose-jwt</artifactId>
|
||||
<version>9.22</version>
|
||||
<groupId>kar</groupId>
|
||||
<artifactId>archidata</artifactId>
|
||||
<version>0.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,133 +0,0 @@
|
||||
package org.kar.karusic;
|
||||
|
||||
import org.kar.karusic.db.DBEntry;
|
||||
import org.kar.karusic.model.User;
|
||||
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class UserDB {
|
||||
|
||||
public UserDB() {
|
||||
}
|
||||
|
||||
public static User getUsers(long userId) throws Exception {
|
||||
return SqlWrapper.get(User.class, 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 static User getUserOrCreate(long userId, String userLogin) throws Exception {
|
||||
User user = getUsers(userId);
|
||||
if (user != null) {
|
||||
/*
|
||||
boolean blocked = false;
|
||||
boolean removed = false;
|
||||
if (user.email != userOAuth.email || user.login != userOAuth.login || user.blocked != blocked || user.removed != removed) {
|
||||
updateUsersInfoFromOAuth(userOAuth.id, userOAuth.email, userOAuth.login, blocked, removed);
|
||||
} else {
|
||||
updateUsersConnectionTime(userOAuth.id);
|
||||
}
|
||||
return getUsers(userOAuth.id);
|
||||
*/
|
||||
return user;
|
||||
}
|
||||
createUsersInfoFromOAuth(userId, userLogin);
|
||||
return getUsers(userId);
|
||||
}
|
||||
/*
|
||||
private static void updateUsersConnectionTime(long userId) {
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
String query = "UPDATE `user` SET `lastConnection`=now(3) WHERE `id` = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
ps.setLong(1, userId);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
}
|
||||
entry.disconnect();
|
||||
}
|
||||
|
||||
private static void updateUsersInfoFromOAuth(long userId, String email, String login, boolean blocked, boolean removed) {
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
String query = "UPDATE `user` SET `login`=?, `email`=?, `lastConnection`=now(3), `blocked`=?, `removed`=? WHERE id = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
ps.setString(1, login);
|
||||
ps.setString(2, email);
|
||||
ps.setString(3, blocked ? "TRUE" : "FALSE");
|
||||
ps.setString(4, removed ? "TRUE" : "FALSE");
|
||||
ps.setLong(5, userId);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
}
|
||||
entry.disconnect();
|
||||
}
|
||||
*/
|
||||
|
||||
private static void createUsersInfoFromOAuth(long userId, String login) {
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
String query = "INSERT INTO `user` (`id`, `login`, `lastConnection`, `admin`, `blocked`, `removed`) VALUE (?,?,now(3),'0','0','0')";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
ps.setLong(1, userId);
|
||||
ps.setString(2, login);
|
||||
ps.executeUpdate();
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
}
|
||||
entry.disconnect();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -1,9 +1,6 @@
|
||||
package org.kar.karusic;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
|
||||
import javax.ws.rs.core.UriBuilder;
|
||||
|
||||
@ -21,31 +18,21 @@ import org.kar.karusic.api.HealthCheck;
|
||||
import org.kar.karusic.api.PlaylistResource;
|
||||
import org.kar.karusic.api.TrackResource;
|
||||
import org.kar.karusic.api.UserResource;
|
||||
import org.kar.karusic.db.DBConfig;
|
||||
import org.kar.karusic.filter.AuthenticationFilter;
|
||||
import org.kar.karusic.filter.CORSFilter;
|
||||
import org.kar.karusic.filter.OptionFilter;
|
||||
import org.kar.archidata.GlobalConfiguration;
|
||||
import org.kar.archidata.SqlWrapper;
|
||||
import org.kar.archidata.UpdateJwtPublicKey;
|
||||
import org.kar.archidata.filter.AuthenticationFilter;
|
||||
import org.kar.archidata.filter.CORSFilter;
|
||||
import org.kar.archidata.filter.OptionFilter;
|
||||
import org.kar.archidata.util.ConfigBaseVariable;
|
||||
import org.kar.karusic.model.Track;
|
||||
import org.kar.karusic.util.ConfigVariable;
|
||||
import org.kar.karusic.util.JWTWrapper;
|
||||
|
||||
|
||||
public class WebLauncher {
|
||||
public static DBConfig dbConfig;
|
||||
|
||||
static {
|
||||
dbConfig = new DBConfig(ConfigVariable.getDBHost(),
|
||||
Integer.parseInt(ConfigVariable.getDBPort()),
|
||||
ConfigVariable.getDBLogin(),
|
||||
ConfigVariable.getDBPassword(),
|
||||
ConfigVariable.getDBName());
|
||||
}
|
||||
|
||||
private WebLauncher() {
|
||||
}
|
||||
|
||||
private static URI getBaseURI() {
|
||||
return UriBuilder.fromUri(ConfigVariable.getlocalAddress()).build();
|
||||
return UriBuilder.fromUri(ConfigBaseVariable.getlocalAddress()).build();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
@ -102,21 +89,10 @@ public class WebLauncher {
|
||||
// */
|
||||
// }
|
||||
//
|
||||
// ===================================================================
|
||||
// Configure resources
|
||||
// ===================================================================
|
||||
ResourceConfig rc = new ResourceConfig();
|
||||
// need to uppgrade when server call us...
|
||||
try {
|
||||
JWTWrapper.initLocalTokenRemote(ConfigVariable.getSSOAddress(), "karusic");
|
||||
} catch (Exception e1) {
|
||||
// TODO Auto-generated catch block
|
||||
e1.printStackTrace();
|
||||
System.out.println("Wait 10 seconds ....");
|
||||
try {
|
||||
Thread.sleep(10000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// add multipart models ..
|
||||
rc.register(new MultiPartFeature());
|
||||
@ -149,7 +125,7 @@ public class WebLauncher {
|
||||
//System.out.println(" getDBLogin: '" + ConfigVariable.getDBLogin() + "'");
|
||||
//System.out.println(" getDBPassword: '" + ConfigVariable.getDBPassword() + "'");
|
||||
//System.out.println(" getDBName: '" + ConfigVariable.getDBName() + "'");
|
||||
System.out.println(" ==> " + dbConfig);
|
||||
System.out.println(" ==> " + GlobalConfiguration.dbConfig);
|
||||
System.out.println("OAuth service " + getBaseURI());
|
||||
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
|
||||
@ -160,7 +136,15 @@ public class WebLauncher {
|
||||
}
|
||||
}, "shutdownHook"));
|
||||
|
||||
// run
|
||||
// ===================================================================
|
||||
// start periodic update of the token ...
|
||||
// ===================================================================
|
||||
UpdateJwtPublicKey keyUpdater = new UpdateJwtPublicKey();
|
||||
keyUpdater.start();
|
||||
|
||||
// ===================================================================
|
||||
// run JERSEY
|
||||
// ===================================================================
|
||||
try {
|
||||
server.start();
|
||||
System.out.println("Jersey app started at " + getBaseURI());
|
||||
|
@ -1,15 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import javax.ws.rs.NameBinding;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.METHOD;
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
import static java.lang.annotation.RetentionPolicy.RUNTIME;
|
||||
|
||||
@NameBinding
|
||||
@Retention(RUNTIME)
|
||||
@Target({METHOD})
|
||||
public @interface PermitTokenInURI {
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLAutoIncrement {
|
||||
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ ElementType.TYPE, ElementType.FIELD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLComment {
|
||||
|
||||
String value();
|
||||
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLCreateTime {
|
||||
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target({ ElementType.TYPE, ElementType.FIELD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLDefault {
|
||||
|
||||
String value();
|
||||
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLIfNotExists {
|
||||
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLLimitSize {
|
||||
int value();
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLNotNull {
|
||||
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLNotRead {
|
||||
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLPrimaryKey {
|
||||
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
|
||||
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLTableLinkGeneric {
|
||||
public enum ModelLink {
|
||||
NONE,
|
||||
INTERNAL,
|
||||
EXTERNAL
|
||||
};
|
||||
ModelLink value() default ModelLink.EXTERNAL;
|
||||
}
|
@ -1,14 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLTableName {
|
||||
|
||||
String value();
|
||||
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package org.kar.karusic.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.FIELD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface SQLUpdateTime {
|
||||
|
||||
}
|
@ -2,10 +2,10 @@ package org.kar.karusic.api;
|
||||
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||
import org.kar.karusic.SqlWrapper;
|
||||
import org.kar.archidata.SqlWrapper;
|
||||
import org.kar.archidata.util.DataTools;
|
||||
import org.kar.karusic.model.Album;
|
||||
import org.kar.karusic.model.Track;
|
||||
import org.kar.karusic.util.CoverTools;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ws.rs.*;
|
||||
@ -82,7 +82,7 @@ public class AlbumResource {
|
||||
@FormDataParam("file") InputStream fileInputStream,
|
||||
@FormDataParam("file") FormDataContentDisposition fileMetaData
|
||||
) {
|
||||
return CoverTools.uploadCover(Album.class, id, fileName, fileInputStream, fileMetaData);
|
||||
return DataTools.uploadCover(Album.class, id, fileName, fileInputStream, fileMetaData);
|
||||
}
|
||||
|
||||
@GET
|
||||
|
@ -2,9 +2,9 @@ package org.kar.karusic.api;
|
||||
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||
import org.kar.karusic.SqlWrapper;
|
||||
import org.kar.karusic.model.Artist;
|
||||
import org.kar.karusic.util.CoverTools;
|
||||
import org.kar.archidata.SqlWrapper;
|
||||
import org.kar.archidata.util.DataTools;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ws.rs.*;
|
||||
@ -63,7 +63,7 @@ public class ArtistResource {
|
||||
@FormDataParam("file") InputStream fileInputStream,
|
||||
@FormDataParam("file") FormDataContentDisposition fileMetaData
|
||||
) {
|
||||
return CoverTools.uploadCover(Artist.class, id, fileName, fileInputStream, fileMetaData);
|
||||
return DataTools.uploadCover(Artist.class, id, fileName, fileInputStream, fileMetaData);
|
||||
}
|
||||
|
||||
|
||||
|
@ -2,20 +2,18 @@ package org.kar.karusic.api;
|
||||
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||
import org.kar.karusic.WebLauncher;
|
||||
import org.kar.karusic.annotation.PermitTokenInURI;
|
||||
import org.kar.karusic.db.DBEntry;
|
||||
import org.kar.karusic.filter.GenericContext;
|
||||
import org.kar.karusic.internal.Log;
|
||||
import org.kar.karusic.model.Data;
|
||||
import org.kar.archidata.GlobalConfiguration;
|
||||
import org.kar.archidata.annotation.PermitTokenInURI;
|
||||
import org.kar.archidata.filter.GenericContext;
|
||||
import org.kar.archidata.util.ConfigBaseVariable;
|
||||
import org.kar.archidata.util.DataTools;
|
||||
import org.kar.archidata.db.DBEntry;
|
||||
import org.kar.karusic.model.DataSmall;
|
||||
import org.kar.karusic.util.ConfigVariable;
|
||||
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.CacheControl;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
@ -25,17 +23,10 @@ import javax.ws.rs.core.StreamingOutput;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
|
||||
// https://stackoverflow.com/questions/35367113/jersey-webservice-scalable-approach-to-download-file-and-reply-to-client
|
||||
@ -44,272 +35,9 @@ import java.util.concurrent.TimeUnit;
|
||||
@Path("/data")
|
||||
@Produces({MediaType.APPLICATION_JSON})
|
||||
public class DataResource {
|
||||
private final static int CHUNK_SIZE = 1024 * 1024; // 1MB chunks
|
||||
private final static int CHUNK_SIZE_IN = 50 * 1024 * 1024; // 1MB chunks
|
||||
/**
|
||||
* Upload some data
|
||||
*/
|
||||
private static long tmpFolderId = 1;
|
||||
|
||||
private static void createFolder(String path) throws IOException {
|
||||
if (!Files.exists(java.nio.file.Path.of(path))) {
|
||||
System.out.println("Create folder: " + path);
|
||||
Files.createDirectories(java.nio.file.Path.of(path));
|
||||
}
|
||||
}
|
||||
|
||||
public static long getTmpDataId() {
|
||||
return tmpFolderId++;
|
||||
}
|
||||
|
||||
public static String getTmpFileInData(long tmpFolderId) {
|
||||
String filePath = ConfigVariable.getTmpDataFolder() + File.separator + tmpFolderId;
|
||||
try {
|
||||
createFolder(ConfigVariable.getTmpDataFolder() + File.separator);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public static String getFileData(long tmpFolderId) {
|
||||
String filePath = ConfigVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator + "data";
|
||||
try {
|
||||
createFolder(ConfigVariable.getMediaDataFolder() + File.separator + tmpFolderId + File.separator);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public static Data getWithSha512(String sha512) {
|
||||
System.out.println("find sha512 = " + sha512);
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
String query = "SELECT `id`, `deleted`, `sha512`, `mime_type`, `size` FROM `data` WHERE `sha512` = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
ps.setString(1, sha512);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
if (rs.next()) {
|
||||
Data out = new Data(rs);
|
||||
entry.disconnect();
|
||||
return out;
|
||||
}
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
}
|
||||
entry.disconnect();
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public static Data getWithId(long id) {
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
String query = "SELECT `id`, `deleted`, `sha512`, `mime_type`, `size` FROM `data` WHERE `deleted` = false AND `id` = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
ps.setLong(1, id);
|
||||
ResultSet rs = ps.executeQuery();
|
||||
if (rs.next()) {
|
||||
Data out = new Data(rs);
|
||||
entry.disconnect();
|
||||
return out;
|
||||
}
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
}
|
||||
entry.disconnect();
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Data createNewData(long tmpUID, String originalFileName, String sha512) throws IOException, SQLException {
|
||||
// determine mime type:
|
||||
String mimeType = "";
|
||||
String extension = originalFileName.substring(originalFileName.lastIndexOf('.') + 1);
|
||||
switch (extension.toLowerCase()) {
|
||||
case "jpg":
|
||||
case "jpeg":
|
||||
mimeType = "image/jpeg";
|
||||
break;
|
||||
case "png":
|
||||
mimeType = "image/png";
|
||||
break;
|
||||
case "webp":
|
||||
mimeType = "image/webp";
|
||||
break;
|
||||
case "mka":
|
||||
mimeType = "audio/x-matroska";
|
||||
break;
|
||||
case "mkv":
|
||||
mimeType = "video/x-matroska";
|
||||
break;
|
||||
case "webm":
|
||||
mimeType = "video/webm";
|
||||
break;
|
||||
default:
|
||||
throw new IOException("Can not find the mime type of data input: '" + extension + "'");
|
||||
}
|
||||
String tmpPath = getTmpFileInData(tmpUID);
|
||||
long fileSize = Files.size(Paths.get(tmpPath));
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
long uniqueSQLID = -1;
|
||||
try {
|
||||
// prepare the request:
|
||||
String query = "INSERT INTO `data` (`sha512`, `mime_type`, `size`, `original_name`) VALUES (?, ?, ?, ?)";
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query,
|
||||
Statement.RETURN_GENERATED_KEYS);
|
||||
int iii = 1;
|
||||
ps.setString(iii++, sha512);
|
||||
ps.setString(iii++, mimeType);
|
||||
ps.setLong(iii++, fileSize);
|
||||
ps.setString(iii++, originalFileName);
|
||||
// execute the request
|
||||
int affectedRows = ps.executeUpdate();
|
||||
if (affectedRows == 0) {
|
||||
throw new SQLException("Creating data failed, no rows affected.");
|
||||
}
|
||||
// retreive uid inserted
|
||||
try (ResultSet generatedKeys = ps.getGeneratedKeys()) {
|
||||
if (generatedKeys.next()) {
|
||||
uniqueSQLID = generatedKeys.getLong(1);
|
||||
} else {
|
||||
throw new SQLException("Creating user failed, no ID obtained (1).");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Can not get the UID key inserted ... ");
|
||||
ex.printStackTrace();
|
||||
throw new SQLException("Creating user failed, no ID obtained (2).");
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
entry.disconnect();
|
||||
System.out.println("Add Data raw done. uid data=" + uniqueSQLID);
|
||||
Data out = getWithId(uniqueSQLID);
|
||||
|
||||
String mediaPath = getFileData(out.id);
|
||||
System.out.println("src = " + tmpPath);
|
||||
System.out.println("dst = " + mediaPath);
|
||||
Files.move(Paths.get(tmpPath), Paths.get(mediaPath), StandardCopyOption.ATOMIC_MOVE);
|
||||
|
||||
System.out.println("Move done");
|
||||
// all is done the file is corectly installed...
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
public static void undelete(Long id) {
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
String query = "UPDATE `data` SET `deleted` = false WHERE `id` = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
ps.setLong(1, id);
|
||||
ps.execute();
|
||||
} catch (SQLException throwables) {
|
||||
throwables.printStackTrace();
|
||||
}
|
||||
entry.disconnect();
|
||||
}
|
||||
|
||||
public static String saveTemporaryFile(InputStream uploadedInputStream, long idData) {
|
||||
return saveFile(uploadedInputStream, DataResource.getTmpFileInData(idData));
|
||||
}
|
||||
|
||||
public static void removeTemporaryFile(long idData) {
|
||||
String filepath = DataResource.getTmpFileInData(idData);
|
||||
if (Files.exists(Paths.get(filepath))) {
|
||||
try {
|
||||
Files.delete(Paths.get(filepath));
|
||||
} catch (IOException e) {
|
||||
System.out.println("can not delete temporary file : " + Paths.get(filepath));
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// save uploaded file to a defined location on the server
|
||||
public static String saveFile(InputStream uploadedInputStream, String serverLocation) {
|
||||
String out = "";
|
||||
try {
|
||||
OutputStream outpuStream = new FileOutputStream(new File(
|
||||
serverLocation));
|
||||
int read = 0;
|
||||
byte[] bytes = new byte[CHUNK_SIZE_IN];
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-512");
|
||||
|
||||
outpuStream = new FileOutputStream(new File(serverLocation));
|
||||
while ((read = uploadedInputStream.read(bytes)) != -1) {
|
||||
//System.out.println("write " + read);
|
||||
md.update(bytes, 0, read);
|
||||
outpuStream.write(bytes, 0, read);
|
||||
}
|
||||
System.out.println("Flush input stream ... " + serverLocation);
|
||||
System.out.flush();
|
||||
outpuStream.flush();
|
||||
outpuStream.close();
|
||||
// create the end of sha512
|
||||
byte[] sha512Digest = md.digest();
|
||||
// convert in hexadecimal
|
||||
out = bytesToHex(sha512Digest);
|
||||
uploadedInputStream.close();
|
||||
} catch (IOException ex) {
|
||||
System.out.println("Can not write in temporary file ... ");
|
||||
ex.printStackTrace();
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
System.out.println("Can not find sha512 algorithms");
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// curl http://localhost:9993/api/users/3
|
||||
//@Secured
|
||||
/*
|
||||
@GET
|
||||
@Path("{id}")
|
||||
//@RolesAllowed("GUEST")
|
||||
@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
public Response retriveData(@HeaderParam("Range") String range, @PathParam("id") Long id) throws Exception {
|
||||
return retriveDataFull(range, id, "no-name");
|
||||
}
|
||||
*/
|
||||
|
||||
public static String bytesToHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (byte b : bytes) {
|
||||
sb.append(String.format("%02x", b));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
@POST
|
||||
@Path("/upload")
|
||||
@Consumes(MediaType.MULTIPART_FORM_DATA)
|
||||
public Response uploadFile(FormDataMultiPart form) {
|
||||
|
||||
FormDataBodyPart filePart = form.getField("file");
|
||||
|
||||
ContentDisposition headerOfFilePart = filePart.getContentDisposition();
|
||||
|
||||
InputStream fileInputStream = filePart.getValueAs(InputStream.class);
|
||||
|
||||
String filePath = ConfigVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
||||
//headerOfFilePart.getFileName();
|
||||
|
||||
// save the file to the server
|
||||
saveFile(fileInputStream, filePath);
|
||||
|
||||
String output = "File saved to server location using FormDataMultiPart : " + filePath;
|
||||
|
||||
return Response.status(200).entity(output).build();
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
public DataSmall getSmall(Long id) {
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
DBEntry entry = new DBEntry(GlobalConfiguration.dbConfig);
|
||||
String query = "SELECT `id`, `sha512`, `mime_type`, `size` FROM `data` WHERE `deleted` = false AND `id` = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
@ -338,13 +66,13 @@ public class DataResource {
|
||||
System.out.println("===================================================");
|
||||
//public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||
System.out.println("Upload file: ");
|
||||
String filePath = ConfigVariable.getTmpDataFolder() + File.separator + tmpFolderId++;
|
||||
String filePath = DataTools.getTmpFolder();
|
||||
try {
|
||||
createFolder(ConfigVariable.getTmpDataFolder() + File.separator);
|
||||
DataTools.createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
saveFile(fileInputStream, filePath);
|
||||
DataTools.saveFile(fileInputStream, filePath);
|
||||
return Response.ok("Data uploaded successfully !!").build();
|
||||
//return null;
|
||||
}
|
||||
@ -366,7 +94,7 @@ public class DataResource {
|
||||
type("text/plain").
|
||||
build();
|
||||
}
|
||||
return buildStream(ConfigVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
|
||||
return buildStream(ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
|
||||
}
|
||||
|
||||
@GET
|
||||
@ -387,7 +115,7 @@ public class DataResource {
|
||||
type("text/plain").
|
||||
build();
|
||||
}
|
||||
String filePathName = ConfigVariable.getMediaDataFolder() + File.separator + id + File.separator + "data";
|
||||
String filePathName = ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data";
|
||||
if ( value.mimeType.contentEquals("image/jpeg")
|
||||
|| value.mimeType.contentEquals("image/png")
|
||||
// || value.mimeType.contentEquals("image/webp")
|
||||
@ -436,7 +164,7 @@ public class DataResource {
|
||||
type("text/plain").
|
||||
build();
|
||||
}
|
||||
return buildStream(ConfigVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
|
||||
return buildStream(ConfigBaseVariable.getMediaDataFolder() + File.separator + id + File.separator + "data", range, value.mimeType);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -486,7 +214,7 @@ public class DataResource {
|
||||
|
||||
//System.out.println("request range : " + ranges.length);
|
||||
//Chunk media if the range upper bound is unspecified. Chrome, Opera sends "bytes=0-"
|
||||
long to = CHUNK_SIZE + from;
|
||||
long to = DataTools.CHUNK_SIZE + from;
|
||||
if (ranges.length == 1) {
|
||||
to = file.length() - 1;
|
||||
} else {
|
||||
|
@ -10,94 +10,13 @@ import javax.ws.rs.core.PathSegment;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.core.Response.ResponseBuilder;
|
||||
|
||||
import org.kar.archidata.api.FrontGeneric;
|
||||
import org.kar.karusic.util.ConfigVariable;
|
||||
|
||||
@Path("/karusic")
|
||||
public class Front {
|
||||
private String getExtension(String filename) {
|
||||
if (filename.contains(".")) {
|
||||
return filename.substring(filename.lastIndexOf(".") + 1);
|
||||
}
|
||||
return "";
|
||||
public class Front extends FrontGeneric {
|
||||
public Front() {
|
||||
this.baseFrontFolder = ConfigVariable.getFrontFolder();
|
||||
|
||||
}
|
||||
private Response retrive(String fileName) throws Exception {
|
||||
String filePathName = ConfigVariable.getFrontFolder() + File.separator + fileName;
|
||||
String extention = getExtension(filePathName);
|
||||
String mineType = null;
|
||||
System.out.println("try retrive : '" + filePathName + "' '" + extention + "'");
|
||||
if (extention.length() !=0 && extention.length() <= 5) {
|
||||
if (extention.equalsIgnoreCase("jpg") || extention.equalsIgnoreCase("jpeg")) {
|
||||
mineType = "image/jpeg";
|
||||
} else if (extention.equalsIgnoreCase("gif")) {
|
||||
mineType = "image/gif";
|
||||
} else if (extention.equalsIgnoreCase("png")) {
|
||||
mineType = "image/png";
|
||||
} else if (extention.equalsIgnoreCase("svg")) {
|
||||
mineType = "image/svg+xml";
|
||||
} else if (extention.equalsIgnoreCase("webp")) {
|
||||
mineType = "image/webp";
|
||||
} else if (extention.equalsIgnoreCase("js")) {
|
||||
mineType = "application/javascript";
|
||||
} else if (extention.equalsIgnoreCase("json")) {
|
||||
mineType = "application/json";
|
||||
} else if (extention.equalsIgnoreCase("ico")) {
|
||||
mineType = "image/x-icon";
|
||||
} else if (extention.equalsIgnoreCase("html")) {
|
||||
mineType = "text/html";
|
||||
} else if (extention.equalsIgnoreCase("css")) {
|
||||
mineType = "text/css";
|
||||
} else {
|
||||
return Response.status(403).
|
||||
entity("Not supported model: '" + fileName + "'").
|
||||
type("text/plain").
|
||||
build();
|
||||
}
|
||||
} else {
|
||||
mineType = "text/html";
|
||||
filePathName = ConfigVariable.getFrontFolder() + File.separator + "index.html";
|
||||
}
|
||||
System.out.println(" ==> '" + filePathName + "'");
|
||||
// reads input image
|
||||
File download = new File(filePathName);
|
||||
if (!download.exists()) {
|
||||
return Response.status(404).
|
||||
entity("Not Found: '" + fileName + "' extension='" + extention + "'").
|
||||
type("text/plain").
|
||||
build();
|
||||
}
|
||||
ResponseBuilder response = Response.ok((Object)download);
|
||||
// use this if I want to download the file:
|
||||
//response.header("Content-Disposition", "attachment; filename=" + fileName);
|
||||
CacheControl cc = new CacheControl();
|
||||
cc.setMaxAge(1);
|
||||
cc.setNoCache(true);
|
||||
response.cacheControl(cc);
|
||||
response.type(mineType);
|
||||
|
||||
return response.build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@PermitAll()
|
||||
//@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
//@CacheMaxAge(time = 1, unit = TimeUnit.DAYS)
|
||||
public Response retrive0() throws Exception {
|
||||
return retrive("index.html");
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("{any: .*}")
|
||||
@PermitAll()
|
||||
//@Produces(MediaType.APPLICATION_OCTET_STREAM)
|
||||
//@CacheMaxAge(time = 10, unit = TimeUnit.DAYS)
|
||||
public Response retrive1(@PathParam("any") List<PathSegment> segments) throws Exception {
|
||||
String filename = "";
|
||||
for (PathSegment elem: segments) {
|
||||
if (!filename.isEmpty()) {
|
||||
filename += File.separator;
|
||||
}
|
||||
filename += elem.getPath();
|
||||
}
|
||||
return retrive(filename);
|
||||
}
|
||||
}
|
||||
|
@ -3,9 +3,9 @@ package org.kar.karusic.api;
|
||||
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||
import org.kar.karusic.SqlWrapper;
|
||||
import org.kar.karusic.model.Gender;
|
||||
import org.kar.karusic.util.CoverTools;
|
||||
import org.kar.archidata.SqlWrapper;
|
||||
import org.kar.archidata.util.DataTools;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ws.rs.*;
|
||||
@ -64,7 +64,7 @@ public class GenderResource {
|
||||
@FormDataParam("file") InputStream fileInputStream,
|
||||
@FormDataParam("file") FormDataContentDisposition fileMetaData
|
||||
) {
|
||||
return CoverTools.uploadCover(Gender.class, id, fileName, fileInputStream, fileMetaData);
|
||||
return DataTools.uploadCover(Gender.class, id, fileName, fileInputStream, fileMetaData);
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,9 +1,12 @@
|
||||
package org.kar.karusic.api;
|
||||
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.*;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
|
||||
import org.kar.archidata.util.JWTWrapper;
|
||||
|
||||
@Path("/health_check")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
public class HealthCheck {
|
||||
@ -16,7 +19,10 @@ public class HealthCheck {
|
||||
// todo : do it better...
|
||||
@GET
|
||||
@PermitAll
|
||||
public HealthResult getHealth() {
|
||||
return new HealthResult("alive and kicking");
|
||||
public Response getHealth() {
|
||||
if (JWTWrapper.getPublicKey() == null) {
|
||||
return Response.status(500).entity(new HealthResult("Missing Jwt public token")).build();
|
||||
}
|
||||
return Response.status(200).entity(new HealthResult("alive and kicking")).build();
|
||||
}
|
||||
}
|
||||
|
@ -2,9 +2,9 @@ package org.kar.karusic.api;
|
||||
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||
import org.kar.karusic.SqlWrapper;
|
||||
import org.kar.karusic.model.Playlist;
|
||||
import org.kar.karusic.util.CoverTools;
|
||||
import org.kar.archidata.SqlWrapper;
|
||||
import org.kar.archidata.util.DataTools;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ws.rs.*;
|
||||
@ -83,7 +83,7 @@ public class PlaylistResource {
|
||||
@FormDataParam("file") InputStream fileInputStream,
|
||||
@FormDataParam("file") FormDataContentDisposition fileMetaData
|
||||
) {
|
||||
return CoverTools.uploadCover(Playlist.class, id, fileName, fileInputStream, fileMetaData);
|
||||
return DataTools.uploadCover(Playlist.class, id, fileName, fileInputStream, fileMetaData);
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,15 +1,14 @@
|
||||
package org.kar.karusic.api;
|
||||
|
||||
import org.glassfish.jersey.internal.guava.Lists;
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.glassfish.jersey.media.multipart.FormDataParam;
|
||||
import org.kar.karusic.SqlWrapper;
|
||||
import org.kar.karusic.model.Album;
|
||||
import org.kar.karusic.model.Artist;
|
||||
import org.kar.karusic.model.Data;
|
||||
import org.kar.archidata.model.Data;
|
||||
import org.kar.karusic.model.Gender;
|
||||
import org.kar.karusic.model.Track;
|
||||
import org.kar.karusic.util.CoverTools;
|
||||
import org.kar.archidata.SqlWrapper;
|
||||
import org.kar.archidata.util.DataTools;
|
||||
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
import javax.ws.rs.*;
|
||||
@ -18,11 +17,7 @@ import javax.ws.rs.core.Response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Types;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@ -95,7 +90,7 @@ public class TrackResource {
|
||||
@FormDataParam("file") InputStream fileInputStream,
|
||||
@FormDataParam("file") FormDataContentDisposition fileMetaData
|
||||
) {
|
||||
return CoverTools.uploadCover(Track.class, id, fileName, fileInputStream, fileMetaData);
|
||||
return DataTools.uploadCover(Track.class, id, fileName, fileInputStream, fileMetaData);
|
||||
}
|
||||
|
||||
|
||||
@ -125,12 +120,12 @@ public class TrackResource {
|
||||
) {
|
||||
try {
|
||||
// correct input string stream :
|
||||
fileName = CoverTools.multipartCorrection(fileName);
|
||||
gender = CoverTools.multipartCorrection(gender);
|
||||
artist = CoverTools.multipartCorrection(artist);
|
||||
album = CoverTools.multipartCorrection(album);
|
||||
trackId = CoverTools.multipartCorrection(trackId);
|
||||
title = CoverTools.multipartCorrection(title);
|
||||
fileName = DataTools.multipartCorrection(fileName);
|
||||
gender = DataTools.multipartCorrection(gender);
|
||||
artist = DataTools.multipartCorrection(artist);
|
||||
album = DataTools.multipartCorrection(album);
|
||||
trackId = DataTools.multipartCorrection(trackId);
|
||||
title = DataTools.multipartCorrection(title);
|
||||
|
||||
//public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||
System.out.println("Upload media file: " + fileMetaData);
|
||||
@ -152,27 +147,27 @@ public class TrackResource {
|
||||
}
|
||||
*/
|
||||
|
||||
long tmpUID = DataResource.getTmpDataId();
|
||||
String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID);
|
||||
Data data = DataResource.getWithSha512(sha512);
|
||||
long tmpUID = DataTools.getTmpDataId();
|
||||
String sha512 = DataTools.saveTemporaryFile(fileInputStream, tmpUID);
|
||||
Data data = DataTools.getWithSha512(sha512);
|
||||
if (data == null) {
|
||||
System.out.println("Need to add the data in the BDD ... ");
|
||||
System.out.flush();
|
||||
try {
|
||||
data = DataResource.createNewData(tmpUID, fileName, sha512);
|
||||
data = DataTools.createNewData(tmpUID, fileName, sha512);
|
||||
} catch (IOException ex) {
|
||||
DataResource.removeTemporaryFile(tmpUID);
|
||||
DataTools.removeTemporaryFile(tmpUID);
|
||||
ex.printStackTrace();
|
||||
return Response.notModified("can not create input media").build();
|
||||
} catch (SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
DataResource.removeTemporaryFile(tmpUID);
|
||||
DataTools.removeTemporaryFile(tmpUID);
|
||||
return Response.notModified("Error in SQL insertion ...").build();
|
||||
}
|
||||
} else if (data.deleted == true) {
|
||||
System.out.println("Data already exist but deleted");
|
||||
System.out.flush();
|
||||
DataResource.undelete(data.id);
|
||||
DataTools.undelete(data.id);
|
||||
data.deleted = false;
|
||||
} else {
|
||||
System.out.println("Data already exist ... all good");
|
||||
@ -191,7 +186,7 @@ public class TrackResource {
|
||||
}
|
||||
// NodeSmall typeNode = TypeResource.getWithId(Long.parseLong(typeId));
|
||||
// if (typeNode == null) {
|
||||
// DataResource.removeTemporaryFile(tmpUID);
|
||||
// DataTools.removeTemporaryFile(tmpUID);
|
||||
// return Response.notModified("TypeId does not exist ...").build();
|
||||
// }
|
||||
System.out.println(" ==> " + genderElem);
|
||||
|
@ -1,13 +1,12 @@
|
||||
package org.kar.karusic.api;
|
||||
|
||||
import org.kar.karusic.SqlWrapper;
|
||||
//import org.kar.karusic.UserDB;
|
||||
import org.kar.archidata.GlobalConfiguration;
|
||||
import org.kar.archidata.SqlWrapper;
|
||||
import org.kar.karusic.WebLauncher;
|
||||
import org.kar.karusic.db.DBEntry;
|
||||
import org.kar.karusic.filter.GenericContext;
|
||||
import org.kar.karusic.model.User;
|
||||
import org.kar.karusic.model.UserExtern;
|
||||
import org.kar.karusic.model.UserPerso;
|
||||
import org.kar.archidata.db.DBEntry;
|
||||
import org.kar.archidata.filter.GenericContext;
|
||||
import org.kar.archidata.model.User;
|
||||
import org.kar.karusic.model.UserKarusic;
|
||||
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
@ -22,10 +21,7 @@ import java.security.NoSuchAlgorithmException;
|
||||
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.Random;
|
||||
|
||||
|
||||
@Path("/users")
|
||||
@ -62,10 +58,10 @@ public class UserResource {
|
||||
// curl http://localhost:9993/api/users
|
||||
@GET
|
||||
@RolesAllowed("ADMIN")
|
||||
public List<User> getUsers() {
|
||||
public List<UserKarusic> getUsers() {
|
||||
System.out.println("getUsers");
|
||||
try {
|
||||
return SqlWrapper.gets(User.class, false);
|
||||
return SqlWrapper.gets(UserKarusic.class, false);
|
||||
} catch (Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
@ -89,14 +85,14 @@ public class UserResource {
|
||||
@GET
|
||||
@Path("{id}")
|
||||
@RolesAllowed("ADMIN")
|
||||
public User getUsers(@Context SecurityContext sc, @PathParam("id") long userId) {
|
||||
public UserKarusic getUsers(@Context SecurityContext sc, @PathParam("id") long userId) {
|
||||
System.out.println("getUser " + userId);
|
||||
GenericContext gc = (GenericContext) sc.getUserPrincipal();
|
||||
System.out.println("===================================================");
|
||||
System.out.println("== USER ? " + gc.user);
|
||||
System.out.println("===================================================");
|
||||
try {
|
||||
return SqlWrapper.get(User.class, userId);
|
||||
return SqlWrapper.get(UserKarusic.class, userId);
|
||||
} catch (Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
@ -130,7 +126,7 @@ public class UserResource {
|
||||
// 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
|
||||
@RolesAllowed("ADMIN")
|
||||
public Response createUser(User user) {
|
||||
public Response createUser(UserKarusic user) {
|
||||
System.out.println("getUser " + user);
|
||||
/*
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
@ -161,7 +157,7 @@ public class UserResource {
|
||||
public Response checkLogin(@QueryParam("login") String login) {
|
||||
System.out.println("checkLogin: " + login);
|
||||
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
DBEntry entry = new DBEntry(GlobalConfiguration.dbConfig);
|
||||
String query = "SELECT COUNT(*) FROM user WHERE login = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
@ -189,7 +185,7 @@ public class UserResource {
|
||||
public Response checkEmail(@QueryParam("email") String email) {
|
||||
System.out.println("checkEmail: " + email);
|
||||
|
||||
DBEntry entry = new DBEntry(WebLauncher.dbConfig);
|
||||
DBEntry entry = new DBEntry(GlobalConfiguration.dbConfig);
|
||||
String query = "SELECT COUNT(*) FROM user WHERE email = ?";
|
||||
try {
|
||||
PreparedStatement ps = entry.connection.prepareStatement(query);
|
||||
|
@ -1,60 +0,0 @@
|
||||
package org.kar.karusic.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;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DBConfig{" +
|
||||
"hostname='" + hostname + '\'' +
|
||||
", port=" + port +
|
||||
", login='" + login + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", 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";
|
||||
}
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
package org.kar.karusic.db;
|
||||
|
||||
import org.kar.karusic.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);
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
@ -1,199 +0,0 @@
|
||||
package org.kar.karusic.filter;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import javax.annotation.security.DenyAll;
|
||||
import javax.annotation.security.PermitAll;
|
||||
import javax.annotation.security.RolesAllowed;
|
||||
|
||||
|
||||
import javax.annotation.Priority;
|
||||
import javax.ws.rs.Priorities;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import javax.ws.rs.container.ResourceInfo;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.HttpHeaders;
|
||||
import javax.ws.rs.core.MultivaluedMap;
|
||||
import javax.ws.rs.core.PathSegment;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
|
||||
import org.kar.karusic.UserDB;
|
||||
|
||||
import org.kar.karusic.annotation.PermitTokenInURI;
|
||||
import org.kar.karusic.model.User;
|
||||
import org.kar.karusic.model.UserSmall;
|
||||
import org.kar.karusic.util.JWTWrapper;
|
||||
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
// https://stackoverflow.com/questions/26777083/best-practice-for-rest-token-based-authentication-with-jax-rs-and-jersey
|
||||
// https://stackoverflow.com/questions/26777083/best-practice-for-rest-token-based-authentication-with-jax-rs-and-jersey/45814178#45814178
|
||||
// https://stackoverflow.com/questions/32817210/how-to-access-jersey-resource-secured-by-rolesallowed
|
||||
|
||||
//@PreMatching
|
||||
@Provider
|
||||
@Priority(Priorities.AUTHENTICATION)
|
||||
public class AuthenticationFilter implements ContainerRequestFilter {
|
||||
@Context
|
||||
private ResourceInfo resourceInfo;
|
||||
|
||||
private static final String AUTHENTICATION_SCHEME = "Yota";
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext) throws IOException {
|
||||
/*
|
||||
System.out.println("-----------------------------------------------------");
|
||||
System.out.println("---- Check if have authorization ----");
|
||||
System.out.println("-----------------------------------------------------");
|
||||
System.out.println(" for:" + requestContext.getUriInfo().getPath());
|
||||
*/
|
||||
Method method = resourceInfo.getResourceMethod();
|
||||
// Access denied for all
|
||||
if(method.isAnnotationPresent(DenyAll.class)) {
|
||||
System.out.println(" ==> deny all " + requestContext.getUriInfo().getPath());
|
||||
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity("Access blocked !!!").build());
|
||||
return;
|
||||
}
|
||||
|
||||
//Access allowed for all
|
||||
if( method.isAnnotationPresent(PermitAll.class)) {
|
||||
System.out.println(" ==> permit all " + requestContext.getUriInfo().getPath());
|
||||
// no control ...
|
||||
return;
|
||||
}
|
||||
// this is a security guard, all the API must define their access level:
|
||||
if(!method.isAnnotationPresent(RolesAllowed.class)) {
|
||||
System.out.println(" ==> missin @RolesAllowed " + requestContext.getUriInfo().getPath());
|
||||
requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).entity("Access ILLEGAL !!!").build());
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
// Get the Authorization header from the request
|
||||
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
|
||||
//System.out.println("authorizationHeader: " + authorizationHeader);
|
||||
if(authorizationHeader == null && method.isAnnotationPresent(PermitTokenInURI.class)) {
|
||||
MultivaluedMap<String, String> quaryparam = requestContext.getUriInfo().getQueryParameters();
|
||||
for (Entry<String, List<String>> item: quaryparam.entrySet()) {
|
||||
if (item.getKey().equals(HttpHeaders.AUTHORIZATION)) {
|
||||
if (!item.getValue().isEmpty()) {
|
||||
authorizationHeader = item.getValue().get(0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//System.out.println("authorizationHeader: " + authorizationHeader);
|
||||
|
||||
|
||||
/*
|
||||
System.out.println(" -------------------------------");
|
||||
// this get the parameters inside the pre-parsed element in the request ex: @Path("thumbnail/{id}") generate a map with "id"
|
||||
MultivaluedMap<String, String> pathparam = requestContext.getUriInfo().getPathParameters();
|
||||
for (Entry<String, List<String>> item: pathparam.entrySet()) {
|
||||
System.out.println(" param: " + item.getKey() + " ==>" + item.getValue());
|
||||
}
|
||||
System.out.println(" -------------------------------");
|
||||
// need to add "@QueryParam("p") String token, " in the model
|
||||
//MultivaluedMap<String, String> quaryparam = requestContext.getUriInfo().getQueryParameters();
|
||||
for (Entry<String, List<String>> item: quaryparam.entrySet()) {
|
||||
System.out.println(" query: " + item.getKey() + " ==>" + item.getValue());
|
||||
}
|
||||
System.out.println(" -------------------------------");
|
||||
List<PathSegment> segments = requestContext.getUriInfo().getPathSegments();
|
||||
for (final PathSegment item: segments) {
|
||||
System.out.println(" query: " + item.getPath() + " ==>" + item.getMatrixParameters());
|
||||
}
|
||||
System.out.println(" -------------------------------");
|
||||
MultivaluedMap<String, String> headers = requestContext.getHeaders();
|
||||
for (Entry<String, List<String>> item: headers.entrySet()) {
|
||||
System.out.println(" headers: " + item.getKey() + " ==>" + item.getValue());
|
||||
}
|
||||
System.out.println(" -------------------------------");
|
||||
*/
|
||||
// Validate the Authorization header data Model "Yota userId:token"
|
||||
if (!isTokenBasedAuthentication(authorizationHeader)) {
|
||||
System.out.println("REJECTED unauthorized: " + requestContext.getUriInfo().getPath());
|
||||
abortWithUnauthorized(requestContext);
|
||||
return;
|
||||
}
|
||||
// check JWT token (basic:)
|
||||
|
||||
// Extract the token from the Authorization header (Remove "Yota ")
|
||||
String token = authorizationHeader.substring(AUTHENTICATION_SCHEME.length()).trim();
|
||||
System.out.println("token: " + token);
|
||||
|
||||
|
||||
User user = null;
|
||||
try {
|
||||
user = validateToken(token);
|
||||
} catch (Exception e) {
|
||||
abortWithUnauthorized(requestContext);
|
||||
}
|
||||
if (user == null) {
|
||||
abortWithUnauthorized(requestContext);
|
||||
}
|
||||
// create the security context model:
|
||||
String scheme = requestContext.getUriInfo().getRequestUri().getScheme();
|
||||
MySecurityContext userContext = new MySecurityContext(user, scheme);
|
||||
// retrieve the allowed right:
|
||||
RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
|
||||
List<String> roles = Arrays.asList(rolesAnnotation.value());
|
||||
// check if the user have the right:
|
||||
boolean haveRight = false;
|
||||
for (String role : roles) {
|
||||
if (userContext.isUserInRole(role)) {
|
||||
haveRight = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//Is user valid?
|
||||
if( ! haveRight) {
|
||||
System.out.println("REJECTED not enought right : " + requestContext.getUriInfo().getPath() + " require: " + roles);
|
||||
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity("Not enought RIGHT !!!").build());
|
||||
return;
|
||||
}
|
||||
requestContext.setSecurityContext(userContext);
|
||||
System.out.println("Get local user : " + user);
|
||||
}
|
||||
|
||||
private boolean isTokenBasedAuthentication(String authorizationHeader) {
|
||||
// Check if the Authorization header is valid
|
||||
// It must not be null and must be prefixed with "Bearer" plus a whitespace
|
||||
// The authentication scheme comparison must be case-insensitive
|
||||
return authorizationHeader != null && authorizationHeader.toLowerCase().startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
|
||||
}
|
||||
|
||||
private void abortWithUnauthorized(ContainerRequestContext requestContext) {
|
||||
|
||||
// Abort the filter chain with a 401 status code response
|
||||
// The WWW-Authenticate header is sent along with the response
|
||||
requestContext.abortWith(
|
||||
Response.status(Response.Status.UNAUTHORIZED)
|
||||
.header(HttpHeaders.WWW_AUTHENTICATE,
|
||||
AUTHENTICATION_SCHEME + " base64(HEADER).base64(CONTENT).base64(KEY)")
|
||||
.build());
|
||||
}
|
||||
|
||||
private User validateToken(String authorization) throws Exception {
|
||||
System.out.println(" validate token : " + authorization);
|
||||
JWTClaimsSet ret = JWTWrapper.validateToken(authorization, "KarAuth");
|
||||
// check the token is valid !!! (signed and coherent issuer...
|
||||
if (ret == null) {
|
||||
System.out.println("The token is not valid: '" + authorization + "'");
|
||||
return null;
|
||||
}
|
||||
// check userID
|
||||
String userUID = ret.getSubject();
|
||||
long id = Long.parseLong(userUID);
|
||||
System.out.println("request user: '" + userUID + "'");
|
||||
return UserDB.getUserOrCreate(id, (String)ret.getClaim("login") );
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
package org.kar.karusic.filter;
|
||||
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerResponseContext;
|
||||
import javax.ws.rs.container.ContainerResponseFilter;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
|
||||
|
||||
@Provider
|
||||
public class CORSFilter implements ContainerResponseFilter {
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext request,
|
||||
ContainerResponseContext response) throws IOException {
|
||||
//System.err.println("filter cors ..." + request.toString());
|
||||
|
||||
response.getHeaders().add("Access-Control-Allow-Origin", "*");
|
||||
response.getHeaders().add("Access-Control-Allow-Headers", "*");
|
||||
// "Origin, content-type, Content-type, Accept, authorization, mime-type, filename");
|
||||
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
|
||||
response.getHeaders().add("Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
package org.kar.karusic.filter;
|
||||
|
||||
import org.kar.karusic.model.User;
|
||||
|
||||
import java.security.Principal;
|
||||
|
||||
public class GenericContext implements Principal {
|
||||
|
||||
public User user;
|
||||
|
||||
public GenericContext(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
if (user == null) {
|
||||
return "???";
|
||||
}
|
||||
return user.login;
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
package org.kar.karusic.filter;
|
||||
|
||||
|
||||
import org.kar.karusic.model.User;
|
||||
|
||||
import javax.ws.rs.core.SecurityContext;
|
||||
import java.security.Principal;
|
||||
|
||||
// https://simplapi.wordpress.com/2015/09/19/jersey-jax-rs-securitycontext-in-action/
|
||||
class MySecurityContext implements SecurityContext {
|
||||
|
||||
private final GenericContext contextPrincipale;
|
||||
private final String sheme;
|
||||
|
||||
public MySecurityContext(User user, String sheme) {
|
||||
this.contextPrincipale = new GenericContext(user);
|
||||
this.sheme = sheme;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Principal getUserPrincipal() {
|
||||
return contextPrincipale;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserInRole(String role) {
|
||||
if (role.contentEquals("ADMIN")) {
|
||||
return contextPrincipale.user.admin == true;
|
||||
}
|
||||
if (role.contentEquals("USER")) {
|
||||
// if not an admin, this is a user...
|
||||
return true; //contextPrincipale.user.admin == false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSecure() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAuthenticationScheme() {
|
||||
return "Yota";
|
||||
}
|
||||
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
package org.kar.karusic.filter;
|
||||
|
||||
import javax.ws.rs.container.ContainerRequestContext;
|
||||
import javax.ws.rs.container.ContainerRequestFilter;
|
||||
import javax.ws.rs.container.PreMatching;
|
||||
import javax.ws.rs.core.Response;
|
||||
import javax.ws.rs.ext.Provider;
|
||||
import java.io.IOException;
|
||||
|
||||
@Provider
|
||||
@PreMatching
|
||||
public class OptionFilter implements ContainerRequestFilter {
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext) throws IOException {
|
||||
if (requestContext.getMethod().contentEquals("OPTIONS")) {
|
||||
requestContext.abortWith(Response.status(Response.Status.NO_CONTENT).build());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -14,9 +14,8 @@ CREATE TABLE `node` (
|
||||
import java.sql.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.kar.karusic.annotation.SQLIfNotExists;
|
||||
import org.kar.karusic.annotation.SQLTableLinkGeneric;
|
||||
import org.kar.karusic.annotation.SQLTableName;
|
||||
import org.kar.archidata.annotation.SQLIfNotExists;
|
||||
import org.kar.archidata.annotation.SQLTableName;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
|
@ -13,9 +13,9 @@ CREATE TABLE `node` (
|
||||
*/
|
||||
|
||||
|
||||
import org.kar.karusic.annotation.SQLIfNotExists;
|
||||
import org.kar.karusic.annotation.SQLLimitSize;
|
||||
import org.kar.karusic.annotation.SQLTableName;
|
||||
import org.kar.archidata.annotation.SQLIfNotExists;
|
||||
import org.kar.archidata.annotation.SQLLimitSize;
|
||||
import org.kar.archidata.annotation.SQLTableName;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
|
@ -1,32 +0,0 @@
|
||||
package org.kar.karusic.model;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class Data {
|
||||
public Long id;
|
||||
public boolean deleted;
|
||||
public String sha512;
|
||||
public String mimeType;
|
||||
public Long size;
|
||||
|
||||
public Data() {
|
||||
|
||||
}
|
||||
|
||||
public Data(ResultSet rs) {
|
||||
int iii = 1;
|
||||
try {
|
||||
this.id = rs.getLong(iii++);
|
||||
this.deleted = rs.getBoolean(iii++);
|
||||
this.sha512 = rs.getString(iii++);
|
||||
this.mimeType = rs.getString(iii++);
|
||||
this.size = rs.getLong(iii++);
|
||||
if (rs.wasNull()) {
|
||||
this.size = null;
|
||||
}
|
||||
} catch (SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
@ -14,8 +14,8 @@ CREATE TABLE `node` (
|
||||
|
||||
import java.sql.ResultSet;
|
||||
|
||||
import org.kar.karusic.annotation.SQLIfNotExists;
|
||||
import org.kar.karusic.annotation.SQLTableName;
|
||||
import org.kar.archidata.annotation.SQLIfNotExists;
|
||||
import org.kar.archidata.annotation.SQLTableName;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
|
@ -1,35 +0,0 @@
|
||||
package org.kar.karusic.model;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import org.kar.karusic.annotation.SQLAutoIncrement;
|
||||
import org.kar.karusic.annotation.SQLComment;
|
||||
import org.kar.karusic.annotation.SQLCreateTime;
|
||||
import org.kar.karusic.annotation.SQLDefault;
|
||||
import org.kar.karusic.annotation.SQLNotNull;
|
||||
import org.kar.karusic.annotation.SQLNotRead;
|
||||
import org.kar.karusic.annotation.SQLPrimaryKey;
|
||||
import org.kar.karusic.annotation.SQLUpdateTime;
|
||||
|
||||
public class GenericTable {
|
||||
@SQLAutoIncrement // Add AUTO_INCREMENT modifier
|
||||
@SQLPrimaryKey // Create a PRIMARY KEY based on this field
|
||||
@SQLNotNull
|
||||
@SQLComment("Primary key of the base")
|
||||
public Long id = null;
|
||||
@SQLNotRead
|
||||
@SQLNotNull
|
||||
@SQLDefault("'0'")
|
||||
@SQLComment("When delete, they are not removed, they are just set in a deleted state")
|
||||
public Boolean deleted = null;
|
||||
@SQLNotRead
|
||||
@SQLCreateTime
|
||||
@SQLNotNull
|
||||
@SQLComment("Create time of the object")
|
||||
public Timestamp create_date = null;
|
||||
@SQLNotRead
|
||||
@SQLUpdateTime
|
||||
@SQLNotNull
|
||||
@SQLComment("When update the object")
|
||||
public Timestamp modify_date = null;
|
||||
}
|
@ -14,10 +14,9 @@ CREATE TABLE `node` (
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.kar.karusic.annotation.SQLLimitSize;
|
||||
import org.kar.karusic.annotation.SQLTableLinkGeneric;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import org.kar.archidata.annotation.SQLLimitSize;
|
||||
import org.kar.archidata.annotation.SQLTableLinkGeneric;
|
||||
import org.kar.archidata.model.GenericTable;
|
||||
|
||||
public class NodeSmall extends GenericTable {
|
||||
@SQLLimitSize(256)
|
||||
|
@ -14,9 +14,9 @@ CREATE TABLE `node` (
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.kar.karusic.annotation.SQLIfNotExists;
|
||||
import org.kar.karusic.annotation.SQLTableLinkGeneric;
|
||||
import org.kar.karusic.annotation.SQLTableName;
|
||||
import org.kar.archidata.annotation.SQLIfNotExists;
|
||||
import org.kar.archidata.annotation.SQLTableLinkGeneric;
|
||||
import org.kar.archidata.annotation.SQLTableName;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
|
@ -14,9 +14,9 @@ CREATE TABLE `node` (
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.kar.karusic.annotation.SQLIfNotExists;
|
||||
import org.kar.karusic.annotation.SQLTableLinkGeneric;
|
||||
import org.kar.karusic.annotation.SQLTableName;
|
||||
import org.kar.archidata.annotation.SQLIfNotExists;
|
||||
import org.kar.archidata.annotation.SQLTableLinkGeneric;
|
||||
import org.kar.archidata.annotation.SQLTableName;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
|
@ -1,55 +0,0 @@
|
||||
package org.kar.karusic.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',
|
||||
`email` varchar(512) COLLATE 'utf8_general_ci' NOT NULL COMMENT 'email of the user',
|
||||
`lastConnection` datetime NOT NULL COMMENT 'last connection time',
|
||||
`admin` enum("TRUE", "FALSE") NOT NULL DEFAULT 'FALSE',
|
||||
`blocked` enum("TRUE", "FALSE") NOT NULL DEFAULT 'FALSE',
|
||||
`removed` enum("TRUE", "FALSE") NOT NULL DEFAULT 'FALSE',
|
||||
`avatar` bigint DEFAULT NULL,
|
||||
) AUTO_INCREMENT=10;
|
||||
|
||||
*/
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
|
||||
import org.kar.karusic.annotation.SQLAutoIncrement;
|
||||
import org.kar.karusic.annotation.SQLComment;
|
||||
import org.kar.karusic.annotation.SQLDefault;
|
||||
import org.kar.karusic.annotation.SQLIfNotExists;
|
||||
import org.kar.karusic.annotation.SQLLimitSize;
|
||||
import org.kar.karusic.annotation.SQLNotNull;
|
||||
import org.kar.karusic.annotation.SQLPrimaryKey;
|
||||
import org.kar.karusic.annotation.SQLTableName;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
@SQLTableName ("user")
|
||||
@SQLIfNotExists
|
||||
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
|
||||
public class User {
|
||||
@SQLAutoIncrement // Add AUTO_INCREMENT modifier
|
||||
@SQLPrimaryKey // Create a PRIMARY KEY based on this field
|
||||
@SQLNotNull
|
||||
@SQLComment("Primary key of the base")
|
||||
public Long id = null;
|
||||
@SQLLimitSize(256)
|
||||
public String login = null;
|
||||
|
||||
public Timestamp lastConnection = null;
|
||||
@SQLDefault("'0'")
|
||||
@SQLNotNull
|
||||
public boolean admin = false;
|
||||
@SQLDefault("'0'")
|
||||
@SQLNotNull
|
||||
public boolean blocked = false;
|
||||
@SQLDefault("'0'")
|
||||
@SQLNotNull
|
||||
public boolean removed = false;
|
||||
|
||||
}
|
@ -19,7 +19,7 @@ public class UserExtern {
|
||||
public String login;
|
||||
public boolean admin;
|
||||
|
||||
public UserExtern(User other) {
|
||||
public UserExtern(UserKarusic other) {
|
||||
this.id = other.id;
|
||||
this.login = other.login;
|
||||
this.admin = other.admin;
|
||||
|
14
back/src/org/kar/karusic/model/UserKarusic.java
Normal file
14
back/src/org/kar/karusic/model/UserKarusic.java
Normal file
@ -0,0 +1,14 @@
|
||||
package org.kar.karusic.model;
|
||||
|
||||
import org.kar.archidata.annotation.SQLIfNotExists;
|
||||
import org.kar.archidata.annotation.SQLTableName;
|
||||
import org.kar.archidata.model.User;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
@SQLTableName ("user")
|
||||
@SQLIfNotExists
|
||||
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
|
||||
public class UserKarusic extends User {
|
||||
|
||||
}
|
@ -21,7 +21,7 @@ public class UserPerso {
|
||||
public boolean blocked;
|
||||
public boolean removed;
|
||||
|
||||
public UserPerso(User other) {
|
||||
public UserPerso(UserKarusic other) {
|
||||
this.id = other.id;
|
||||
this.login = other.login;
|
||||
this.admin = other.admin;
|
||||
|
@ -1,85 +1,15 @@
|
||||
package org.kar.karusic.util;
|
||||
|
||||
public class ConfigVariable {
|
||||
public static final String BASE_NAME = "ORG_KARUSIC_";
|
||||
|
||||
public static String getTmpDataFolder() {
|
||||
String out = System.getenv("org.kar.karusic.dataTmpFolder");
|
||||
if (out == null) {
|
||||
return "/application/data/tmp";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getMediaDataFolder() {
|
||||
String out = System.getenv("org.kar.karusic.dataFolder");
|
||||
if (out == null) {
|
||||
return "/application/data/media";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getFrontFolder() {
|
||||
String out = System.getenv("ORG_KARUSIC_FRONT_FOLDER");
|
||||
String out = System.getenv(BASE_NAME + "FRONT_FOLDER");
|
||||
if (out == null) {
|
||||
return "/application/karusic";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
public static String getDBHost() {
|
||||
String out = System.getenv("ORG_KARUSIC_DB_HOST");
|
||||
if (out == null) {
|
||||
return "localhost";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getDBPort() {
|
||||
String out = System.getenv("ORG_KARUSIC_DB_PORT");
|
||||
if (out == null) {
|
||||
return "17036";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getDBLogin() {
|
||||
String out = System.getenv("ORG_KARUSIC_DB_LOGIN");
|
||||
if (out == null) {
|
||||
return "root";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getDBPassword() {
|
||||
String out = System.getenv("MYSQL_ROOT_PASSWORD");
|
||||
if (out == null) {
|
||||
return "ZERTYSDGFVHSDFGHJYZSDFGSQxfgsqdfgsqdrf4564654";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getDBName() {
|
||||
String out = System.getenv("MYSQL_DATABASE");
|
||||
if (out == null) {
|
||||
return "karusic";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getlocalAddress() {
|
||||
String out = System.getenv("ORG_KARUSIC_ADDRESS");
|
||||
if (out == null) {
|
||||
return "http://0.0.0.0:19080/karusic/api/";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static String getSSOAddress() {
|
||||
String out = System.getenv("SSO_ADDRESS");
|
||||
if (out == null) {
|
||||
return "http://192.168.1.156/karauth/api/";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
@ -1,87 +0,0 @@
|
||||
package org.kar.karusic.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
|
||||
import org.kar.karusic.SqlWrapper;
|
||||
import org.kar.karusic.api.DataResource;
|
||||
import org.kar.karusic.model.Data;
|
||||
|
||||
public class CoverTools {
|
||||
|
||||
public static String multipartCorrection(String data) {
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
if (data.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (data.contentEquals("null")) {
|
||||
return null;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
public static <T> Response uploadCover(Class<T> clazz,
|
||||
Long id,
|
||||
String fileName,
|
||||
InputStream fileInputStream,
|
||||
FormDataContentDisposition fileMetaData
|
||||
) {
|
||||
try {
|
||||
// correct input string stream :
|
||||
fileName = multipartCorrection(fileName);
|
||||
|
||||
//public NodeSmall uploadFile(final FormDataMultiPart form) {
|
||||
System.out.println("Upload media file: " + fileMetaData);
|
||||
System.out.println(" - id: " + id);
|
||||
System.out.println(" - file_name: " + fileName);
|
||||
System.out.println(" - fileInputStream: " + fileInputStream);
|
||||
System.out.println(" - fileMetaData: " + fileMetaData);
|
||||
System.out.flush();
|
||||
T media = SqlWrapper.get(clazz, id);
|
||||
if (media == null) {
|
||||
return Response.notModified("Media Id does not exist or removed...").build();
|
||||
}
|
||||
|
||||
long tmpUID = DataResource.getTmpDataId();
|
||||
String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID);
|
||||
Data data = DataResource.getWithSha512(sha512);
|
||||
if (data == null) {
|
||||
System.out.println("Need to add the data in the BDD ... ");
|
||||
System.out.flush();
|
||||
try {
|
||||
data = DataResource.createNewData(tmpUID, fileName, sha512);
|
||||
} catch (IOException ex) {
|
||||
DataResource.removeTemporaryFile(tmpUID);
|
||||
ex.printStackTrace();
|
||||
return Response.notModified("can not create input media").build();
|
||||
} catch (SQLException ex) {
|
||||
ex.printStackTrace();
|
||||
DataResource.removeTemporaryFile(tmpUID);
|
||||
return Response.notModified("Error in SQL insertion ...").build();
|
||||
}
|
||||
} else if (data.deleted == true) {
|
||||
System.out.println("Data already exist but deleted");
|
||||
System.out.flush();
|
||||
DataResource.undelete(data.id);
|
||||
data.deleted = false;
|
||||
} else {
|
||||
System.out.println("Data already exist ... all good");
|
||||
System.out.flush();
|
||||
}
|
||||
// Fist step: retrieve all the Id of each parents:...
|
||||
System.out.println("Find typeNode");
|
||||
SqlWrapper.addLink(clazz, id, "cover", data.id);
|
||||
return Response.ok(SqlWrapper.get(clazz, id)).build();
|
||||
} catch (Exception ex) {
|
||||
System.out.println("Cat ann unexpected error ... ");
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return Response.serverError().build();
|
||||
}
|
||||
}
|
@ -1,175 +0,0 @@
|
||||
package org.kar.karusic.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.text.ParseException;
|
||||
import java.util.Date;
|
||||
import java.util.UUID;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nimbusds.jose.JOSEException;
|
||||
import com.nimbusds.jose.JOSEObjectType;
|
||||
import com.nimbusds.jose.JWSAlgorithm;
|
||||
import com.nimbusds.jose.JWSHeader;
|
||||
import com.nimbusds.jose.JWSSigner;
|
||||
import com.nimbusds.jose.JWSVerifier;
|
||||
import com.nimbusds.jose.crypto.RSASSASigner;
|
||||
import com.nimbusds.jose.crypto.RSASSAVerifier;
|
||||
import com.nimbusds.jose.jwk.RSAKey;
|
||||
import com.nimbusds.jose.jwk.gen.RSAKeyGenerator;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import com.nimbusds.jwt.SignedJWT;
|
||||
|
||||
public class JWTWrapper {
|
||||
private static RSAKey rsaJWK = null;;
|
||||
private static RSAKey rsaPublicJWK = null;
|
||||
|
||||
public static class PublicKey {
|
||||
public String key;
|
||||
|
||||
public PublicKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
public PublicKey() {
|
||||
}
|
||||
}
|
||||
public static void initLocalTokenRemote(String ssoUri, String application) throws IOException, ParseException {
|
||||
// check Token:
|
||||
URL obj = new URL(ssoUri + "public_key");
|
||||
System.out.println("Request token from:" + obj);
|
||||
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
con.setRequestProperty("User-Agent", application);
|
||||
con.setRequestProperty("Cache-Control", "no-cache");
|
||||
con.setRequestProperty("Content-Type", "application/json");
|
||||
con.setRequestProperty("Accept", "application/json");
|
||||
int responseCode = con.getResponseCode();
|
||||
|
||||
System.out.println("GET Response Code :: " + responseCode);
|
||||
if (responseCode == HttpURLConnection.HTTP_OK) { // success
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
||||
|
||||
String inputLine;
|
||||
StringBuffer response = new StringBuffer();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
response.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
// print result
|
||||
System.out.println(response.toString());
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
;
|
||||
PublicKey values = mapper.readValue(response.toString(), PublicKey.class);
|
||||
rsaPublicJWK = RSAKey.parse(values.key);
|
||||
}
|
||||
System.out.println("GET JWT validator token not worked");
|
||||
}
|
||||
|
||||
public static void initLocalToken() throws Exception{
|
||||
// RSA signatures require a public and private RSA key pair, the public key
|
||||
// must be made known to the JWS recipient in order to verify the signatures
|
||||
try {
|
||||
String generatedStringForKey = UUID.randomUUID().toString();
|
||||
rsaJWK = new RSAKeyGenerator(2048).keyID(generatedStringForKey).generate();
|
||||
rsaPublicJWK = rsaJWK.toPublicJWK();
|
||||
//System.out.println("RSA key (all): " + rsaJWK.toJSONString());
|
||||
//System.out.println("RSA key (pub): " + rsaPublicJWK.toJSONString());
|
||||
} catch (JOSEException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
System.out.println("Can not generate teh public abnd private keys ...");
|
||||
rsaJWK = null;
|
||||
rsaPublicJWK = null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void initValidateToken(String publicKey) {
|
||||
try {
|
||||
rsaPublicJWK = RSAKey.parse(publicKey);
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("Can not retrieve public Key !!!!!!!! RSAKey='" + publicKey + "'");
|
||||
}
|
||||
|
||||
}
|
||||
public static String getPublicKey() {
|
||||
if (rsaPublicJWK == null) {
|
||||
return null;
|
||||
}
|
||||
return rsaPublicJWK.toJSONString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a token with the provided elements
|
||||
* @param userID UniqueId of the USER (global unique ID)
|
||||
* @param userLogin Login of the user (never change)
|
||||
* @param isuer The one who provide the Token
|
||||
* @param timeOutInMunites Expiration of the token.
|
||||
* @return the encoded token
|
||||
*/
|
||||
public static String generateJWToken(long userID, String userLogin, String isuer, int timeOutInMunites) {
|
||||
if (rsaJWK == null) {
|
||||
System.out.println("JWT private key is not present !!!");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// Create RSA-signer with the private key
|
||||
JWSSigner signer = new RSASSASigner(rsaJWK);
|
||||
// Prepare JWT with claims set
|
||||
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
|
||||
.subject(Long.toString(userID))
|
||||
.claim("login", userLogin)
|
||||
.issuer(isuer)
|
||||
.issueTime(new Date())
|
||||
.expirationTime(new Date(new Date().getTime() + 60 * timeOutInMunites * 1000 /* millisecond */))
|
||||
.build();
|
||||
|
||||
SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT)/*.keyID(rsaJWK.getKeyID())*/.build(), claimsSet);
|
||||
|
||||
// Compute the RSA signature
|
||||
signedJWT.sign(signer);
|
||||
// serialize the output...
|
||||
return signedJWT.serialize();
|
||||
} catch (JOSEException ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static JWTClaimsSet validateToken(String signedToken, String isuer) {
|
||||
if (rsaPublicJWK == null) {
|
||||
System.out.println("JWT public key is not present !!!");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// On the consumer side, parse the JWS and verify its RSA signature
|
||||
SignedJWT signedJWT = SignedJWT.parse(signedToken);
|
||||
|
||||
JWSVerifier verifier = new RSASSAVerifier(rsaPublicJWK);
|
||||
if (!signedJWT.verify(verifier)) {
|
||||
System.out.println("JWT token is NOT verified ");
|
||||
return null;
|
||||
}
|
||||
if (!new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) {
|
||||
System.out.println("JWT token is expired now = " + new Date() + " with=" + signedJWT.getJWTClaimsSet().getExpirationTime() );
|
||||
return null;
|
||||
}
|
||||
if (!isuer.equals(signedJWT.getJWTClaimsSet().getIssuer())) {
|
||||
System.out.println("JWT issuer is wong: '" + isuer + "' != '" + signedJWT.getJWTClaimsSet().getIssuer() + "'" );
|
||||
return null;
|
||||
}
|
||||
// the element must be validated outside ...
|
||||
//System.out.println("JWT token is verified 'alice' =?= '" + signedJWT.getJWTClaimsSet().getSubject() + "'");
|
||||
//System.out.println("JWT token isuer 'https://c2id.com' =?= '" + signedJWT.getJWTClaimsSet().getIssuer() + "'");
|
||||
return signedJWT.getJWTClaimsSet();
|
||||
} catch (JOSEException ex) {
|
||||
ex.printStackTrace();
|
||||
} catch (ParseException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
package org.kar.karusic.util;
|
||||
|
||||
|
||||
public class PublicKey {
|
||||
public String key;
|
||||
|
||||
public PublicKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
}
|
@ -24,7 +24,7 @@
|
||||
<div class="clear"></div>
|
||||
<div class="title" *ngIf="artists.length > 1">Artists:</div>
|
||||
<div class="title" *ngIf="artists.length == 1">Artist:</div>
|
||||
<div *ngFor="let data of artists" class="item-list" (click)="onSelectAlbum($event, data.id)" (auxclick)="onSelectArtist($event, data.id)">
|
||||
<div *ngFor="let data of artists" class="item-list" (click)="onSelectArtist($event, data.id)" (auxclick)="onSelectArtist($event, data.id)">
|
||||
<app-element-season
|
||||
[element]="data"
|
||||
countSubType="Album"
|
||||
|
@ -50,7 +50,7 @@ export class ArtistsScene implements OnInit {
|
||||
self.artists = undefined;
|
||||
});
|
||||
}
|
||||
onSelectAlbum(event: any, idSelected: number):void {
|
||||
onSelectArtist(event: any, idSelected: number):void {
|
||||
if (event.ctrlKey) {
|
||||
this.arianeService.navigateArtistEdit({id: idSelected, newWindows:event.which === 2} );
|
||||
} else {
|
||||
|
@ -109,7 +109,7 @@ export class ArtistService extends GenericInterfaceModelDB {
|
||||
return new Promise((resolve, reject) => {
|
||||
self.bdd.get('track')
|
||||
.then((response:DataInterface) => {
|
||||
console.log(" <<<========================================>>> " + idArtist);
|
||||
//console.log(" <<<========================================>>> " + idArtist);
|
||||
let data = response.getsWhere([
|
||||
{
|
||||
check: TypeCheck.CONTAINS, //< this is for array containing
|
||||
@ -147,7 +147,7 @@ export class ArtistService extends GenericInterfaceModelDB {
|
||||
return new Promise((resolve, reject) => {
|
||||
self.bdd.get('track')
|
||||
.then((response:DataInterface) => {
|
||||
console.log(" <<<========================================>>> " + idArtist);
|
||||
//console.log(" <<<========================================>>> " + idArtist);
|
||||
let data = response.getsWhere([
|
||||
{
|
||||
check: TypeCheck.CONTAINS, //< this is for array containing
|
||||
|
Loading…
x
Reference in New Issue
Block a user