diff --git a/api/pom.xml b/api/pom.xml index 9fffd9b..1432cf8 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -25,6 +25,7 @@ + false @@ -35,6 +36,7 @@ com.maptology.api.version.IVersionService com.maptology.api.device.IDeviceService com.maptology.api.share.IShareService + com.maptology.api.location.ILocationService http diff --git a/api/src/main/java/com/maptology/api/Entity.java b/api/src/main/java/com/maptology/api/Entity.java index e7fb004..74ac757 100644 --- a/api/src/main/java/com/maptology/api/Entity.java +++ b/api/src/main/java/com/maptology/api/Entity.java @@ -28,7 +28,7 @@ import io.swagger.annotations.ApiModelProperty; setterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @ApiModel(description="Represents an entity.") -public abstract class Entity { +public class Entity { /** * The unique identifier of the data. diff --git a/api/src/main/java/com/maptology/api/Page.java b/api/src/main/java/com/maptology/api/Page.java index a5cf3aa..db9098f 100644 --- a/api/src/main/java/com/maptology/api/Page.java +++ b/api/src/main/java/com/maptology/api/Page.java @@ -64,6 +64,7 @@ public abstract class Page { @XmlElementWrapper @XmlElement(name="element") @JsonProperty(value="elements") // force jackson to keep the name + @ApiModelProperty(value="The elements of the page.", required=true) private List elements = new ArrayList<>(); /** diff --git a/api/src/main/java/com/maptology/api/access/Authorizations.java b/api/src/main/java/com/maptology/api/access/Authorizations.java new file mode 100644 index 0000000..89067dc --- /dev/null +++ b/api/src/main/java/com/maptology/api/access/Authorizations.java @@ -0,0 +1,30 @@ +package com.maptology.api.access; + +/** + * A class with constants for the authorization schemes + * used to reference swagger security definitions. + * + * @author Marcus + */ +public class Authorizations { + + /** + * Basic auth for administrators. + */ + public static final String ADMIN = "admin"; + + /** + * Basic auth for regular users. + */ + public static final String USER = "user"; + + /** + * Bearer auth for devices. + */ + public static final String DEVICE = "device"; + + /** + * Prevent instantiation. + */ + private Authorizations() { } +} diff --git a/api/src/main/java/com/maptology/api/access/package-info.java b/api/src/main/java/com/maptology/api/access/package-info.java index fb57a88..d83cfb2 100644 --- a/api/src/main/java/com/maptology/api/access/package-info.java +++ b/api/src/main/java/com/maptology/api/access/package-info.java @@ -1,8 +1,7 @@ /** * This package defines the basic roles for role-based - * access control. In addition, it defines annotations - * that can be used to define access restrictions on - * resource methods. + * access control and the associated authorizations to + * authenticate and authorize users. * * @author Marcus */ diff --git a/api/src/main/java/com/maptology/api/device/Device.java b/api/src/main/java/com/maptology/api/device/Device.java index 2da3266..669d8e0 100644 --- a/api/src/main/java/com/maptology/api/device/Device.java +++ b/api/src/main/java/com/maptology/api/device/Device.java @@ -1,54 +1,149 @@ package com.maptology.api.device; -import com.maptology.api.Entity; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; +import com.maptology.api.Entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + /** - * * A data transfer object for a device with associated swagger and - * jaxb annotations that supports xml and json serialization. + * * A data transfer object for a device with associated swagger and jaxb + * annotations that supports xml and json serialization. * * @author Ole */ @XmlRootElement @ApiModel(description = "Represents a device.", parent = Entity.class) public class Device extends Entity { + + /** + * The owning user or null. + */ + @XmlAttribute + @ApiModelProperty(value="The id of the owning user or null, if there is none.") + private Long user; + + /** + * The operating system. + */ + @NotNull + @XmlAttribute(required=true) + @ApiModelProperty(value="The operating system.", required=true) + private OperatingSystem os; + + /** + * The manufacturer name. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The manufacturer name, see android.os.Build.MANUFACTURER.", required=true) + private String manufacturer; + + /** + * The device name (industrial design). + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The device name, see android.os.Build.DEVICE.", required=true) + private String device; + + /** + * The model name. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The model name, see android.os.Build.MODEL.", required=true) + private String model; - /** - * The login name of the user that owns this device. - * Null, if this device has no attached user account. - */ - @XmlAttribute() - @ApiModelProperty( - value = "The login name of the user.", - notes = "Null, if this device has no attached user account.", - required = false, - readOnly = true) - private String userLogin; + /** + * Returns the user. + * + * @return The user. + */ + public Long getUser() { + return user; + } - /** - * The secret device token. The token is used for authenticating the device. - */ - @XmlAttribute() - @ApiModelProperty(value = "The secret device token. The token is used for authenticating the device.", required = true) - private String authToken; + /** + * Sets the user. + * + * @param user The user to set. + */ + public void setUser(Long user) { + this.user = user; + } - public String getAuthToken() { - return authToken; - } + /** + * Returns the os. + * + * @return The os. + */ + public OperatingSystem getOs() { + return os; + } - public void setAuthToken(String authToken) { - this.authToken = authToken; - } + /** + * Sets the os. + * + * @param os The os to set. + */ + public void setOs(OperatingSystem os) { + this.os = os; + } - public String getUserLogin() { - return userLogin; - } + /** + * Returns the manufacturer. + * + * @return The manufacturer. + */ + public String getManufacturer() { + return manufacturer; + } - public void setUserLogin(String userLogin) { - this.userLogin = userLogin; - } + /** + * Sets the manufacturer. + * + * @param manufacturer The manufacturer to set. + */ + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + + /** + * Returns the device. + * + * @return The device. + */ + public String getDevice() { + return device; + } + + /** + * Sets the device. + * + * @param device The device to set. + */ + public void setDevice(String device) { + this.device = device; + } + + /** + * Returns the model. + * + * @return The model. + */ + public String getModel() { + return model; + } + + /** + * Sets the model. + * + * @param model The model to set. + */ + public void setModel(String model) { + this.model = model; + } + + } diff --git a/api/src/main/java/com/maptology/api/device/DeviceHandle.java b/api/src/main/java/com/maptology/api/device/DeviceHandle.java new file mode 100644 index 0000000..4450dcc --- /dev/null +++ b/api/src/main/java/com/maptology/api/device/DeviceHandle.java @@ -0,0 +1,44 @@ +package com.maptology.api.device; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Represents a device with it's secret auth token assigned by the server + * upon device registration. + * + * @author Marcus + */ +@XmlRootElement +@ApiModel(description = "Represents a device with a secret token.", parent = Device.class) +public class DeviceHandle extends Device { + + /** + * The secret token used for authenticating the device. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value = "The secret token used for authenticating the device.", required = true) + private String token; + + /** + * Returns the auth token. + * + * @return The auth token. + */ + public String getToken() { + return token; + } + + /** + * Sets the auth token. + * + * @param authToken The auth token. + */ + public void setToken(String token) { + this.token = token; + } + +} diff --git a/api/src/main/java/com/maptology/api/device/DeviceInfo.java b/api/src/main/java/com/maptology/api/device/DeviceInfo.java new file mode 100644 index 0000000..d84221d --- /dev/null +++ b/api/src/main/java/com/maptology/api/device/DeviceInfo.java @@ -0,0 +1,132 @@ +package com.maptology.api.device; + +import javax.validation.constraints.NotNull; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * A device registration is used to register a device. + * + * @author Marcus + */ +@XmlAccessorType(XmlAccessType.FIELD) +@JsonAutoDetect( + fieldVisibility = JsonAutoDetect.Visibility.ANY, + getterVisibility = JsonAutoDetect.Visibility.NONE, + setterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +@XmlRootElement +@ApiModel(description = "Represents information about a device.") +public class DeviceInfo { + + /** + * The operating system. + */ + @NotNull + @XmlAttribute(required=true) + @ApiModelProperty(value="The operating system.", required=true) + private OperatingSystem os; + + /** + * The manufacturer name. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The manufacturer name, see android.os.Build.MANUFACTURER.", required=true) + private String manufacturer; + + /** + * The device name (industrial design). + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The device name, see android.os.Build.DEVICE.", required=true) + private String device; + + /** + * The model name. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The model name, see android.os.Build.MODEL.", required=true) + private String model; + + /** + * Returns the os. + * + * @return The os. + */ + public OperatingSystem getOs() { + return os; + } + + /** + * Sets the os. + * + * @param os The os to set. + */ + public void setOs(OperatingSystem os) { + this.os = os; + } + + /** + * Returns the manufacturer. + * + * @return The manufacturer. + */ + public String getManufacturer() { + return manufacturer; + } + + /** + * Sets the manufacturer. + * + * @param manufacturer The manufacturer to set. + */ + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + + /** + * Returns the device. + * + * @return The device. + */ + public String getDevice() { + return device; + } + + /** + * Sets the device. + * + * @param device The device to set. + */ + public void setDevice(String device) { + this.device = device; + } + + /** + * Returns the model. + * + * @return The model. + */ + public String getModel() { + return model; + } + + /** + * Sets the model. + * + * @param model The model to set. + */ + public void setModel(String model) { + this.model = model; + } + + + +} diff --git a/api/src/main/java/com/maptology/api/device/IDeviceService.java b/api/src/main/java/com/maptology/api/device/IDeviceService.java index 5911290..00e18dc 100644 --- a/api/src/main/java/com/maptology/api/device/IDeviceService.java +++ b/api/src/main/java/com/maptology/api/device/IDeviceService.java @@ -1,18 +1,34 @@ package com.maptology.api.device; -import com.maptology.api.PageConfig; -import com.maptology.api.access.Roles; -import io.swagger.annotations.*; - import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import javax.validation.constraints.Min; -import javax.ws.rs.*; +import javax.validation.constraints.NotNull; +import javax.ws.rs.BeanParam; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import com.maptology.api.PageConfig; +import com.maptology.api.access.Authorizations; +import com.maptology.api.access.Roles; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; + /** * A service to manage devices. * @@ -24,6 +40,8 @@ import javax.ws.rs.core.Response; @Path("/") public interface IDeviceService { + // device functions (for the mobile app) + /** * Creates and returns a new device. * @@ -31,18 +49,104 @@ public interface IDeviceService { */ @POST @Path("devices") - @ApiOperation(value = "Creates a new device.", + @ApiOperation(value = "Creates a new device and returns its handle.", notes = "The response will include the auth token to be stored on the device and supplied as authentication " + "on all subsequent api calls. Note that the auth token can not be requested after creation, " + "so when losing the auth token you may lose access to the device data.") @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The device was created successfully.", response = Device.class) + @ApiResponse(code = HttpServletResponse.SC_CREATED, message = "The device was created successfully.", response = DeviceHandle.class) }) @PermitAll - Response createDevice(); + Response createDevice(@NotNull @Valid DeviceInfo info); + /** + * Returns the current device. + * + * @return The current device. + */ + @GET + @Path("devices/current") + @ApiOperation(value = "Returns the current device.", authorizations = {@Authorization(Authorizations.DEVICE)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The operation was successful.", response= Device.class), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device was not found."), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") + }) + @RolesAllowed({Roles.DEVICE}) + Response getCurrentDevice(); + + /** + * Deletes the current device. + */ + @DELETE + @Path("devices/current") + @ApiOperation(value = "Deletes the current device.", authorizations = {@Authorization(Authorizations.DEVICE)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The device was deleted successfully."), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device was not found."), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") + }) + @RolesAllowed({Roles.DEVICE}) + Response deleteCurrentDevice(); + + // user functions (for the web app) + + /** + * Returns a page of devices of the current user. + * + * @param config The page configuration. + * @return The list of devices. + */ + @GET + @Path("users/current/devices") + @ApiOperation(value = "Returns the list of devices for the current user.", authorizations = {@Authorization(Authorizations.USER)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The list of devices of the current user", response=DevicePage.class), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device was not found."), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") + }) + @RolesAllowed({Roles.USER}) + Response getCurrentUserDevices(PageConfig config); + + // mixed admin and user functions + + /** + * This method deletes a specific device. + * + * @param id The id of the device. + */ + @DELETE + @Path("devices/{id: [0-9]+}") + @ApiOperation(value = "Deletes a device.", authorizations = {@Authorization(Authorizations.USER)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The device was deleted successfully."), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device does not exists."), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") + }) + @RolesAllowed({Roles.USER, Roles.ADMIN}) + Response deleteDevice(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id); + + + /** + * Returns a particular device. + * + * @param id The id of the device. + * @return The device, if allowed and available. + */ + @GET + @Path("devices/{id: [0-9]+}") + @ApiOperation(value = "Gets a device.", authorizations = {@Authorization(Authorizations.ADMIN), @Authorization(Authorizations.USER)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The device returned successfully.", response=Device.class), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device does not exists."), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") + }) + @RolesAllowed({Roles.USER, Roles.ADMIN}) + Response getDevice(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id); + + + // admin functions -// TODO: Discuss if an user should be able to fetch a list of all his registered devices. First of all this is useful for an admin to manage and possible delete or block an device. /** * Returns all currently registered devices * @@ -50,7 +154,7 @@ public interface IDeviceService { */ @GET @Path("devices") - @ApiOperation(value = "Returns all currently registered devices", authorizations = @Authorization("admin")) + @ApiOperation(value = "Returns all devices.", authorizations = @Authorization(Authorizations.ADMIN)) @ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = DevicePage.class), @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for retrieval."), @@ -58,54 +162,25 @@ public interface IDeviceService { }) @RolesAllowed({Roles.ADMIN}) Response getDevices(@BeanParam @Valid PageConfig pageConfig); + /** - * This method deletes the current device + * Sets the values of a particular device. + * + * @param id The id of the device. + * @param device The device data. + * @return The modified device. */ - @DELETE - @Path("devices/current") - @ApiOperation(value = "Deletes the current device", authorizations = {@Authorization("device")}) + @PUT + @Path("devices/{id: [0-9]+}") + @ApiOperation(value = "Sets the values of a device.", authorizations = {@Authorization(Authorizations.ADMIN), @Authorization(Authorizations.USER)}) @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The device was deleted successfully."), - @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") - }) - @RolesAllowed({Roles.DEVICE}) - Response deleteCurrentDevice(); - - - /** - * This method deletes a specific device - * - * @param id The id of the device - */ - @DELETE - @Path("devices/{id}") - @ApiOperation(value = "Deletes a device", authorizations = {@Authorization("admin")}) - @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The device was deleted successfully."), - @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device does not exists"), + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The device returned successfully.", response=Device.class), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device does not exists."), + @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "The device has been updated in parallel."), @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") }) @RolesAllowed({Roles.ADMIN}) - Response deleteDevice(@ApiParam(value = "The device id", required = true) @PathParam("id") @Valid @Min(0) long id); - - - // TODO: Discuss if an admin should be able to see the location of a device and if there is any usecase to ask for it without having a share (consider that a device itself already know its own location). - - /** - * Set the last known location of a device - * - * @param location The location to set - */ - @POST - @Path("devices/current/location") - @ApiOperation(value = "Updates the last known location of the current device", authorizations = {@Authorization("device")}) - @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successfully"), - @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges"), - @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.") - }) - @RolesAllowed({Roles.DEVICE}) - Response setDeviceLocation(@ApiParam(value = "The location to set", required = true) @Valid Location location); + Response setDevice(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id, @ApiParam("The device values.") @Valid @NotNull Device device); } diff --git a/api/src/main/java/com/maptology/api/device/Location.java b/api/src/main/java/com/maptology/api/device/Location.java deleted file mode 100644 index 600a769..0000000 --- a/api/src/main/java/com/maptology/api/device/Location.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.maptology.api.device; - -import com.maptology.api.Entity; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * * A data transfer object for a device location with associated swagger and - * jaxb annotations that supports xml and json serialization. - * - * @author Ole - */ -@XmlRootElement -@ApiModel(description = "Represents a location.", parent = Entity.class) -public class Location extends Entity { - - @Min(-180) - @Max(180) - @XmlAttribute(required = true) - @ApiModelProperty(value = "The longitude of a location", required = true) - private double lon; - - @Min(-90) - @Max(90) - @XmlAttribute(required = true) - @ApiModelProperty(value = "The latitude of a location", required = true) - private double lat; - - @XmlAttribute(required = true) - @ApiModelProperty(value = "The timestamp of the location", required = true) - private long timestamp; - - public double getLon() { - return lon; - } - - public void setLon(double lon) { - this.lon = lon; - } - - public double getLat() { - return lat; - } - - public void setLat(double lat) { - this.lat = lat; - } - - public long getTimestamp() { - return timestamp; - } - - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } -} diff --git a/api/src/main/java/com/maptology/api/device/OperatingSystem.java b/api/src/main/java/com/maptology/api/device/OperatingSystem.java new file mode 100644 index 0000000..4ae7428 --- /dev/null +++ b/api/src/main/java/com/maptology/api/device/OperatingSystem.java @@ -0,0 +1,39 @@ +package com.maptology.api.device; + +/** + * The names of operating systems. + * + * @author Marcus + */ +public enum OperatingSystem { + + /** + * Google Android. + */ + ANDROID, + /** + * Apple iOS. + */ + IOS; + + @Override + public String toString() { + return name().toLowerCase(); + } + + /** + * Deserializes the operating system. + * + * @param os The os string. + * @return The operating system. + */ + public OperatingSystem fromString(String os) { + for (OperatingSystem o: OperatingSystem.values()) { + if (o.name().equalsIgnoreCase(os)) { + return o; + } + } + return null; + } + +} diff --git a/api/src/main/java/com/maptology/api/location/Availability.java b/api/src/main/java/com/maptology/api/location/Availability.java new file mode 100644 index 0000000..3948463 --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/Availability.java @@ -0,0 +1,52 @@ +package com.maptology.api.location; + +/** + * Meta data to provide information about the + * (un-)availability of a location update. + * + * @author Marcus + */ +public enum Availability { + + /** + * The gps position has been computed directly + * from a gps provider. + */ + FRESH, + /** + * The gps position has been taken from cache + * due to some energy-savings mechanism. + */ + CACHED, + /** + * The gps position could not be computed due + * to a lack of location provider. + */ + UNABLE, + /** + * The gps position was computed but is not + * transmited or shared due to privacy restrictions. + */ + PRIVATE; + + + @Override + public String toString() { + return name().toLowerCase(); + } + + /** + * Parses the availability from a string. + * + * @param s The string to parse. + * @return The availability. + */ + public static Availability fromString(String s) { + for (Availability a: values()) { + if (a.name().equalsIgnoreCase(s)) { + return a; + } + } + return null; + } +} diff --git a/api/src/main/java/com/maptology/api/location/Coordinate.java b/api/src/main/java/com/maptology/api/location/Coordinate.java new file mode 100644 index 0000000..e8e7d81 --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/Coordinate.java @@ -0,0 +1,104 @@ +package com.maptology.api.location; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Represents a simple WGS84 (gps) position. + * + * @author Marcus + */ +@XmlAccessorType(XmlAccessType.FIELD) +@JsonAutoDetect( + fieldVisibility = JsonAutoDetect.Visibility.ANY, + getterVisibility = JsonAutoDetect.Visibility.NONE, + setterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +@XmlRootElement +@ApiModel(description = "Represents a WGS84 position.") +public class Coordinate { + + /** + * The longitude. + */ + @Min(-180) + @Max(180) + @XmlAttribute(required = true) + @ApiModelProperty(value = "The longitude of a location.", required = true) + private double longitude; + + /** + * The latitude. + */ + @Min(-90) + @Max(90) + @XmlAttribute(required = true) + @ApiModelProperty(value = "The latitude of a location.", required = true) + private double latitude; + + /** + * Creates a new coordinate with longitude and latitude + * set to 0. Used for serialization. + */ + public Coordinate() { + super(); + } + + /** + * Creates a new coordinate with longitude and latitude + * set to the specified values. + * + * @param longitude The longitude to set. + * @param latitude The latitude to set. + */ + public Coordinate(double longitude, double latitude) { + this.longitude = longitude; + this.latitude = latitude; + } + + /** + * Returns the longitude. + * + * @return The longitude. + */ + public double getLongitude() { + return longitude; + } + + /** + * Sets the longitude. + * + * @param longitude The longitude. + */ + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + /** + * Returns the latitude. + * + * @return The latitude. + */ + public double getLatitude() { + return latitude; + } + + /** + * Sets the latitude. + * + * @param latitude The latitude. + */ + public void setLatitude(double latitude) { + this.latitude = latitude; + } + +} diff --git a/api/src/main/java/com/maptology/api/location/DetailedLocation.java b/api/src/main/java/com/maptology/api/location/DetailedLocation.java new file mode 100644 index 0000000..cdf1ad7 --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/DetailedLocation.java @@ -0,0 +1,169 @@ +package com.maptology.api.location; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * The location update is transmitted from the mobile + * app to the server in order to update the information + * about a device. + * + * @author Marcus + */ +@XmlRootElement +@ApiModel(description = "Represents a location with full details.", parent=Location.class) +public class DetailedLocation extends Location { + + /** + * The version code of the application. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="The version code of the application.", required=true) + private int version; + + /** + * The speed in meter per second or null, if not available. + */ + @XmlAttribute + @ApiModelProperty(value="The speed in meter per second or null, if not available.") + private Double speed; + + /** + * The bearing in degree or null, if not available. + */ + @XmlAttribute + @ApiModelProperty(value="The bearing in degree or null, if not available.") + private Double bearing; + + /** + * The altitude in meters or null, if not available. + */ + @XmlAttribute + @ApiModelProperty(value="The altitude in meters or null, if not available.") + private Double altitude; + + /** + * The accuracy in meters or null, if not available. + */ + @XmlAttribute + @ApiModelProperty(value="The accuracy in meters or null, if not available.") + private Double accuracy; + + /** + * The provider name or null, if not available. + */ + @XmlAttribute + @ApiModelProperty(value="The provider name or null, if not available.") + private String provider; + + /** + * Returns the version. + * + * @return The version. + */ + public int getVersion() { + return version; + } + + /** + * Sets the version. + * + * @param version The version to set. + */ + public void setVersion(int version) { + this.version = version; + } + + /** + * Returns the speed. + * + * @return The speed. + */ + public Double getSpeed() { + return speed; + } + + /** + * Sets the speed. + * + * @param speed The speed to set. + */ + public void setSpeed(Double speed) { + this.speed = speed; + } + + /** + * Returns the bearing. + * + * @return The bearing. + */ + public Double getBearing() { + return bearing; + } + + /** + * Sets the bearing. + * + * @param bearing The bearing to set. + */ + public void setBearing(Double bearing) { + this.bearing = bearing; + } + + /** + * Returns the altitude. + * + * @return The altitude. + */ + public Double getAltitude() { + return altitude; + } + + /** + * Sets the altitude. + * + * @param altitude The altitude to set. + */ + public void setAltitude(Double altitude) { + this.altitude = altitude; + } + + /** + * Returns the accuracy. + * + * @return The accuracy. + */ + public Double getAccuracy() { + return accuracy; + } + + /** + * Sets the accuracy. + * + * @param accuracy The accuracy to set. + */ + public void setAccuracy(Double accuracy) { + this.accuracy = accuracy; + } + + /** + * Returns the provider. + * + * @return The provider. + */ + public String getProvider() { + return provider; + } + + /** + * Sets the provider. + * + * @param provider The provider to set. + */ + public void setProvider(String provider) { + this.provider = provider; + } +} diff --git a/api/src/main/java/com/maptology/api/location/ILocationService.java b/api/src/main/java/com/maptology/api/location/ILocationService.java new file mode 100644 index 0000000..c184fa8 --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/ILocationService.java @@ -0,0 +1,95 @@ +package com.maptology.api.location; + +import javax.annotation.security.PermitAll; +import javax.annotation.security.RolesAllowed; +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import com.maptology.api.access.Authorizations; +import com.maptology.api.access.Roles; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; + +@Api +@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) +@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) +@Path("/") +public interface ILocationService { + + // public functions + + /** + * Get the last known location of a share. + * + * @param token The secret token of the share. + * @return The last known location. + */ + @GET + @Path("shares/{token: [A-Za-z0-9_-]+}/location") + @ApiOperation(value = "Get a shared location by its secret token.") + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = Location.class), + @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter."), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists"), + + }) + @PermitAll + Response getShareLocation(@ApiParam(value = "The secret token.", required = true) @PathParam("token") @Valid @NotNull String token); + + // device functions + + /** + * Adds a set of locations to the current device. + * + * @param update The location update with the locations to set ordered by their creation time. + */ + @POST + @Path("devices/current/locations") + @ApiOperation(value = "Updates the locations of the current device.", authorizations = {@Authorization(Authorizations.DEVICE)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successfully."), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges."), + @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.") + }) + @RolesAllowed({Roles.DEVICE}) + Response addLocations(@ApiParam(value = "The location update with the locations to add.", required = true) @NotNull @Valid LocationUpdate update); + + + // mixed admin and user functions + + /** + * Returns the last location of a particular device + * + * @param id The id of the device. + * @return The last device location. + */ + @GET + @Path("devices/{id: [0-9]+}/location") + @ApiOperation(value = "Gets the last device location.", authorizations = {@Authorization(Authorizations.ADMIN), @Authorization(Authorizations.USER)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The location has been round.", response=Location.class), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device does not exists."), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for executing this method.") + }) + @RolesAllowed({Roles.USER, Roles.ADMIN}) + Response getDeviceLocation(@ApiParam(value = "The device id.", required = true) @PathParam("id") @Valid @Min(0) long id); + + + + +} diff --git a/api/src/main/java/com/maptology/api/location/Location.java b/api/src/main/java/com/maptology/api/location/Location.java new file mode 100644 index 0000000..0650849 --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/Location.java @@ -0,0 +1,108 @@ +package com.maptology.api.location; + +import javax.validation.constraints.NotNull; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * A data transfer object for device locations. This object + * is returned in response to requests for information about + * a share. + * + * @author Ole + */ +@XmlAccessorType(XmlAccessType.FIELD) +@JsonAutoDetect( + fieldVisibility = JsonAutoDetect.Visibility.ANY, + getterVisibility = JsonAutoDetect.Visibility.NONE, + setterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +@XmlRootElement +@ApiModel(description = "Represents a location.") +public class Location { + + /** + * The time stamp in epoch milliseconds. + */ + @XmlAttribute(required = true) + @ApiModelProperty(value = "The timestamp of the location.", required = true) + private long timestamp; + + /** + * The WGS84 coordinate. + */ + @XmlElement(required = false) + @ApiModelProperty(value = "The coordinate of the location.", required = false) + private Coordinate coordinate; + + + @NotNull + @XmlAttribute(required=true) + @ApiModelProperty(value = "The availability information of the location.", required = false) + private Availability availability; + + /** + * Returns the time stamp in Epoch milliseconds. + * + * @return The time stamp in milliseconds. + */ + public long getTimestamp() { + return timestamp; + } + + /** + * Sets the time stamp in Epoch milliseconds. + * + * @param timestamp The time stamp in milliseconds. + */ + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + /** + * Returns the coordinate. + * + * @return The coordinate. + */ + public Coordinate getCoordinate() { + return coordinate; + } + + /** + * Sets the coordinate. + * + * @param coordinate The coordinate to set. + */ + public void setCoordinate(Coordinate coordinate) { + this.coordinate = coordinate; + } + + /** + * Returns the availability. + * + * @return The availability. + */ + public Availability getAvailability() { + return availability; + } + + /** + * Sets the availability. + * + * @param availability The availability to set. + */ + public void setAvailability(Availability availability) { + this.availability = availability; + } + + + +} diff --git a/api/src/main/java/com/maptology/api/location/LocationUpdate.java b/api/src/main/java/com/maptology/api/location/LocationUpdate.java new file mode 100644 index 0000000..81e3efc --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/LocationUpdate.java @@ -0,0 +1,58 @@ +package com.maptology.api.location; + +import java.util.ArrayList; +import java.util.List; + +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonProperty; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@JsonAutoDetect( + fieldVisibility = JsonAutoDetect.Visibility.ANY, + getterVisibility = JsonAutoDetect.Visibility.NONE, + setterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +@ApiModel(description="Represents a location update conisting of a batch of locations.") +public class LocationUpdate { + + @NotNull + @Valid + @XmlElementWrapper + @XmlElement(name="location") + @JsonProperty(value="locations") // force jackson to keep the name + @ApiModelProperty(value="The locations released with this update.", required=true) + private List locations = new ArrayList<>(); + + /** + * Returns the locations. + * + * @return The locations. + */ + public List getLocations() { + return locations; + } + + /** + * Sets the locations. + * + * @param locations The locations to set. + */ + public void setLocations(List locations) { + this.locations = locations; + } + + + +} diff --git a/api/src/main/java/com/maptology/api/location/ReleasedLocation.java b/api/src/main/java/com/maptology/api/location/ReleasedLocation.java new file mode 100644 index 0000000..103b730 --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/ReleasedLocation.java @@ -0,0 +1,68 @@ +package com.maptology.api.location; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * A detailled location + * + * @author Marcus + */ +@XmlRootElement +@ApiModel(description = "Represents a detailed location with usage approved or prohibited by the user.", parent=DetailedLocation.class) +public class ReleasedLocation extends DetailedLocation { + + /** + * A boolean value to mark the location update as sharable. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="A boolean value to mark the update as sharable for research purposes.", required=true) + private boolean sharable; + + /** + * A boolean value to mark the location update as analyzable. + */ + @XmlAttribute(required=true) + @ApiModelProperty(value="A boolean value to mark the update as analyzable to compute places and visits.", required=true) + private boolean analyzable; + + /** + * Returns the sharable. + * + * @return The sharable. + */ + public boolean isSharable() { + return sharable; + } + + /** + * Sets the sharable. + * + * @param sharable The sharable to set. + */ + public void setSharable(boolean sharable) { + this.sharable = sharable; + } + + /** + * Returns the analyzable. + * + * @return The analyzable. + */ + public boolean isAnalyzable() { + return analyzable; + } + + /** + * Sets the analyzable. + * + * @param analyzable The analyzable to set. + */ + public void setAnalyzable(boolean analyzable) { + this.analyzable = analyzable; + } + +} diff --git a/api/src/main/java/com/maptology/api/location/package-info.java b/api/src/main/java/com/maptology/api/location/package-info.java new file mode 100644 index 0000000..143d075 --- /dev/null +++ b/api/src/main/java/com/maptology/api/location/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author Marcus + * + */ +package com.maptology.api.location; \ No newline at end of file diff --git a/api/src/main/java/com/maptology/api/log/ILogService.java b/api/src/main/java/com/maptology/api/log/ILogService.java index 7c0cf0b..b42f412 100644 --- a/api/src/main/java/com/maptology/api/log/ILogService.java +++ b/api/src/main/java/com/maptology/api/log/ILogService.java @@ -12,6 +12,7 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import com.maptology.api.access.Authorizations; import com.maptology.api.access.Roles; import io.swagger.annotations.Api; @@ -40,8 +41,8 @@ public interface ILogService { * @return The list of log messages, which might be empty. */ @GET - @Path("log/message") - @ApiOperation(value = "Returns a list of log messages starting from a particular id.", authorizations= { @Authorization(value="admin") }) + @Path("log/messages") + @ApiOperation(value = "Returns a list of log messages starting from a particular id.", authorizations= { @Authorization(value=Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Notice page retrieved successfully.", response=LogMessage.class, responseContainer="List"), diff --git a/api/src/main/java/com/maptology/api/notice/INoticeService.java b/api/src/main/java/com/maptology/api/notice/INoticeService.java index 1a93b08..17cdab7 100644 --- a/api/src/main/java/com/maptology/api/notice/INoticeService.java +++ b/api/src/main/java/com/maptology/api/notice/INoticeService.java @@ -19,6 +19,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.maptology.api.PageConfig; +import com.maptology.api.access.Authorizations; import com.maptology.api.access.Roles; import io.swagger.annotations.Api; @@ -52,7 +53,7 @@ public interface INoticeService { * on the front page of the web site. */ @GET - @Path("notice/active") + @Path("notices/active") @ApiOperation(value = "Returns a page of notices.") @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Notice page retrieved successfully.", response=NoticePage.class), @@ -73,7 +74,7 @@ public interface INoticeService { * stamp for synchronization with a mobile client. */ @GET - @Path("notice/updated") + @Path("notices/updated") @ApiOperation(value = "Returns all active notices modified after the date.", response = Notice.class, responseContainer = "List" ) @PermitAll Response getUpdatedNotices(@ApiParam(defaultValue="0", value="The earlies time in epoch milliseconds.") @@ -87,8 +88,8 @@ public interface INoticeService { * @return The list of notices as page. */ @GET - @Path("notice") - @ApiOperation(value = "Returns a page of notices.", authorizations= { @Authorization(value="admin") }) + @Path("notices") + @ApiOperation(value = "Returns a page of notices.", authorizations= { @Authorization(value=Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Notice page retrieved successfully.", response=NoticePage.class), @@ -104,8 +105,8 @@ public interface INoticeService { * @return The added notice and a location header set to the new location. */ @POST - @Path("notice") - @ApiOperation(value = "Adds a new notice and returns the notice as well as its location.", authorizations= { @Authorization(value="admin") }) + @Path("notices") + @ApiOperation(value = "Adds a new notice and returns the notice as well as its location.", authorizations= { @Authorization(value=Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_CREATED, message="Notice created successfully.", response = Notice.class, responseHeaders= {@ResponseHeader(name=HttpHeaders.LOCATION, description="Url of the added notice.")}), @@ -121,8 +122,8 @@ public interface INoticeService { * @return The notice. */ @GET - @Path("notice/{id:-?\\d+}") - @ApiOperation(value = "Returns the notice with the specified id.", authorizations= { @Authorization(value="admin") }) + @Path("notices/{id:-?\\d+}") + @ApiOperation(value = "Returns the notice with the specified id.", authorizations= { @Authorization(value=Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Notice retrieved successfully.", response=Notice.class), @@ -138,8 +139,8 @@ public interface INoticeService { * @return The updated notice. */ @PUT - @Path("notice/{id:-?\\d+}") - @ApiOperation(value = "Updates an existing notice.", authorizations= { @Authorization(value="admin") }) + @Path("notices/{id:-?\\d+}") + @ApiOperation(value = "Updates an existing notice.", authorizations= { @Authorization(value=Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Notice updated successfully.", response=Notice.class), diff --git a/api/src/main/java/com/maptology/api/share/IShareService.java b/api/src/main/java/com/maptology/api/share/IShareService.java index c0c165b..f752871 100644 --- a/api/src/main/java/com/maptology/api/share/IShareService.java +++ b/api/src/main/java/com/maptology/api/share/IShareService.java @@ -1,20 +1,31 @@ package com.maptology.api.share; -import com.maptology.api.PageConfig; -import com.maptology.api.access.Roles; -import com.maptology.api.device.Location; -import io.swagger.annotations.*; - import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; -import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import com.maptology.api.access.Authorizations; +import com.maptology.api.access.Roles; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; + /** * A service to manage shares. * @@ -33,41 +44,60 @@ public interface IShareService { */ @POST @Path("shares") - @ApiOperation(value = "Creates a new share", authorizations = {@Authorization("device")}) + @ApiOperation(value = "Creates a new share.", authorizations = {@Authorization(Authorizations.DEVICE)}) @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The share was created successfully."), - @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for this method."), - @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter."), - @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "There is already a share using the provided secret.") - }) - @RolesAllowed({Roles.DEVICE}) - Response createShare(@ApiParam(value = "Necessary data from the client for creating a new share", required = true) @Valid @NotNull ShareCreationRequest shareRequest); - - /** - * Get all received shares for an user - * - * - * @return A list of all received shares for an user - */ - @GET - @Path("shares/my") - @ApiOperation(value = "Get all received shares for an user", authorizations = {@Authorization("user")}) - @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = SharePage.class), + @ApiResponse(code = HttpServletResponse.SC_CREATED, message = "The share was created successfully.", response=Share.class), @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for this method."), @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.") }) - @RolesAllowed({Roles.USER}) - Response getShares(@BeanParam @Valid PageConfig pageConfig); + @RolesAllowed({Roles.DEVICE}) + Response createShare(@ApiParam(value = "Necessary data from to create a share.", required = true) @Valid @NotNull ShareInfo shareInfo); /** - * Delete a share + * Delete a share. + * + * @param id The id of the share to delete + */ + @GET + @Path("shares/{id: ([0-9])+}") + @ApiOperation(value = "Returns a share.", authorizations = {@Authorization(Authorizations.DEVICE)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response=Share.class), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for this method."), + @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter."), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists"), + }) + @RolesAllowed({Roles.DEVICE}) + Response getShare(@ApiParam(value = "The share id.", required = true) @PathParam("id") long id); + + + /** + * Updates the values of an existing share. + * + * @param share The share. + * @return The modified or conflicting share. + */ + @PUT + @Path("shares/{id: ([0-9])+}") + @ApiOperation(value = "Updates an existing share.", authorizations = {@Authorization(Authorizations.DEVICE)}) + @ApiResponses({ + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response=Share.class), + @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges to set the share."), + @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter."), + @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "Conflicting change detected.", response=Share.class), + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists."), + }) + @RolesAllowed({Roles.DEVICE}) + Response setShare(@ApiParam(value = "The share id.", required = true) @PathParam("id") long id, @ApiParam(value = "The new share to set.") @Valid @NotNull Share share); + + /** + * Delete a share. * * @param id The id of the share to delete */ @DELETE - @Path("shares/{secretId: [A-Za-z0-9]+}") - @ApiOperation(value = "Delete a share", authorizations = {@Authorization("device")}) + @Path("shares/{id: ([0-9])+}") + @ApiOperation(value = "Delete a share.", authorizations = {@Authorization(Authorizations.DEVICE)}) @ApiResponses({ @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful."), @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges for this method."), @@ -75,44 +105,23 @@ public interface IShareService { @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists"), }) @RolesAllowed({Roles.DEVICE}) - Response deleteShare(@ApiParam(value = "The share id", required = true) @PathParam("secretId") @Valid @Min(0) long id); + Response deleteShare(@ApiParam(value = "The share id.", required = true) @PathParam("id") long id); /** - * Get a share + * Get a share info by a secret token. * - * @param secretId The secret id of the share to return - * @return The requested share + * @param token The secret id of the share. + * @return The requested share info. */ @GET - @Path("shares/{secretId: [A-Za-z0-9]+}") - @ApiOperation(value = "Get a share") + @Path("shares/{token: [A-Za-z0-9_-]+}/info") + @ApiOperation(value = "Get a share info by its secret token.") @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = Share.class), + @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = ShareInfo.class), @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter."), - @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists"), - + @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists") }) @PermitAll - Response getShare(@ApiParam(value = "The secret share id", required = true) @PathParam("secretId") @Valid @NotNull String secretId); - - /** - * Get the last known location of a share. - * This is used as an efficient variant for updating the location only of an share. Therefore it belongs to the share API. - * - * @param secretId The secret id of the share to return - * @return The last known location - */ - @GET - @Path("shares/{secretId: [A-Za-z0-9]+}/location") - // swagger does not allow using the same path with templates twice (it's dumb, but thats the way it is) - @ApiOperation(value = "Get the last known location of a share") - @ApiResponses({ - @ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = Location.class), - @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter."), - @ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists"), - - }) - @PermitAll - Response getShareLocation(@ApiParam(value = "The secret share id", required = true) @PathParam("secretId") @Valid @NotNull String secretId); + Response getShareInfo(@ApiParam(value = "The secret token.", required = true) @PathParam("token") @Valid @NotNull String token); } diff --git a/api/src/main/java/com/maptology/api/share/Share.java b/api/src/main/java/com/maptology/api/share/Share.java index e04490d..8c76260 100644 --- a/api/src/main/java/com/maptology/api/share/Share.java +++ b/api/src/main/java/com/maptology/api/share/Share.java @@ -1,14 +1,14 @@ package com.maptology.api.share; -import com.maptology.api.Entity; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; +import com.maptology.api.Entity; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + /** * * A data transfer object for a share with associated swagger and * jaxb annotations that supports xml and json serialization. @@ -20,50 +20,157 @@ import javax.xml.bind.annotation.XmlRootElement; public class Share extends Entity { /** - * The secret id. This is needed to access the share. + * The "secret" token to forward to other users. */ @NotNull @XmlAttribute(required = true) - @ApiModelProperty(value = "The secret id. This is needed to access the share.", required = true) - private String secretId; + @ApiModelProperty(value = "The token to forward to other persons to be able to access the share.", required = true) + private String token; /** - * The expiration time of the share. Determine until the share is valid. + * The id of the related device. */ - @Min(0) @XmlAttribute(required = true) - @ApiModelProperty(value = "The expiration time of the share. Determine until the share is valid.", required = true) + @ApiModelProperty(value = "The id of the related device.", required = true, readOnly=true) + private long device; + + /** + * A message to be displayed to the user. + */ + @XmlAttribute + @ApiModelProperty(value="A message to be displayed to the share receiving users.") + private String message; + + /** + * A destination to be displayed to the user. + */ + @XmlAttribute + @ApiModelProperty(value="A destination to be displayed to the share receiving users.") + private String destination; + + /** + * The expiration time of the share that should be created. + */ + @XmlAttribute(required = true) + @ApiModelProperty(value = "The expiration time of the share that should be created.", required = true) private long expirationTime; + /** - * The id of the related device + * A flag to temporarily pause the sharing. */ - @Min(0) @XmlAttribute(required = true) - @ApiModelProperty(value = "The id of the related device", required = true) - private long deviceId; + @ApiModelProperty(value = "A flag to indicate whether the sharing is temporarily paused.") + private boolean paused; + + /** + * Returns the token. + * + * @return The token. + */ + public String getToken() { + return token; + } - public long getExpirationTime() { - return expirationTime; - } + /** + * Sets the token. + * + * @param token The token to set. + */ + public void setToken(String token) { + this.token = token; + } - public void setExpirationTime(long expirationTime) { - this.expirationTime = expirationTime; - } + /** + * Returns the device. + * + * @return The device. + */ + public long getDevice() { + return device; + } - public long getDeviceId() { - return deviceId; - } + /** + * Sets the device. + * + * @param device The device to set. + */ + public void setDevice(long device) { + this.device = device; + } - public void setDeviceId(long deviceId) { - this.deviceId = deviceId; - } + /** + * Returns the paused. + * + * @return The paused. + */ + public boolean isPaused() { + return paused; + } - public String getSecretId() { - return secretId; - } + /** + * Sets the paused. + * + * @param paused The paused to set. + */ + public void setPaused(boolean paused) { + this.paused = paused; + } - public void setSecretId(String secretId) { - this.secretId = secretId; - } + /** + * Returns the message. + * + * @return The message. + */ + public String getMessage() { + return message; + } + + /** + * Sets the message. + * + * @param message The message to set. + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Returns the destination. + * + * @return The destination. + */ + public String getDestination() { + return destination; + } + + /** + * Sets the destination. + * + * @param destination The destination to set. + */ + public void setDestination(String destination) { + this.destination = destination; + } + + /** + * Returns the expirationTime. + * + * @return The expirationTime. + */ + public long getExpirationTime() { + return expirationTime; + } + + /** + * Sets the expirationTime. + * + * @param expirationTime The expirationTime to set. + */ + public void setExpirationTime(long expirationTime) { + this.expirationTime = expirationTime; + } + + + } diff --git a/api/src/main/java/com/maptology/api/share/ShareCreationRequest.java b/api/src/main/java/com/maptology/api/share/ShareCreationRequest.java deleted file mode 100644 index 6f20904..0000000 --- a/api/src/main/java/com/maptology/api/share/ShareCreationRequest.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.maptology.api.share; - -import com.fasterxml.jackson.annotation.JsonAutoDetect; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * A data transfer object for a share request with associated swagger and - * jaxb annotations that supports xml and json serialization. - * - * @author Ole - */ -@XmlRootElement -@ApiModel(description = "Represents a request to create a new share.") -@XmlAccessorType(XmlAccessType.FIELD) -@JsonAutoDetect( - fieldVisibility = JsonAutoDetect.Visibility.ANY, - getterVisibility = JsonAutoDetect.Visibility.NONE, - setterVisibility = JsonAutoDetect.Visibility.NONE, - isGetterVisibility = JsonAutoDetect.Visibility.NONE) -public class ShareCreationRequest { - - /** - * The expiration time of the share that should be created. - */ - @Min(0) - @XmlAttribute(required = true) - @ApiModelProperty(value = "The expiration time of the share that should be created.", required = true) - private long expirationTime; - - /** - * The secret that is shared to other users in order to access the share created from this request. - */ - @NotNull - @Size(min = 32, max = 32) - @XmlAttribute(required = true) - @ApiModelProperty(value = "The secret that is shared to other users in order to access the share created from this request.", required = true) - private String secretId; - - public long getExpirationTime() { - return expirationTime; - } - - public void setExpirationTime(long expirationTime) { - this.expirationTime = expirationTime; - } - - public String getSecretId() { - return secretId; - } - - public void setSecretId(String secretId) { - this.secretId = secretId; - } -} diff --git a/api/src/main/java/com/maptology/api/share/ShareInfo.java b/api/src/main/java/com/maptology/api/share/ShareInfo.java new file mode 100644 index 0000000..44d1956 --- /dev/null +++ b/api/src/main/java/com/maptology/api/share/ShareInfo.java @@ -0,0 +1,103 @@ +package com.maptology.api.share; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * A data transfer object for a share request with associated swagger and + * jaxb annotations that supports xml and json serialization. + * + * @author Ole + */ +@XmlRootElement +@ApiModel(description = "Represents a request to create a new share.") +@XmlAccessorType(XmlAccessType.FIELD) +@JsonAutoDetect( + fieldVisibility = JsonAutoDetect.Visibility.ANY, + getterVisibility = JsonAutoDetect.Visibility.NONE, + setterVisibility = JsonAutoDetect.Visibility.NONE, + isGetterVisibility = JsonAutoDetect.Visibility.NONE) +public class ShareInfo { + + /** + * A message to be displayed to the user. + */ + @XmlAttribute + @ApiModelProperty(value="A message to be displayed to the share receiving users.") + private String message; + + /** + * A destination to be displayed to the user. + */ + @XmlAttribute + @ApiModelProperty(value="A destination to be displayed to the share receiving users.") + private String destination; + + /** + * The expiration time of the share that should be created. + */ + @XmlAttribute(required = true) + @ApiModelProperty(value = "The expiration time of the share that should be created.", required = true) + private long expirationTime; + + /** + * Returns the message. + * + * @return The message. + */ + public String getMessage() { + return message; + } + + /** + * Sets the message. + * + * @param message The message to set. + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Returns the destination. + * + * @return The destination. + */ + public String getDestination() { + return destination; + } + + /** + * Sets the destination. + * + * @param destination The destination to set. + */ + public void setDestination(String destination) { + this.destination = destination; + } + + /** + * Returns the expirationTime. + * + * @return The expirationTime. + */ + public long getExpirationTime() { + return expirationTime; + } + + /** + * Sets the expirationTime. + * + * @param expirationTime The expirationTime to set. + */ + public void setExpirationTime(long expirationTime) { + this.expirationTime = expirationTime; + } + +} diff --git a/api/src/main/java/com/maptology/api/user/IUserService.java b/api/src/main/java/com/maptology/api/user/IUserService.java index b354620..559cf3c 100644 --- a/api/src/main/java/com/maptology/api/user/IUserService.java +++ b/api/src/main/java/com/maptology/api/user/IUserService.java @@ -18,6 +18,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.maptology.api.PageConfig; +import com.maptology.api.access.Authorizations; import com.maptology.api.access.Roles; import io.swagger.annotations.Api; @@ -46,8 +47,8 @@ public interface IUserService { * @return The user that is currently authorized. */ @GET - @Path("user/current") - @ApiOperation(value = "Returns the user currently authorized.", authorizations= { @Authorization(value="user") }) + @Path("users/current") + @ApiOperation(value = "Returns the user currently authorized.", authorizations= { @Authorization(Authorizations.USER) }) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="User retrieved successfully.", response=User.class), @ApiResponse(code=HttpServletResponse.SC_FORBIDDEN, message="No valid authorization found.") @@ -63,8 +64,8 @@ public interface IUserService { * @return The updated user, if successful. */ @PUT - @Path("user/current") - @ApiOperation(value = "Updates the currently authorized user.", authorizations= { @Authorization(value="user") }) + @Path("users/current") + @ApiOperation(value = "Updates the currently authorized user.", authorizations= { @Authorization(Authorizations.USER) }) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="User updated successfully.", response=User.class), @ApiResponse(code=HttpServletResponse.SC_CONFLICT, message="User modified in parallel.", response=User.class), @@ -82,8 +83,8 @@ public interface IUserService { * @return The user if successful, an error code otherwise. */ @PUT - @Path("user/current/password") - @ApiOperation(value="Sets the password of the currently authorized user.", authorizations= { @Authorization(value="user") }) + @Path("users/current/password") + @ApiOperation(value="Sets the password of the currently authorized user.", authorizations= { @Authorization(Authorizations.USER) }) @RolesAllowed({Roles.USER}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Password updated successfully.", response=User.class), @@ -102,8 +103,8 @@ public interface IUserService { * @return The updated user, if successful. */ @POST - @Path("user") - @ApiOperation(value = "Adds a user account with the specified roles and emails.", authorizations= { @Authorization(value="admin") }) + @Path("users") + @ApiOperation(value = "Adds a user account with the specified roles and emails.", authorizations= { @Authorization(Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_CREATED, message="User added successfully.", response=User.class), @@ -122,8 +123,8 @@ public interface IUserService { * @return The user with the specified id. */ @GET - @Path("user/{id: ([0-9])+}") - @ApiOperation(value = "Returns the user account with the specified id.", authorizations= { @Authorization(value="admin") }) + @Path("users/{id: ([0-9])+}") + @ApiOperation(value = "Returns the user account with the specified id.", authorizations= { @Authorization(Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="User retrieved successfully.", response=User.class), @@ -142,8 +143,8 @@ public interface IUserService { * @return The updated user, if successful. */ @PUT - @Path("user/{id: ([0-9])+}") - @ApiOperation(value = "Updates the values of a particular user account.", authorizations= { @Authorization(value="admin") }) + @Path("users/{id: ([0-9])+}") + @ApiOperation(value = "Updates the values of a particular user account.", authorizations= { @Authorization(Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="User updated successfully.", response=User.class), @@ -162,8 +163,8 @@ public interface IUserService { * @return The user if successful, an error code otherwise. */ @PUT - @Path("user/{id: ([0-9])+}/password") - @ApiOperation(value="Sets the password of a user.", authorizations= { @Authorization(value="admin") }) + @Path("users/{id: ([0-9])+}/password") + @ApiOperation(value="Sets the password of a user.", authorizations= { @Authorization(Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Password updated successfully.", response=User.class), @@ -179,8 +180,8 @@ public interface IUserService { * @return The list of users as page. */ @GET - @Path("user") - @ApiOperation(value = "Returns a list of users.", authorizations= { @Authorization(value="admin") }) + @Path("users") + @ApiOperation(value = "Returns a list of users.", authorizations= { @Authorization(Authorizations.ADMIN) }) @RolesAllowed({Roles.ADMIN}) @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="User page retrieved successfully.", response=UserPage.class), @@ -189,6 +190,23 @@ public interface IUserService { }) Response getUsers(@BeanParam @Valid PageConfig pageConfig); + /** + * Returns a list of users whose name or login contains the search term. + * + * @param pageConfig The page configuration. + * @param term The search term. + * @return A page of users whose name or login contains the search term. + */ + @GET + @Path("users/search") + @ApiOperation(value = "Returns a list of users whose login name or name contains the term.", authorizations= { @Authorization(Authorizations.ADMIN) }) + @RolesAllowed({Roles.ADMIN}) + @ApiResponses({ + @ApiResponse(code=HttpServletResponse.SC_OK, message="User page retrieved successfully.", response=UserPage.class), + @ApiResponse(code=HttpServletResponse.SC_FORBIDDEN, message="Insufficient privileges for retrieval."), + @ApiResponse(code=HttpServletResponse.SC_BAD_REQUEST, message="Invalid request parameter.") + }) + Response searchUsers(@BeanParam @Valid PageConfig pageConfig, @ApiParam(value="The search term.", required=true) @QueryParam("term") @NotNull @Valid String term); // registration work-flow @@ -199,7 +217,7 @@ public interface IUserService { * @return Success or failure, if login is taken already. */ @POST - @Path("user/register") + @Path("users/register") @ApiOperation(value = "Registers a new user and sends an email account verification.") @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_CREATED, message="User registered successfully.", response=User.class), @@ -216,7 +234,7 @@ public interface IUserService { * @return A success or error code with an empty body. */ @POST - @Path("user/reset") + @Path("users/reset") @ApiOperation(value = "Sends a password reset email to the correspondence email account of a user.") @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_NO_CONTENT, message="Reset email sent successfully."), @@ -236,7 +254,7 @@ public interface IUserService { * @return The account, if successful. An error otherwise. */ @PUT - @Path("user/password/{token}") + @Path("users/password/{token}") @ApiOperation(value = "Sets the password of a user account using a token received via email.") @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Password updated successfully.", response=User.class), @@ -255,7 +273,7 @@ public interface IUserService { * @return An error code to indicate success or failure. */ @PUT - @Path("user/verify/{token}") + @Path("users/verify/{token}") @ApiOperation(value = "Verifies an email address using a token received via email.") @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_NO_CONTENT, message="Email verified successfully."), diff --git a/api/src/main/java/com/maptology/api/version/IVersionService.java b/api/src/main/java/com/maptology/api/version/IVersionService.java index aaa124b..42cefcc 100644 --- a/api/src/main/java/com/maptology/api/version/IVersionService.java +++ b/api/src/main/java/com/maptology/api/version/IVersionService.java @@ -31,7 +31,7 @@ public interface IVersionService { * @return The build version of the service. */ @GET - @Path("version/build") + @Path("versions/build") @ApiOperation(value = "Returns the build version.") @ApiResponses({ @ApiResponse(code=HttpServletResponse.SC_OK, message="Build version retrieved successfully.", response=BuildVersion.class) diff --git a/service/ejb/pom.xml b/service/ejb/pom.xml index b22f3b1..53db01b 100644 --- a/service/ejb/pom.xml +++ b/service/ejb/pom.xml @@ -63,6 +63,12 @@ pom test + + org.picketbox + picketbox + 4.9.6.Final + test + org.jboss.arquillian.junit arquillian-junit-container diff --git a/service/ejb/src/main/java/com/maptology/service/conversion/AbstractDeviceConverter.java b/service/ejb/src/main/java/com/maptology/service/conversion/AbstractDeviceConverter.java new file mode 100644 index 0000000..1b48ac5 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/conversion/AbstractDeviceConverter.java @@ -0,0 +1,35 @@ +package com.maptology.service.conversion; + +import com.maptology.api.device.Device; +import com.maptology.service.entity.device.DeviceEntity; + +/** + * Base class to convert device entities. + * + * @author Marcus + */ +public abstract class AbstractDeviceConverter extends AbstractEntityConverter { + + /** + * Creates a new converter. + * + * @param filtered True to filter out deleted devices. + */ + public AbstractDeviceConverter(boolean filtered) { + super(filtered); + } + + @Override + public D convert(DeviceEntity source) { + D result = super.convert(source); + if (source.getUser() != null) { + result.setUser(source.getUser().getId()); + } + result.setDevice(source.getDevice()); + result.setManufacturer(source.getManufacturer()); + result.setModel(source.getModel()); + result.setOs(source.getOs()); + return result; + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/conversion/DeviceConverter.java b/service/ejb/src/main/java/com/maptology/service/conversion/DeviceConverter.java index a76c4d6..0fa7d2f 100644 --- a/service/ejb/src/main/java/com/maptology/service/conversion/DeviceConverter.java +++ b/service/ejb/src/main/java/com/maptology/service/conversion/DeviceConverter.java @@ -1,62 +1,26 @@ package com.maptology.service.conversion; import com.maptology.api.device.Device; -import com.maptology.service.entity.device.DeviceEntity; -import com.maptology.service.entity.user.UserEntity; - /** - * Creates a device from a device entity. - * The secret field is excluded + * Converts device entities to devices. + * + * @author Marcus */ -public class DeviceConverter extends AbstractEntityConverter { +public class DeviceConverter extends AbstractDeviceConverter { - /** - * A flag to indicate whether the returned objects should contain the secret. - */ - private final boolean includeAuthToken; + /** + * Creates a converter. + * + * @param filtered True to filter deleted. + */ + public DeviceConverter(boolean filtered) { + super(filtered); + } - /** - * Creates a new entity converter. - * - * @param filtered A flag to indicate whether - * deleted objects should be filtered. - */ - public DeviceConverter(boolean filtered) { - this(filtered, false); - } + @Override + public Device create() { + return new Device(); + } - /** - * Creates a new entity converter. - * - * @param filtered A flag to indicate whether - * deleted objects should be filtered. - */ - public DeviceConverter(boolean filtered, boolean includeAuthToken) { - super(filtered); - this.includeAuthToken = includeAuthToken; - } - - @Override - public Device create() { - return new Device(); - } - - @Override - public Device convert(DeviceEntity source) { - Device device = super.convert(source); - if (device == null) return null; - - // set fields - - UserEntity user = source.getUser(); - if (user != null) { - device.setUserLogin(user.getLogin()); - } - - if (includeAuthToken) { - device.setAuthToken(source.getAuthToken()); - } - return device; - } } diff --git a/service/ejb/src/main/java/com/maptology/service/conversion/DeviceHandleConverter.java b/service/ejb/src/main/java/com/maptology/service/conversion/DeviceHandleConverter.java new file mode 100644 index 0000000..08a39aa --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/conversion/DeviceHandleConverter.java @@ -0,0 +1,35 @@ +package com.maptology.service.conversion; + +import com.maptology.api.device.DeviceHandle; +import com.maptology.service.entity.device.DeviceEntity; + +/** + * Converts device entities to device handles. + * + * @author Marcus + */ +public class DeviceHandleConverter extends AbstractDeviceConverter { + + /** + * Creates a new converter. + * + * @param filtered True to filter deleted. + */ + public DeviceHandleConverter(boolean filtered) { + super(filtered); + } + + @Override + public DeviceHandle create() { + return new DeviceHandle(); + } + + @Override + public DeviceHandle convert(DeviceEntity source) { + DeviceHandle result = super.convert(source); + result.setToken(source.getToken()); + return result; + } + + +} diff --git a/service/ejb/src/main/java/com/maptology/service/conversion/LocationConverter.java b/service/ejb/src/main/java/com/maptology/service/conversion/LocationConverter.java index bd1b145..0c58819 100644 --- a/service/ejb/src/main/java/com/maptology/service/conversion/LocationConverter.java +++ b/service/ejb/src/main/java/com/maptology/service/conversion/LocationConverter.java @@ -1,20 +1,25 @@ package com.maptology.service.conversion; -import com.maptology.api.device.Location; +import com.maptology.api.location.Coordinate; +import com.maptology.api.location.Location; +import com.maptology.service.entity.location.EmbeddedCoordinate; import com.maptology.service.entity.location.LocationEntity; /** + * Converter for locations. + * * @author Ole */ -public class LocationConverter extends AbstractEntityConverter { - /** +public class LocationConverter extends AbstractConverter { + + /** * Creates a new entity converter. * * @param filtered A flag to indicate whether * deleted objects should be filtered. */ public LocationConverter(boolean filtered) { - super(filtered); + super(); } @Override @@ -24,12 +29,15 @@ public class LocationConverter extends AbstractEntityConverter { @@ -24,12 +26,12 @@ public class ShareConverter extends AbstractEntityConverter @Override public Share convert(ShareEntity source) { - Share share = super.convert(source); - if (share == null) return null; - //Populate fields - share.setDeviceId(source.getDevice().getId()); - share.setExpirationTime(source.getExpirationTime()); - share.setSecretId(source.getSecretId()); - return share; + Share result = super.convert(source); + result.setDestination(source.getDestination()); + result.setMessage(source.getMessage()); + result.setExpirationTime(source.getExpirationTime()); + result.setPaused(source.isPaused()); + result.setToken(source.getToken()); + return result; } } diff --git a/service/ejb/src/main/java/com/maptology/service/conversion/ShareInfoConverter.java b/service/ejb/src/main/java/com/maptology/service/conversion/ShareInfoConverter.java new file mode 100644 index 0000000..b7e63ad --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/conversion/ShareInfoConverter.java @@ -0,0 +1,46 @@ +package com.maptology.service.conversion; + +import com.maptology.api.share.ShareInfo; +import com.maptology.service.entity.share.ShareEntity; + +/** + * A converter to convert share entities into share infos. + * + * @author Marcus + */ +public class ShareInfoConverter extends AbstractConverter { + + /** + * A flag to indicate whether we should filter. + */ + protected boolean filtered; + + /** + * Creates a new converter. + * + * @param filtered True to filter. + */ + public ShareInfoConverter(boolean filtered) { + this.filtered = filtered; + } + + @Override + public ShareInfo create() { + return new ShareInfo(); + } + + @Override + public ShareInfo convert(ShareEntity source) { + ShareInfo result = create(); + result.setDestination(source.getDestination()); + result.setMessage(source.getMessage()); + result.setExpirationTime(source.getExpirationTime()); + return result; + } + + @Override + public boolean isFiltered(ShareEntity source) { + return source.isDeleted() && filtered; + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/crypto/SecureToken.java b/service/ejb/src/main/java/com/maptology/service/crypto/SecureToken.java index db6217f..2efc3b8 100644 --- a/service/ejb/src/main/java/com/maptology/service/crypto/SecureToken.java +++ b/service/ejb/src/main/java/com/maptology/service/crypto/SecureToken.java @@ -10,19 +10,15 @@ import java.util.Base64; */ public class SecureToken { - /** - * The token. - */ - public static final int SIZE = 16; - /** * Creates a new random urlsafe token. * + * @param type The token type to generate. * @return The new random urlsafe token. * @throws SecureException Thrown if the random number generator fails. */ - public static String createToken() { - return createToken(SIZE); + public static String createToken(TokenType type) { + return createToken(type.getLength()); } /** @@ -32,7 +28,7 @@ public class SecureToken { * @return The new random urlsafe token. * @throws SecureException Thrown if the random number generator fails. */ - public static String createToken(int baseBytes) { + protected static String createToken(int baseBytes) { return encodeToken(generateToken(baseBytes)); } @@ -43,7 +39,7 @@ public class SecureToken { * @throws SecureException Thrown if the random number generator * fails. */ - public static byte[] generateToken(int size) { + protected static byte[] generateToken(int size) { try { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); byte[] value = new byte[size]; @@ -62,7 +58,7 @@ public class SecureToken { * @param bytes The bytes to encode. * @return The urlsafe encoded token. */ - public static String encodeToken(byte[] bytes) { + protected static String encodeToken(byte[] bytes) { String s = Base64.getEncoder().encodeToString(bytes); s = s.replace('/', '_'); s = s.replace('+', '-'); diff --git a/service/ejb/src/main/java/com/maptology/service/crypto/TokenType.java b/service/ejb/src/main/java/com/maptology/service/crypto/TokenType.java new file mode 100644 index 0000000..b281bee --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/crypto/TokenType.java @@ -0,0 +1,49 @@ +package com.maptology.service.crypto; + +/** + * The default sizes for secure tokens. This class + * defines two constants, one for user-facing tokens + * that are 1) short-lived and 2) should not be too + * long and one for internal tokens that are possibly + * 1) long-lived and 2) should be very secure. + * + * @author Marcus + */ +public enum TokenType { + + /** + * User facing tokens that are short lived and + * should be convenient to use. + */ + EXTERNAL(16), + /** + * Internal tokens that are potentially long-lived + * and should be very hard to guess. + */ + INTERNAL(64); + + /** + * The length of the token in byte. + */ + private final int length; + + /** + * Creates a token size. + * + * @param length The length in bytes. + */ + private TokenType(int length) { + this.length = length; + } + + /** + * Returns the length in bytes. + * + * @return The length in bytes. + */ + public int getLength() { + return length; + } + + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/AbstractEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/AbstractEntity.java index caf9d4c..b870ef0 100644 --- a/service/ejb/src/main/java/com/maptology/service/entity/AbstractEntity.java +++ b/service/ejb/src/main/java/com/maptology/service/entity/AbstractEntity.java @@ -1,15 +1,25 @@ package com.maptology.service.entity; -import com.maptology.api.PageConfig; - -import javax.persistence.*; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import java.io.Serializable; import java.util.List; +import javax.persistence.Entity; +import javax.persistence.EntityManager; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.SequenceGenerator; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + +import com.maptology.api.PageConfig; + @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @@ -187,37 +197,4 @@ public abstract class AbstractEntity implements Serializable { return q.getResultList(); } - /** - * Returns an entry by its primary key id. - * - * @param em The entity manager. - * @param id The id. - * @return The entry or null if no entry for the id exists. - */ - public static E find(EntityManager em, Class type, long id, boolean filtered) { - CriteriaBuilder cb = em.getCriteriaBuilder(); - CriteriaQuery cq = cb.createQuery(type); - - // from Entity e - Root r = cq.from(type); - // select e - cq.select(r); - - // where u.id=:id - Predicate where = cb.equal(r.get("id"), id); - - if (filtered) { - // where deleted = false - where = cb.and(where, cb.equal(r.get("deleted"), false)); - } - - cq.where(where); - TypedQuery q = em.createQuery(cq); - - try { - return q.getSingleResult(); - } catch (NoResultException e) { - return null; - } - } } diff --git a/service/ejb/src/main/java/com/maptology/service/entity/device/DeviceEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/device/DeviceEntity.java index 24bc17e..5629ef8 100644 --- a/service/ejb/src/main/java/com/maptology/service/entity/device/DeviceEntity.java +++ b/service/ejb/src/main/java/com/maptology/service/entity/device/DeviceEntity.java @@ -1,11 +1,34 @@ package com.maptology.service.entity.device; -import com.maptology.service.crypto.SecureToken; -import com.maptology.service.entity.AbstractEntity; -import com.maptology.service.entity.user.UserEntity; +import java.util.List; -import javax.persistence.*; -import java.util.logging.Level; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityManager; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.FetchType; +import javax.persistence.Index; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.NoResultException; +import javax.persistence.OneToMany; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +import com.maptology.api.PageConfig; +import com.maptology.api.device.OperatingSystem; +import com.maptology.service.entity.AbstractEntity; +import com.maptology.service.entity.OrderCriterion; +import com.maptology.service.entity.location.LocationEntity; +import com.maptology.service.entity.share.ShareEntity; +import com.maptology.service.entity.user.UserEntity; /** * The entity to store devices. @@ -16,60 +39,327 @@ import java.util.logging.Level; @Table(name = "device", indexes = { @Index(columnList = "deleted,modificationTime", unique = false), - @Index(columnList = "authToken", unique = true) + //@Index(columnList = "user,deleted,modificationTime", unique = false), + @Index(columnList = "token", unique = true) }) @NamedQueries({ - @NamedQuery(name = "findDeviceByToken", query = "select d from DeviceEntity d where d.authToken=:authToken and d.deleted = false") + @NamedQuery(name = "findDeviceByToken", query = "select d from DeviceEntity d where d.token=:token") }) public class DeviceEntity extends AbstractEntity { /** - * The user that this device belongs to. + * The serialization id. + */ + private static final long serialVersionUID = 1L; + + /** + * The user that this device belongs to. This + * may be null, if the device is not assigned. */ - @ManyToOne(fetch = FetchType.EAGER) + @ManyToOne(fetch = FetchType.LAZY) private UserEntity user; /** - * The auth token to be used when authenticating the device. - * Can only be generated by the server. + * The authentication token. */ @Column(length = 128) - private String authToken; - - public DeviceEntity() { - regenerateAuthToken(); - } - - public UserEntity getUser() { - return user; - } - - public void setUser(UserEntity user) { - this.user = user; - } - - public String getAuthToken() { - return authToken; - } - - public void regenerateAuthToken() { - this.authToken = SecureToken.createToken(32); - } + private String token; + + /** + * The device name assigned by the manufacturer. + */ + @Column(length = 50) + private String device; + + /** + * The manufacturer name. + */ + @Column(length = 50) + private String manufacturer; + + /** + * The device model. + */ + @Column(length = 50) + private String model; + + /** + * The operating system. + */ + @Enumerated(EnumType.ORDINAL) + private OperatingSystem os; /** + * The last location that has been stored for + * the device. + */ + @OneToOne + private LocationEntity location; + + /** + * The locations stored for the device. + */ + @OneToMany(mappedBy="device", fetch=FetchType.LAZY) + private List locations; + + /** + * The shares for the device. + */ + @OneToMany(mappedBy="device", fetch=FetchType.LAZY) + private List shares; + + /** + * Returns the user. + * + * @return The user. + */ + public UserEntity getUser() { + return user; + } + + /** + * Sets the user. + * + * @param user The user to set. + */ + public void setUser(UserEntity user) { + this.user = user; + } + + /** + * Returns the token. + * + * @return The token. + */ + public String getToken() { + return token; + } + + /** + * Sets the token. + * + * @param token The token to set. + */ + public void setToken(String token) { + this.token = token; + } + + /** + * Returns the device. + * + * @return The device. + */ + public String getDevice() { + return device; + } + + /** + * Sets the device. + * + * @param device The device to set. + */ + public void setDevice(String device) { + this.device = device; + } + + /** + * Returns the manufacturer. + * + * @return The manufacturer. + */ + public String getManufacturer() { + return manufacturer; + } + + /** + * Sets the manufacturer. + * + * @param manufacturer The manufacturer to set. + */ + public void setManufacturer(String manufacturer) { + this.manufacturer = manufacturer; + } + + /** + * Returns the model. + * + * @return The model. + */ + public String getModel() { + return model; + } + + /** + * Sets the model. + * + * @param model The model to set. + */ + public void setModel(String model) { + this.model = model; + } + + /** + * Returns the os. + * + * @return The os. + */ + public OperatingSystem getOs() { + return os; + } + + /** + * Sets the os. + * + * @param os The os to set. + */ + public void setOs(OperatingSystem os) { + this.os = os; + } + + /** + * Returns the shares. + * + * @return The shares. + */ + public List getShares() { + return shares; + } + + /** + * Sets the shares. + * + * @param shares The shares to set. + */ + public void setShares(List shares) { + this.shares = shares; + } + + + /** + * Returns the location. + * + * @return The location. + */ + public LocationEntity getLocation() { + return location; + } + + /** + * Sets the location. + * + * @param location The location to set. + */ + public void setLocation(LocationEntity location) { + this.location = location; + } + + /** + * Returns the locations. + * + * @return The locations. + */ + public List getLocations() { + return locations; + } + + /** + * Sets the locations. + * + * @param locations The locations to set. + */ + public void setLocations(List locations) { + this.locations = locations; + } + + /** * Finds a device by its authentication token. * * @param em The entity manager. - * @param authToken The authentication token. + * @param token The authentication token. * @return The device entity or null, if none could be found. */ - public static DeviceEntity findByAuthToken(EntityManager em, String authToken) { + public static DeviceEntity findByToken(EntityManager em, String token) { try { TypedQuery q = em.createNamedQuery("findDeviceByToken", DeviceEntity.class); - q.setParameter("authToken", authToken); + q.setParameter("token", token); return q.getSingleResult(); } catch (NoResultException e) { return null; } } + + + /** + * Returns the last modification of the devices of a user or 0 if the query is empty. + * + * @param em The entity manager. + * @param user The user whose devices should be paged. + * @return The last modification of the table or 0 if the table is empty. + */ + public static long getLastModifiedForUser(EntityManager em, UserEntity user) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Long.class); + Root r = cq.from(DeviceEntity.class); // from Entity e + cq.select(cb.max(r.get("modificationTime").as(Long.class))); // select max(e.modificationTime) + cq.where(cb.equal(r.get("user"), user)); // where e.user = user + List result = em.createQuery(cq).getResultList(); + Long value = result.get(0); + if (value == null) return 0; + else return value; + } + + /** + * Returns the total number of devices of a user. + * + * @param em The entity manager. + * @param type The entity type. + * @param filtered True to also count deleted entities. + * @return The total number of entities. + */ + public static int getCountForUser(EntityManager em, UserEntity user, boolean filtered) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Long.class); + Root r = cq.from(DeviceEntity.class); // from Entity e + cq.select(cb.count(r)); // select count(e) + Predicate where = cb.equal(r.get("user"), user); // where e.user = user + if (filtered) { + where = cb.and(where, cb.equal(r.get("deleted"), false)); // and e.deleted=false + } + cq.where(where); + return em.createQuery(cq).getSingleResult().intValue(); + } + + /** + * Returns a list of devices for a user ordered by the specified criterion. + * + * @param em The entity manager. + * @param config The page configuration with offset and size. + * @param order The order criterion. + * @param filtered True to filter out deleted entities. + * @return The ordered list of entries. + */ + public static List findAllForUser(EntityManager em, UserEntity user, PageConfig config, OrderCriterion order, boolean filtered) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(DeviceEntity.class); + Root r = cq.from(DeviceEntity.class); // from Entity e + cq.select(r); // select e + Predicate where = cb.equal(r.get("user"), user); // where e.user = user + if (filtered) { + where = cb.and(where, cb.equal(r.get("deleted"), false)); // and e.deleted=false + } + cq.where(where); + if (order.isDescending()) { + cq.orderBy(cb.desc(r.get(order.getField()))); // order by field desc + } else { + cq.orderBy(cb.asc(r.get(order.getField()))); // order by field asc + } + TypedQuery q = em.createQuery(cq); + q.setFirstResult(config.getOffset()); + q.setMaxResults(config.getSize()); + return q.getResultList(); + } + + + + } diff --git a/service/ejb/src/main/java/com/maptology/service/entity/location/EmbeddedCoordinate.java b/service/ejb/src/main/java/com/maptology/service/entity/location/EmbeddedCoordinate.java new file mode 100644 index 0000000..c0a4388 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/entity/location/EmbeddedCoordinate.java @@ -0,0 +1,81 @@ +package com.maptology.service.entity.location; + +import javax.persistence.Embeddable; + +/** + * An embeddable coordinate. + * + * @author Marcus + */ +@Embeddable +public class EmbeddedCoordinate { + + /** + * The latitude. + */ + private double latitude; + + /** + * The longitude. + */ + private double longitude; + + /** + * Creates a new coordinate with longitude and + * latitude set to 0. + */ + public EmbeddedCoordinate() { + super(); + } + + /** + * Creates a new coordinate with the latitude and longitude. + * + * @param longitude The longitude. + * @param latitude The latitude. + */ + public EmbeddedCoordinate(double longitude, double latitude) { + this.longitude = longitude; + this.latitude = latitude; + } + + + /** + * Returns the latitude. + * + * @return The latitude. + */ + public double getLatitude() { + return latitude; + } + + /** + * Sets the latitude. + * + * @param latitude The latitude to set. + */ + public void setLatitude(double latitude) { + this.latitude = latitude; + } + + /** + * Returns the longitude. + * + * @return The longitude. + */ + public double getLongitude() { + return longitude; + } + + /** + * Sets the longitude. + * + * @param longitude The longitude to set. + */ + public void setLongitude(double longitude) { + this.longitude = longitude; + } + + + +} diff --git a/service/ejb/src/main/java/com/maptology/service/entity/location/LocationEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/location/LocationEntity.java index 5700eae..80c44cb 100644 --- a/service/ejb/src/main/java/com/maptology/service/entity/location/LocationEntity.java +++ b/service/ejb/src/main/java/com/maptology/service/entity/location/LocationEntity.java @@ -1,87 +1,129 @@ package com.maptology.service.entity.location; +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.FetchType; +import javax.persistence.Index; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +import com.maptology.api.location.Availability; import com.maptology.service.entity.AbstractEntity; import com.maptology.service.entity.device.DeviceEntity; -import javax.persistence.*; - /** - * The entity to store a location + * The entity to store a location for a device. * * @author Ole */ @Entity @Table(name = "location", - indexes = { - @Index(columnList = "timestamp", unique = false) - }) -@NamedQueries({ - @NamedQuery(name = "findLastLocation", query = "select l from LocationEntity l where l.device.id=:deviceId order by l.timestamp desc") -}) + indexes = { + @Index(columnList = "timestamp", unique = false) + }) public class LocationEntity extends AbstractEntity { - + /** + * The serialization version. + */ + private static final long serialVersionUID = 7816852169530117521L; + + /** * The device that ist the source of the location */ @ManyToOne(fetch = FetchType.LAZY) private DeviceEntity device; - + /** - * The longitude + * The (un-) availability information for the entity. */ - private double lon; + @Enumerated(EnumType.ORDINAL) + private Availability availability; /** - * The latitude - */ - private double lat; - - /** - * The measurement time of the location + * The measurement time of the location. */ private long timestamp; + + /** + * The (optional) coordinate of the location. + */ + @Embedded + private EmbeddedCoordinate coordinate; - public static LocationEntity findLastLocation(EntityManager em, long deviceId) { - try { - TypedQuery q = em.createNamedQuery("findLastLocation", LocationEntity.class); - q.setMaxResults(1); - q.setParameter("deviceId", deviceId); - return q.getSingleResult(); - } catch (NoResultException e) { - return null; - } - } + /** + * Returns the device. + * + * @return The device. + */ + public DeviceEntity getDevice() { + return device; + } - public double getLon() { - return lon; - } + /** + * Sets the device. + * + * @param device The device to set. + */ + public void setDevice(DeviceEntity device) { + this.device = device; + } - public void setLon(double lon) { - this.lon = lon; - } + /** + * Returns the availability. + * + * @return The availability. + */ + public Availability getAvailability() { + return availability; + } - public double getLat() { - return lat; - } + /** + * Sets the availability. + * + * @param availability The availability to set. + */ + public void setAvailability(Availability availability) { + this.availability = availability; + } - public void setLat(double lat) { - this.lat = lat; - } + /** + * Returns the timestamp. + * + * @return The timestamp. + */ + public long getTimestamp() { + return timestamp; + } - public long getTimestamp() { - return timestamp; - } + /** + * Sets the timestamp. + * + * @param timestamp The timestamp to set. + */ + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } + /** + * Returns the coordinate. + * + * @return The coordinate. + */ + public EmbeddedCoordinate getCoordinate() { + return coordinate; + } - public DeviceEntity getDevice() { - return device; - } - - public void setDevice(DeviceEntity device) { - this.device = device; - } + /** + * Sets the coordinate. + * + * @param coordinate The coordinate to set. + */ + public void setCoordinate(EmbeddedCoordinate coordinate) { + this.coordinate = coordinate; + } + } diff --git a/service/ejb/src/main/java/com/maptology/service/entity/share/ShareEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/share/ShareEntity.java index d4ed2ad..e7d0e8e 100644 --- a/service/ejb/src/main/java/com/maptology/service/entity/share/ShareEntity.java +++ b/service/ejb/src/main/java/com/maptology/service/entity/share/ShareEntity.java @@ -1,12 +1,21 @@ package com.maptology.service.entity.share; -import com.maptology.api.PageConfig; -import com.maptology.service.crypto.SecureToken; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EntityManager; +import javax.persistence.FetchType; +import javax.persistence.Index; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.NoResultException; +import javax.persistence.Table; +import javax.persistence.TypedQuery; +import javax.validation.constraints.NotNull; + import com.maptology.service.entity.AbstractEntity; import com.maptology.service.entity.device.DeviceEntity; -import javax.persistence.*; -import java.util.List; /** * The entity to store a share @@ -16,26 +25,23 @@ import java.util.List; @Entity @Table(name = "share", indexes = { - @Index(columnList = "secretId", unique = true) + @Index(columnList = "token", unique = true) }) @NamedQueries({ - @NamedQuery(name = "findShareBySecretId", query = "select s from ShareEntity s where s.secretId=:secretId"), - @NamedQuery(name = "findShareById", query = "select s from ShareEntity s where s.id=:id"), - @NamedQuery(name = "findSharesByUser", query = "select s from ShareEntity s where s.device.user.id=:userId"), - @NamedQuery(name = "findSharesByUserCount", query = "select count(s) from ShareEntity s where s.device.user.id=:userId") + @NamedQuery(name = "findShareByToken", query = "select s from ShareEntity s where s.token=:token") }) public class ShareEntity extends AbstractEntity { /** - * The secret id that is needed to access this share. - * This field is generated on the server side. - */ - @Column(length = 128) - private String secretId; + * The serialization id to get rid of warnings. + */ + private static final long serialVersionUID = -636211508321203063L; + /** * The device that shares its location */ + @NotNull @ManyToOne(fetch = FetchType.LAZY) private DeviceEntity device; @@ -43,79 +49,157 @@ public class ShareEntity extends AbstractEntity { * This field indicates up to when the share is valid. */ private long expirationTime; + - public ShareEntity() { - this.secretId = SecureToken.createToken(32); - } + /** + * The secret token that is shared with other + * persons to get access to the share info and location. + */ + @Column(length = 128) + private String token; + + /** + * The message provided by the user. + */ + @Column(length = 200) + private String message; - public static ShareEntity findBySecretId(EntityManager em, String secretId) { + /** + * The destination provided by the user. + */ + @Column(length = 200) + private String destination; + + /** + * A boolean to pause the share temporarily. + */ + private boolean paused; + + /** + * Returns the device. + * + * @return The device. + */ + public DeviceEntity getDevice() { + return device; + } + + /** + * Sets the device. + * + * @param device The device to set. + */ + public void setDevice(DeviceEntity device) { + this.device = device; + } + + /** + * Returns the expirationTime. + * + * @return The expirationTime. + */ + public long getExpirationTime() { + return expirationTime; + } + + /** + * Sets the expirationTime. + * + * @param expirationTime The expirationTime to set. + */ + public void setExpirationTime(long expirationTime) { + this.expirationTime = expirationTime; + } + + /** + * Returns the token. + * + * @return The token. + */ + public String getToken() { + return token; + } + + /** + * Sets the token. + * + * @param token The token to set. + */ + public void setToken(String token) { + this.token = token; + } + + /** + * Returns the message. + * + * @return The message. + */ + public String getMessage() { + return message; + } + + /** + * Sets the message. + * + * @param message The message to set. + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * Returns the destination. + * + * @return The destination. + */ + public String getDestination() { + return destination; + } + + /** + * Sets the destination. + * + * @param destination The destination to set. + */ + public void setDestination(String destination) { + this.destination = destination; + } + + /** + * Returns the paused. + * + * @return The paused. + */ + public boolean isPaused() { + return paused; + } + + /** + * Sets the paused. + * + * @param paused The paused to set. + */ + public void setPaused(boolean paused) { + this.paused = paused; + } + + /** + * Finds a share by its token. + * + * @param em The entity manager. + * @param token The token to find. + * @return The share or null. + */ + public static ShareEntity findByToken(EntityManager em, String token) { try { - TypedQuery q = em.createNamedQuery("findShareBySecretId", ShareEntity.class); - q.setParameter("secretId", secretId); + TypedQuery q = em.createNamedQuery("findShareByToken", ShareEntity.class); + q.setParameter("token", token); return q.getSingleResult(); } catch (NoResultException e) { return null; } } - public static ShareEntity findById(EntityManager em, long id) { - try { - TypedQuery q = em.createNamedQuery("findShareById", ShareEntity.class); - q.setParameter("id", id); - return q.getSingleResult(); - } catch (NoResultException e) { - return null; - } - } - public static List getAllForUser(EntityManager em, long userId, PageConfig config, boolean filtered) { - try { - TypedQuery q = em.createNamedQuery("findSharesByUser", ShareEntity.class); - q.setParameter("userId", userId); - q.setFirstResult(config.getOffset()); - q.setMaxResults(config.getSize()); - return q.getResultList(); - } catch (NoResultException e) { - return null; - } - - } - - public static long getAllForUserCount(EntityManager em, long userId, boolean filtered) { - - try { - TypedQuery q = em.createNamedQuery("findSharesByUserCount", Long.class); - q.setParameter("userId", userId); - ; - return q.getSingleResult(); - } catch (NoResultException e) { - return 0; - } - - } - - public String getSecretId() { - return secretId; - } - - public void setSecretId(String secretId) { - this.secretId = secretId; - } - - public DeviceEntity getDevice() { - return device; - } - - public void setDevice(DeviceEntity device) { - this.device = device; - } - - public long getExpirationTime() { - return expirationTime; - } - - public void setExpirationTime(long expirationTime) { - this.expirationTime = expirationTime; - } } diff --git a/service/ejb/src/main/java/com/maptology/service/entity/user/UserEntity.java b/service/ejb/src/main/java/com/maptology/service/entity/user/UserEntity.java index a4738f4..ae83729 100644 --- a/service/ejb/src/main/java/com/maptology/service/entity/user/UserEntity.java +++ b/service/ejb/src/main/java/com/maptology/service/entity/user/UserEntity.java @@ -1,5 +1,6 @@ package com.maptology.service.entity.user; +import java.util.List; import java.util.Set; import javax.persistence.Column; @@ -17,9 +18,14 @@ import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.TypedQuery; import javax.persistence.UniqueConstraint; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; +import com.maptology.api.PageConfig; import com.maptology.service.entity.AbstractEntity; /** @@ -33,7 +39,7 @@ import com.maptology.service.entity.AbstractEntity; indexes = @Index(columnList="deleted,modificationTime", unique = false) ) @NamedQueries({ - @NamedQuery(name="findUserByLogin", query="select u from UserEntity u where u.login=:login") + @NamedQuery(name="findUserByLogin", query="select u from UserEntity u where u.login=:login"), }) public class UserEntity extends AbstractEntity { @@ -256,5 +262,59 @@ public class UserEntity extends AbstractEntity { } } + /** + * Counts the number of users whose login or name contains the string. + * + * @param em The entity manager. + * @param term The string to search for. + * @param filtered True to filter deleted. + * @return The number of results. + */ + public static Long countByTerm(EntityManager em, String term, boolean filtered) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(Long.class); + Root r = cq.from(UserEntity.class); // from UserEntity e + cq.select(cb.count(r)); // select count(e) + Predicate like = cb.or(cb.like(r.get("login"), "%"+term+"%"), // login like %term% + cb.like(r.get("name"), "%"+term+"%")); // or name like %term% + if (filtered) { + cq.where(cb.and(cb.equal(r.get("deleted"), false), like)); // and not deleted + } else { + cq.where(like); // ignore deleted + } + try { + TypedQuery q = em.createQuery(cq); + return q.getSingleResult(); + } catch (NoResultException e) { + return new Long(0); + } + } + + /** + * Finds the users for a page whose login name or name contains the string. + * + * @param em The entity manager. + * @param term The string to search for. + * @param filtered True to filter deleted. + * @param page The page configuration. + * @return The list to fill the page. + */ + public static List findByTerm(EntityManager em, String term, PageConfig page, boolean filtered) { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cq = cb.createQuery(UserEntity.class); + Root r = cq.from(UserEntity.class); // from UserEntity e + cq.select(r); // select E + Predicate like = cb.or(cb.like(r.get("login"), "%"+term+"%"), // login like %term% + cb.like(r.get("name"), "%"+term+"%")); // or name like %term% + if (filtered) { + cq.where(cb.and(cb.equal(r.get("deleted"), false), like)); // and not deleted + } else { + cq.where(like); // ignore deleted + } + TypedQuery q = em.createQuery(cq); + q.setFirstResult(page.getOffset()); + q.setMaxResults(page.getSize()); + return q.getResultList(); + } } diff --git a/service/ejb/src/main/java/com/maptology/service/principal/MaptologyPrincipal.java b/service/ejb/src/main/java/com/maptology/service/principal/MaptologyPrincipal.java new file mode 100644 index 0000000..9b65039 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/principal/MaptologyPrincipal.java @@ -0,0 +1,89 @@ +package com.maptology.service.principal; + +import java.security.Principal; + +/** + * A custom principal that provides the device id and the user id + * of users and devices that have logged in successfully. + * + * @author Ole + */ +public final class MaptologyPrincipal implements Principal { + + /** + * The login name of the authenticated user. Could be null if only a device is + * authenticated. + */ + private Long user; + + /** + * The id of the authenticated device. Could be null if only an user is + * authenticated. + */ + private Long device; + + /** + * The name consisting of the user login and the device token combined with a + * colon (i.e. login:token). + */ + private String name; + + /** + * Creates a new principal with the specified name, user and device. + * + * @param name + * The name consisting of login:token, not null. + * @param user + * The user id, if available. + * @param device + * The device id, if available. + */ + public MaptologyPrincipal(String name, Long user, Long device) { + if (name == null) + throw new IllegalArgumentException("Name must not be null."); + this.name = name; + this.user = user; + this.device = device; + } + + /** + * Returns the device id or null, if no device is logged in. + * + * @return The device id or null. + */ + public Long getDevice() { + return device; + } + + /** + * Returns the user id or null, if no user is logged in. + * + * @return The user id or null. + */ + public Long getUser() { + return user; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MaptologyPrincipal p = (MaptologyPrincipal)o; + return p.name.equals(name); + } + + @Override + public int hashCode() { + return name.hashCode(); + } + + @Override + public String toString() { + return name + " (" + user + ":" + device + ")"; + } + + @Override + public String getName() { + return name; + } +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/AbstractPrincipalSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/AbstractPrincipalSessionBean.java new file mode 100644 index 0000000..7cff290 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/session/AbstractPrincipalSessionBean.java @@ -0,0 +1,70 @@ +package com.maptology.service.session; + +import java.security.Principal; +import java.util.logging.Level; + +import javax.annotation.Resource; +import javax.ejb.SessionContext; + +import com.maptology.service.entity.device.DeviceEntity; +import com.maptology.service.entity.user.UserEntity; +import com.maptology.service.principal.MaptologyPrincipal; + +/** + * An abstract base class for session beans that require + * access to the caller principal. It provides methods to + * access the device entity and the user entity that are + * representing the caller in a clean and simple way. + * + * @author Marcus + */ +public abstract class AbstractPrincipalSessionBean extends AbstractSessionBean { + + /** + * The session context to access the principal. + */ + @Resource + protected SessionContext sessionContext; + + /** + * Returns the caller principal casted into a maptology + * principal or null, if this is not possible. + * + * @return The maptology principal or null. + */ + protected MaptologyPrincipal getPrincipal() { + Principal p = sessionContext.getCallerPrincipal(); + log.log(Level.INFO, "Principal is: " + p); + if (p instanceof MaptologyPrincipal) { + return (MaptologyPrincipal)p; + } + return null; + } + + /** + * Returns the user entity for the caller principal or + * null, if the user cannot be determined. + * + * @return The user entity of the caller or null. + */ + protected UserEntity getPrincipalUser() { + MaptologyPrincipal p = getPrincipal(); + log.log(Level.INFO, "Principal is: " + p); + if (p == null || p.getUser() == null) return null; + return em.find(UserEntity.class, p.getUser()); + } + + /** + * Returns the device entity of the caller or null, + * if the device entity cannot be determined. + * + * @return The device entity of the caller or null. + */ + protected DeviceEntity getPrincipalDevice() { + MaptologyPrincipal p = getPrincipal(); + if (p == null || p.getDevice() == null) return null; + return em.find(DeviceEntity.class, p.getDevice()); + } + + +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/DataInitializerBean.java b/service/ejb/src/main/java/com/maptology/service/session/DataSessionBean.java similarity index 82% rename from service/ejb/src/main/java/com/maptology/service/session/DataInitializerBean.java rename to service/ejb/src/main/java/com/maptology/service/session/DataSessionBean.java index 0b28650..cdd4a9e 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/DataInitializerBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/DataSessionBean.java @@ -4,10 +4,9 @@ import java.util.HashSet; import java.util.logging.Level; import java.util.logging.Logger; -import javax.annotation.PostConstruct; -import javax.ejb.DependsOn; -import javax.ejb.Singleton; -import javax.ejb.Startup; +import javax.annotation.security.PermitAll; +import javax.ejb.Stateful; +import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.persistence.EntityManager; @@ -18,15 +17,14 @@ import com.maptology.service.entity.user.RoleEntity; import com.maptology.service.entity.user.UserEntity; /** - * A bean that is executed at startup to initialize the - * database with the default roles and users. + * A bean that is executed by the startup bean to + * initialize the database. * * @author Marcus */ -@Startup -@Singleton -@DependsOn(value= { "LogSessionBean" }) -public class DataInitializerBean { +@Stateful +@RequestScoped +public class DataSessionBean implements IDataSessionBean { @Inject @@ -35,8 +33,10 @@ public class DataInitializerBean { @Inject protected EntityManager em; - - @PostConstruct + /** + * Initializes the data. + */ + @PermitAll public void init() { initRoles(); initUsers(); @@ -45,8 +45,8 @@ public class DataInitializerBean { /** * Initializes the database with the default roles. */ - public void initRoles() { - log.log(Level.INFO, "Initializing roles."); + protected void initRoles() { + log.log(Level.INFO, "Initializing roles (data)."); addRole(Roles.ADMIN, "Grants admin privileges."); addRole(Roles.USER, "Grants user privileges."); addRole(Roles.DEVICE, "Grants device privileges."); @@ -59,7 +59,7 @@ public class DataInitializerBean { * @param description The description of the role. * @return The role that was present or has been added. */ - public RoleEntity addRole(String name, String description) { + protected RoleEntity addRole(String name, String description) { log.log(Level.INFO, "Creating role " + name + "."); RoleEntity r = RoleEntity.findByName(em, name); if (r != null) { @@ -79,7 +79,7 @@ public class DataInitializerBean { /** * Initializes a default set of users. */ - public void initUsers() { + protected void initUsers() { log.log(Level.INFO, "Initializing users."); initUser("admin", "Administrator", "admin", "nes-admin@uni-due.de", new String[] { Roles.ADMIN, Roles.USER}); initUser("handte", "Marcus Handte", "secure", "marcus.handte@uni-due.de", new String[] { Roles.USER }); @@ -95,7 +95,7 @@ public class DataInitializerBean { * @param roles The roles. * @return The created or existing user. */ - public UserEntity initUser(String login, String name, String password, String email, String[] roles) { + protected UserEntity initUser(String login, String name, String password, String email, String[] roles) { log.log(Level.INFO, "Creating user " + login + "."); UserEntity u = UserEntity.findByLogin(em, login); if (u != null) { diff --git a/service/ejb/src/main/java/com/maptology/service/session/DebugDataSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/DebugDataSessionBean.java new file mode 100644 index 0000000..10d6579 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/session/DebugDataSessionBean.java @@ -0,0 +1,26 @@ +package com.maptology.service.session; + +import javax.ejb.Stateful; +import javax.enterprise.context.RequestScoped; +import javax.enterprise.inject.Alternative; + +/** + * An extended implementation of the data session + * bean that initializes the database in a more + * complete state for testing. + * + * @author Marcus + */ +@Alternative +@Stateful +@RequestScoped +public class DebugDataSessionBean extends DataSessionBean { + + + @Override + public void init() { + super.init(); + // here you can initialize more data + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java index f96372b..2ead0dd 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/DebugEmailSessionBean.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; +import javax.annotation.security.PermitAll; import javax.ejb.Lock; import javax.ejb.LockType; import javax.ejb.Singleton; @@ -36,12 +37,14 @@ public class DebugEmailSessionBean implements IDebugEmailSessionBean { @Override @Lock(LockType.WRITE) + @PermitAll public void sendEmail(String receiver, String subject, String body) { sendEmail("noreply@maptology.com", receiver, subject, body); } @Override @Lock(LockType.WRITE) + @PermitAll public void sendEmail(String sender, String receiver, String subject, String body) { EmailEntry entry = new EmailEntry(sender, receiver, subject, body); log.log(Level.INFO, entry.toString()); @@ -50,6 +53,7 @@ public class DebugEmailSessionBean implements IDebugEmailSessionBean { @Override @Lock(LockType.READ) + @PermitAll public List getEntries() { return entries; } diff --git a/service/ejb/src/main/java/com/maptology/service/session/DeviceSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/DeviceSessionBean.java index fc7d4ea..239b104 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/DeviceSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/DeviceSessionBean.java @@ -1,26 +1,32 @@ package com.maptology.service.session; +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.security.DeclareRoles; +import javax.annotation.security.PermitAll; +import javax.annotation.security.RolesAllowed; +import javax.ejb.Stateful; +import javax.enterprise.context.RequestScoped; + import com.maptology.api.PageConfig; import com.maptology.api.access.Roles; import com.maptology.api.device.Device; +import com.maptology.api.device.DeviceHandle; +import com.maptology.api.device.DeviceInfo; import com.maptology.api.device.DevicePage; import com.maptology.service.conversion.DeviceConverter; +import com.maptology.service.conversion.DeviceHandleConverter; +import com.maptology.service.crypto.SecureToken; +import com.maptology.service.crypto.TokenType; import com.maptology.service.entity.AbstractEntity; +import com.maptology.service.entity.EntityForbiddenException; +import com.maptology.service.entity.EntityNotFoundException; import com.maptology.service.entity.OrderCriterion; import com.maptology.service.entity.device.DeviceEntity; import com.maptology.service.entity.user.UserEntity; -import javax.annotation.Resource; -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; -import javax.ejb.EJB; -import javax.ejb.SessionContext; -import javax.ejb.Stateful; -import javax.enterprise.context.RequestScoped; -import javax.ws.rs.NotFoundException; -import java.util.logging.Level; - /** * A stateful session bean to manage devices. * @@ -28,33 +34,56 @@ import java.util.logging.Level; */ @Stateful @RequestScoped -public class DeviceSessionBean extends AbstractSessionBean { - - @EJB - UserSessionBean userSession; - - /** - * The context to lookup prinicpals and roles - * of a caller. - */ - @Resource - private SessionContext sessionContext; +@DeclareRoles({ Roles.ADMIN, Roles.USER, Roles.DEVICE }) +public class DeviceSessionBean extends AbstractPrincipalSessionBean { /** * Adds a new device to the database. * - * @return The new device, also containing the secret to be used for authentication. + * @return The new device handle. */ @PermitAll - public Device addDevice(Device device) { - - UserEntity userEntity = userSession.getCurrentUserEntity(); + public DeviceHandle addDevice(DeviceInfo info) { DeviceEntity entity = new DeviceEntity(); - entity.setUser(userEntity); - - em.persist(entity); // add to persistence context - em.flush(); // generate the id (don't wait for end of transaction) - return new DeviceConverter(false, true).convert(entity); + entity.setUser(getPrincipalUser()); + entity.setDevice(info.getDevice()); + entity.setManufacturer(info.getManufacturer()); + entity.setModel(info.getModel()); + entity.setOs(info.getOs()); + entity.setToken(SecureToken.createToken(TokenType.INTERNAL)); + em.persist(entity); + em.flush(); + return new DeviceHandleConverter(true).convert(entity); + } + + + /** + * Returns the current device. + * + * @return The current device. + * @throws EntityNotFoundException Thrown if the entity cannot be found. + * @throws EntityForbiddenException Thrown if the entity is deleted. + */ + @RolesAllowed({Roles.DEVICE}) + public Device getCurrentDevice() throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity entity = getPrincipalDevice(); + if (entity == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device."); + if (entity.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, entity.getId(), "Device is deleted."); + return new DeviceConverter(true).convert(entity); + } + + /** + * Deletes the current device. + * + * @throws EntityNotFoundException Throw if the device is not found. + * @throws EntityForbiddenException Thrown if the device is deleted already. + */ + @RolesAllowed({Roles.DEVICE}) + public void deleteCurrentDevice() throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = getPrincipalDevice(); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device."); + if (device.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted."); + device.setDeleted(true); } /** @@ -65,27 +94,48 @@ public class DeviceSessionBean extends AbstractSessionBean { * @return The page of devices. */ @RolesAllowed({Roles.ADMIN}) - public DevicePage getAll(PageConfig pageConfig, boolean filtered) { + public DevicePage getAllDevices(PageConfig pageConfig, boolean filtered) { return getAll(DeviceEntity.class, pageConfig, new OrderCriterion("id", true), filtered, new DevicePage(), new DeviceConverter(filtered)); } - + /** - * Returns the entity of the currently authenticated device. - * - * @return The device entity or null if there is no device authenticated + * Returns a device page for the current user ordered by the creation time. + * + * @param pageConfig The page configuration. + * @param filtered True to filter. + * @return The page of devices. + * @throws EntityNotFoundException Thrown if the user cannot be found. */ - @PermitAll - public DeviceEntity getCurrentDeviceEntity() { - try { - MaptologyPrincipal principal = (MaptologyPrincipal) sessionContext.getCallerPrincipal(); - if (principal.getDeviceId() != null) { - return DeviceEntity.find(em, DeviceEntity.class , principal.getDeviceId(), true); - } - } catch (ClassCastException e) { - log.log(Level.WARNING, "Wrong Principal Implementation. Pleas use the MaptologyPrincipal class in order to ensure that the service is working!"); - } - return null; + @RolesAllowed({Roles.USER}) + public DevicePage getAllDevicesForCurrentUser(PageConfig pageConfig, boolean filtered) throws EntityNotFoundException { + UserEntity user = getPrincipalUser(); + if (user == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user."); + int count = DeviceEntity.getCountForUser(em, user, filtered); + List data = new ArrayList<>(); + if (count > pageConfig.getOffset()) { + data = DeviceEntity.findAllForUser(em, user, pageConfig, new OrderCriterion("creationTime"), filtered); + } + DevicePage page = new DevicePage(); + page.setElements(new DeviceConverter(filtered).convert(data)); + page.setOffset(pageConfig.getOffset()); + page.setSize(pageConfig.getSize()); + page.setTotal(count); + return page; } + + /** + * Returns the last modification time for the devices of the current user. + * + * @return The last modification time for the devices of the current user or 0 if the user does not have any devices. + * @throws EntityNotFoundException Thrown if the current user cannot be found. + */ + @RolesAllowed({Roles.USER}) + public long getLastModifiedDeviceForCurrentUser() throws EntityNotFoundException { + UserEntity user = getPrincipalUser(); + if (user == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot find principal user."); + return DeviceEntity.getLastModifiedForUser(em, user); + } + /** * Returns the time stamp of the last modification to the set of devices. @@ -93,24 +143,82 @@ public class DeviceSessionBean extends AbstractSessionBean { * @return The time stamp of the last device modification. */ @PermitAll - public long getLastModified() { + public long getLastModifiedDevice() { return AbstractEntity.getLastModified(em, DeviceEntity.class); } + + /** + * Allows an admin to access all devices by id and a user to access his own devices by id. + * + * @param id The id to fetch. + * @return The device with the id. + * @throws EntityNotFoundException Thrown if the device cannot be found. + * @throws EntityForbiddenException Thrown if the entity cannot be accessed. + */ + @RolesAllowed({Roles.USER, Roles.ADMIN}) + public Device getDevice(long id) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = em.find(DeviceEntity.class, new Long(id)); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found."); + if (!sessionContext.isCallerInRole(Roles.ADMIN)) { + if (device.isDeleted()) { + throw new EntityForbiddenException(DeviceEntity.class, id, "Device is deleted."); + } + UserEntity principal = getPrincipalUser(); + if (principal == null || device.getUser() != principal) { + throw new EntityForbiddenException(DeviceEntity.class, id, "Device access is not allowed."); + } + } + em.flush(); + return new DeviceConverter(false).convert(device); + } + + /** + * Sets the device values. + * + * @param id The id of the device. + * @param device The device values. + * @return The updated device. + * @throws EntityNotFoundException Thrown if the entity cannot be found. + */ + @RolesAllowed({Roles.ADMIN}) + public Device setDevice(long id, Device device) throws EntityNotFoundException { + DeviceEntity entity = em.find(DeviceEntity.class, new Long(id)); + if (entity == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found."); + entity.setDeleted(device.isDeleted()); + entity.setDevice(device.getDevice()); + entity.setManufacturer(device.getManufacturer()); + entity.setModel(device.getModel()); + entity.setOs(device.getOs()); + if (device.getUser() != null) { + entity.setUser(em.find(UserEntity.class, device.getUser())); + } else { + entity.setUser(null); + } + em.flush(); + return new DeviceConverter(false).convert(entity); + } /** - * Sets a device as deleted. + * Deletes a device. * * @param id The id of the device. - * @return The device if successfully deleted or already deleted, or null if the device was not found. - * @throws NotFoundException if no device for this id exists. + * @throws EntityNotFoundException Thrown if the device is not found. + * @throws EntityForbiddenException Thrown if the user cannot access the device. */ - @RolesAllowed(Roles.ADMIN) - public Device removeDevice(long id) { - DeviceEntity entity = DeviceEntity.find(em, DeviceEntity.class, id, false); - if (entity == null) { - throw new NotFoundException(); - } - entity.setDeleted(true); - return new DeviceConverter(false).convert(entity); + @RolesAllowed({Roles.ADMIN, Roles.USER}) + public void deleteDevice(long id) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = em.find(DeviceEntity.class, new Long(id)); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found."); + if (!sessionContext.isCallerInRole(Roles.ADMIN)) { + if (device.isDeleted()) { + throw new EntityForbiddenException(DeviceEntity.class, id, "Device is deleted."); + } + UserEntity principal = getPrincipalUser(); + if (principal == null || device.getUser() != principal) { + throw new EntityForbiddenException(DeviceEntity.class, id, "Device access is not allowed."); + } + } + device.setDeleted(true); } + } diff --git a/service/ejb/src/main/java/com/maptology/service/session/DefaultEmailSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/EmailSessionBean.java similarity index 92% rename from service/ejb/src/main/java/com/maptology/service/session/DefaultEmailSessionBean.java rename to service/ejb/src/main/java/com/maptology/service/session/EmailSessionBean.java index b949837..20b7103 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/DefaultEmailSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/EmailSessionBean.java @@ -3,6 +3,7 @@ package com.maptology.service.session; import java.util.logging.Level; import java.util.logging.Logger; +import javax.annotation.security.PermitAll; import javax.ejb.Stateful; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; @@ -23,7 +24,7 @@ import javax.mail.internet.MimeMessage; */ @RequestScoped @Stateful -public class DefaultEmailSessionBean implements IEmailSessionBean { +public class EmailSessionBean implements IEmailSessionBean { @Inject private Logger log; @@ -32,11 +33,13 @@ public class DefaultEmailSessionBean implements IEmailSessionBean { private Session mailSession; @Override + @PermitAll public void sendEmail(String receiver, String subject, String body) { sendEmail("noreply@maptology.com", receiver, subject, body); } @Override + @PermitAll public void sendEmail(String sender, String receiver, String subject, String body) { log.log(Level.INFO, String.format("Sending message from '%s' to '%s' with subject '%s'.", sender, receiver, subject)); Message message = new MimeMessage(mailSession); diff --git a/service/ejb/src/main/java/com/maptology/service/session/IDataSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/IDataSessionBean.java new file mode 100644 index 0000000..f385cc6 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/session/IDataSessionBean.java @@ -0,0 +1,16 @@ +package com.maptology.service.session; + +/** + * A bean that initializes the database. + * + * @author Marcus + */ +public interface IDataSessionBean { + + /** + * Initializes the database with + * default data. + */ + void init(); + +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/LocationSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/LocationSessionBean.java index 800e893..0f03601 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/LocationSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/LocationSessionBean.java @@ -1,13 +1,25 @@ package com.maptology.service.session; -import com.maptology.api.access.Roles; -import com.maptology.api.device.Location; -import com.maptology.service.entity.location.LocationEntity; - +import javax.annotation.security.DeclareRoles; +import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; -import javax.ejb.EJB; import javax.ejb.Stateful; import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; + +import com.maptology.api.access.Roles; +import com.maptology.api.location.Availability; +import com.maptology.api.location.Coordinate; +import com.maptology.api.location.Location; +import com.maptology.api.location.LocationUpdate; +import com.maptology.api.location.ReleasedLocation; +import com.maptology.service.conversion.LocationConverter; +import com.maptology.service.entity.EntityForbiddenException; +import com.maptology.service.entity.EntityNotFoundException; +import com.maptology.service.entity.device.DeviceEntity; +import com.maptology.service.entity.location.EmbeddedCoordinate; +import com.maptology.service.entity.location.LocationEntity; +import com.maptology.service.entity.share.ShareEntity; /** * A stateful session to manage locations @@ -16,25 +28,104 @@ import javax.enterprise.context.RequestScoped; */ @Stateful @RequestScoped -public class LocationSessionBean extends AbstractSessionBean { - - @EJB - private DeviceSessionBean deviceSessionBean; - +@DeclareRoles({ Roles.ADMIN, Roles.USER, Roles.DEVICE }) +public class LocationSessionBean extends AbstractPrincipalSessionBean { + + /** + * The bean to find shares. + */ + @Inject + ShareSessionBean shareSession; + + /** + * Adds a set of locations to the database for the principal device. + * + * @param update The update with the locations. + * @throws EntityNotFoundException Thrown if the device cannot be found. + * @throws EntityForbiddenException Thrown if the device is deleted. + */ @RolesAllowed({Roles.DEVICE}) - public void addLocation(Location location) { - LocationEntity locationEntity = new LocationEntity(); - locationEntity.setLat(location.getLat()); - locationEntity.setLon(location.getLon()); - locationEntity.setTimestamp(location.getTimestamp()); - locationEntity.setDevice(deviceSessionBean.getCurrentDeviceEntity()); - - em.persist(locationEntity); + public void addLocations(LocationUpdate update) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = getPrincipalDevice(); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot update locations without principal device."); + if (device.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted."); + LocationEntity lastLocation = null; + for (ReleasedLocation location: update.getLocations()) { + lastLocation = new LocationEntity(); + lastLocation.setAvailability(location.getAvailability()); + lastLocation.setDevice(device); + lastLocation.setTimestamp(location.getTimestamp()); + Coordinate c = location.getCoordinate(); + if (c != null) { + lastLocation.setCoordinate(new EmbeddedCoordinate(c.getLongitude(), c.getLatitude())); + } + em.persist(lastLocation); + } + if (lastLocation != null) { + device.setLocation(lastLocation); + } } - - @RolesAllowed({Roles.DEVICE}) - public void getLastKnownLocation() { - LocationEntity.findLastLocation(em, deviceSessionBean.getCurrentDeviceEntity().getId()); + + /** + * Returns the last known location for a share. + * + * @param token The secret id that identifies a share. + * @param currentTime The current time. + * @return The location. + * @throws EntityNotFoundException If the share cannot be found. + * @throws EntityForbiddenException If the share cannot be accessed. + */ + @PermitAll + public Location getShareLocation(String token, long currentTime) throws EntityNotFoundException, EntityForbiddenException { + ShareEntity shareEntity = shareSession.findShare(token, currentTime); + LocationEntity location = shareEntity.getDevice().getLocation(); + Location result = new Location(); + if (location == null || location.isDeleted()) { + result.setAvailability(Availability.UNABLE); + result.setTimestamp(shareEntity.getDevice().getModificationTime()); + return result; + } else if (shareEntity.isPaused()) { + result.setAvailability(Availability.PRIVATE); + result.setTimestamp(location.getTimestamp()); + return result; + } else { + return new LocationConverter(false).convert(location); + } + } + + /** + * Returns the last known location for a device. + * + * @param id The id of the device. + * @return The location. + * @throws EntityNotFoundException Thrown if the device cannot be found. + * @throws EntityForbiddenException Thrown if the user cannot access the device. + */ + @RolesAllowed({Roles.ADMIN, Roles.USER}) + public Location getDeviceLocation(long id) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = em.find(DeviceEntity.class, id); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, id, "Device not found."); + if (sessionContext.isCallerInRole(Roles.ADMIN)) { + if (device.getLocation() == null) { + Location result = new Location(); + result.setAvailability(Availability.UNABLE); + result.setTimestamp(device.getModificationTime()); + return result; + } else { + return new LocationConverter(false).convert(device.getLocation()); + } + } else if (!device.isDeleted() && device.getUser() != null && device.getUser() == getPrincipalUser()) { + if (device.getLocation() == null || device.getLocation().isDeleted()) { + Location result = new Location(); + result.setAvailability(Availability.UNABLE); + result.setTimestamp(device.getModificationTime()); + return result; + } else { + return new LocationConverter(false).convert(device.getLocation()); + } + } else { + throw new EntityForbiddenException(DeviceEntity.class, id, "User may not access device."); + } } } diff --git a/service/ejb/src/main/java/com/maptology/service/session/LogSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/LogSessionBean.java index fc8ebdf..f40ca3f 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/LogSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/LogSessionBean.java @@ -12,6 +12,7 @@ import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import javax.annotation.security.DeclareRoles; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.ejb.ConcurrencyManagement; @@ -31,6 +32,7 @@ import com.maptology.api.log.LogMessage; @Startup @Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) +@DeclareRoles(Roles.ADMIN) public class LogSessionBean { /** diff --git a/service/ejb/src/main/java/com/maptology/service/session/MaptologyPrincipal.java b/service/ejb/src/main/java/com/maptology/service/session/MaptologyPrincipal.java deleted file mode 100644 index 3bbdf1d..0000000 --- a/service/ejb/src/main/java/com/maptology/service/session/MaptologyPrincipal.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.maptology.service.session; - - -import java.security.Principal; - -/** - * A custom Principal that can additionally contain the id of an authenticated device - * - * @author Ole - */ -public final class MaptologyPrincipal implements Principal { - - /** - * The login name of the authenticated user. Could be null if only a device is authenticated. - */ - private String userLogin; - /** - * The id of the authenticated device. Could be null if only an user is authenticated. - */ - private Long deviceId; - - public MaptologyPrincipal(String userLogin, Long deviceId) { - this.userLogin = userLogin; - this.deviceId = deviceId; - } - - public Long getDeviceId() { - return deviceId; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - MaptologyPrincipal that = (MaptologyPrincipal) o; - - if (deviceId != that.deviceId) return false; - return userLogin != null ? userLogin.equals(that.userLogin) : that.userLogin == null; - } - - @Override - public int hashCode() { - int result = userLogin != null ? userLogin.hashCode() : 0; - result = 31 * result + (int) (deviceId ^ (deviceId >>> 32)); - return result; - } - - @Override - public String toString() { - return "MaptologyPrincipal{" + - "userLogin='" + userLogin + '\'' + - ", deviceId=" + deviceId + - '}'; - } - - @Override - public String getName() { - return userLogin; - } -} diff --git a/service/ejb/src/main/java/com/maptology/service/session/ResourceConflictException.java b/service/ejb/src/main/java/com/maptology/service/session/ResourceConflictException.java deleted file mode 100644 index fc41ced..0000000 --- a/service/ejb/src/main/java/com/maptology/service/session/ResourceConflictException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.maptology.service.session; - -import javax.ws.rs.ClientErrorException; -import javax.ws.rs.core.Response; - -/** - * An exception indicating a conflict with the current state of a resource - * - * @author Ole - */ -public class ResourceConflictException extends ClientErrorException { - public ResourceConflictException() { - super(Response.Status.CONFLICT); - } -} diff --git a/service/ejb/src/main/java/com/maptology/service/session/ShareSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/ShareSessionBean.java index 4371b2e..2edfb05 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/ShareSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/ShareSessionBean.java @@ -1,122 +1,157 @@ package com.maptology.service.session; +import javax.annotation.security.DeclareRoles; +import javax.annotation.security.PermitAll; +import javax.annotation.security.RolesAllowed; +import javax.ejb.Stateful; +import javax.enterprise.context.RequestScoped; + import com.maptology.api.PageConfig; import com.maptology.api.access.Roles; -import com.maptology.api.device.Location; import com.maptology.api.share.Share; +import com.maptology.api.share.ShareInfo; import com.maptology.api.share.SharePage; -import com.maptology.service.conversion.LocationConverter; import com.maptology.service.conversion.ShareConverter; +import com.maptology.service.conversion.ShareInfoConverter; +import com.maptology.service.crypto.SecureToken; +import com.maptology.service.crypto.TokenType; import com.maptology.service.entity.AbstractEntity; +import com.maptology.service.entity.EntityForbiddenException; +import com.maptology.service.entity.EntityNotFoundException; import com.maptology.service.entity.OrderCriterion; import com.maptology.service.entity.device.DeviceEntity; -import com.maptology.service.entity.location.LocationEntity; import com.maptology.service.entity.share.ShareEntity; -import com.maptology.service.entity.user.UserEntity; - -import javax.annotation.security.PermitAll; -import javax.annotation.security.RolesAllowed; -import javax.ejb.EJB; -import javax.ejb.Stateful; -import javax.enterprise.context.RequestScoped; -import javax.persistence.PersistenceException; -import javax.ws.rs.ForbiddenException; -import javax.ws.rs.NotFoundException; -import java.util.List; -import java.util.logging.Level; /** * A stateful session bean that provides methods to manipulate shares. + * * @author Ole */ @Stateful @RequestScoped -public class ShareSessionBean extends AbstractSessionBean { +@DeclareRoles({ Roles.ADMIN, Roles.USER, Roles.DEVICE }) +public class ShareSessionBean extends AbstractPrincipalSessionBean { + /** - * The DeviceSessionBean for accessing the current authenticated device - */ - @EJB - private DeviceSessionBean deviceSession; - - /** - * The UserSessionBean for accessing the current authenticated user - */ - @EJB - private UserSessionBean userSessionBean; - - /** - * This method creates a new share for an device based on the information provided by the client + * Creates a new share for the current device. * - * @param secretId The client generated secretId. This happens on the client side to enable async share creation (for example if the device is offline). - * @param expirationTime Determines how long the share is valid and accessible - * @return The created share + * @param share The share info. + * @return The created share. + * @throws EntityNotFoundException Thrown if the device cannot be found. + * @throws EntityForbiddenException Thrown if the device is deleted. */ @RolesAllowed({Roles.DEVICE}) - public ShareEntity createShare(String secretId, long expirationTime) { - DeviceEntity device = deviceSession.getCurrentDeviceEntity(); + public Share createShare(ShareInfo share) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = getPrincipalDevice(); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device."); + if (device.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted."); ShareEntity shareEntity = new ShareEntity(); shareEntity.setDevice(device); - shareEntity.setExpirationTime(expirationTime); - shareEntity.setSecretId(secretId); - try { - em.persist(shareEntity); - em.flush(); - } catch (Exception e) { - if (e instanceof PersistenceException) { - log.log(Level.INFO, "User try to create a second share using the same secret."); - throw new ResourceConflictException(); - } else { - log.log(Level.INFO, "Can't persist share", e); - } - } - return shareEntity; + shareEntity.setExpirationTime(share.getExpirationTime()); + shareEntity.setToken(SecureToken.createToken(TokenType.EXTERNAL)); + shareEntity.setDestination(share.getDestination()); + shareEntity.setMessage(share.getMessage()); + em.persist(shareEntity); + em.flush(); + return new ShareConverter(false).convert(shareEntity); } - + + /** + * Returns the share with the id. + * + * @param id The id of the share. + * @return The share for the id. + * @throws EntityNotFoundException Thrown if the entity is not found. + * @throws EntityForbiddenException Thrown if the entity may not be accessed. + */ @RolesAllowed({Roles.DEVICE}) - public void deleteShare(long id) { - DeviceEntity device = deviceSession.getCurrentDeviceEntity(); - ShareEntity share = getShareById(id); - if (share == null) throw new NotFoundException(); - if (device == null || share.getDevice().getId() != device.getId()) throw new ForbiddenException(); - - device.setDeleted(true); - em.persist(share); + public Share getShare(long id) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = getPrincipalDevice(); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device."); + if (device.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted."); + ShareEntity shareEntity = em.find(ShareEntity.class, new Long(id)); + if (shareEntity == null) throw new EntityNotFoundException(ShareEntity.class, id, "Share does not exist."); + if (shareEntity.isDeleted()) throw new EntityNotFoundException(ShareEntity.class, id, "Share is deleted."); + if (shareEntity.getDevice() != device) throw new EntityForbiddenException(ShareEntity.class, id, "Device is not allowed to access share."); + return new ShareConverter(false).convert(shareEntity); } /** - * Get share for a secret id + * Sets the share with the id. + * + * @param id The id of the share. + * @param share The share values to set. + * @return The updated share. + * @throws EntityNotFoundException Thrown if the entity is not found. + * @throws EntityForbiddenException Thrown if the entity may not be accessed. + */ + @RolesAllowed({Roles.DEVICE}) + public Share setShare(long id, Share share) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = getPrincipalDevice(); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device."); + if (device.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted."); + ShareEntity shareEntity = em.find(ShareEntity.class, new Long(id)); + if (shareEntity == null) throw new EntityNotFoundException(ShareEntity.class, id, "Share does not exist."); + if (shareEntity.isDeleted()) throw new EntityNotFoundException(ShareEntity.class, id, "Share is deleted."); + if (shareEntity.getDevice() != device) throw new EntityForbiddenException(ShareEntity.class, id, "Device is not allowed to access share."); + shareEntity.setDestination(share.getDestination()); + shareEntity.setExpirationTime(share.getExpirationTime()); + shareEntity.setPaused(share.isPaused()); + shareEntity.setMessage(share.getMessage()); + em.flush(); + return new ShareConverter(false).convert(shareEntity); + } + + /** + * Deletes a share with a particular id. + * + * @param id + * @throws EntityNotFoundException + * @throws EntityForbiddenException + */ + @RolesAllowed({Roles.DEVICE}) + public void deleteShare(long id) throws EntityNotFoundException, EntityForbiddenException { + DeviceEntity device = getPrincipalDevice(); + if (device == null) throw new EntityNotFoundException(DeviceEntity.class, null, "Cannot find principal device."); + if (device.isDeleted()) throw new EntityForbiddenException(DeviceEntity.class, device.getId(), "Device is deleted."); + ShareEntity share = em.find(ShareEntity.class, new Long(id)); + if (share == null) throw new EntityNotFoundException(ShareEntity.class, id, "Cannot find share."); + if (share.isDeleted()) throw new EntityForbiddenException(ShareEntity.class, id, "Share is deleted."); + if (share.getDevice() != device) throw new EntityForbiddenException(ShareEntity.class, id, "Device is not allowed to access share."); + share.setDeleted(true); + } + + /** + * Finds a share for a token. * - * @param secretId The secret id - * @return The share or null if there is no share for the provided secret id + * @param token The secret token. + * @param currentTime The current time in Epoch milliseconds. + * @return The share entity. + * @throws EntityNotFoundException Thrown if the share is not found, deleted or expired. */ @PermitAll - public ShareEntity getShareEntityBySecretId(String secretId) { - return ShareEntity.findBySecretId(em, secretId); + public ShareEntity findShare(String token, long currentTime) throws EntityNotFoundException { + ShareEntity entity = ShareEntity.findByToken(em, token); + if (entity == null) throw new EntityNotFoundException(ShareEntity.class, null, "Share not found."); + if (entity.isDeleted()) throw new EntityNotFoundException(ShareEntity.class, entity.getId(), "Share is deleted."); + if (entity.getExpirationTime() <= currentTime) throw new EntityNotFoundException(ShareEntity.class, entity.getId(), "Share is expired."); + return entity; } /** - * Get share for a secret id + * Gets a share info for a token. * - * @param secretId The secret id - * @return The share or null if there is no share for the provided secret id + * @param token The secret token. + * @param currentTime The current time in Epoch milliseconds. + * @return The share info. + * @throws EntityNotFoundException Thrown if the share is not found, deleted or expired. */ @PermitAll - public Share getShareBySecretId(String secretId) { - return new ShareConverter(true).convert(getShareEntityBySecretId(secretId)); + public ShareInfo getShareInfo(String token, long currentTime) throws EntityNotFoundException { + return new ShareInfoConverter(true).convert(findShare(token, currentTime)); } - - /** - * Get share by id - * - * @param id The id of the share - * @return The share or null if there is no share for the provided id - */ - @PermitAll - public ShareEntity getShareById(long id) { - return ShareEntity.findById(em, id); - } - + /** * Returns a share page ordered by their inverse id. * @@ -125,45 +160,18 @@ public class ShareSessionBean extends AbstractSessionBean { * @return The page of shares. */ @RolesAllowed({Roles.ADMIN}) - public SharePage getAll(PageConfig pageConfig, boolean filtered) { + public SharePage getAllShares(PageConfig pageConfig, boolean filtered) { return getAll(ShareEntity.class, pageConfig, new OrderCriterion("id", true), filtered, new SharePage(), new ShareConverter(filtered)); } - @RolesAllowed({Roles.USER}) - public SharePage getAllForUser(PageConfig pageConfig, boolean filtered) { - UserEntity user = userSessionBean.getCurrentUserEntity(); - if (user == null) throw new ForbiddenException(); - List shareEntityList = ShareEntity.getAllForUser(em, user.getId(), pageConfig, filtered); - SharePage page = new SharePage(); - page.setElements(new ShareConverter(filtered).convert(shareEntityList)); - page.setOffset(pageConfig.getOffset()); - page.setSize(pageConfig.getSize()); - //TODO: think about using long as type for the total count in the page class - page.setTotal(Math.toIntExact(ShareEntity.getAllForUserCount(em, user.getId(), filtered))); - return page; - } - /** * Returns the time stamp of the last modification to the set of shares. * * @return The time stamp of the last share modification. */ @PermitAll - public long getLastModified() { + public long getLastModifiedShare() { return AbstractEntity.getLastModified(em, ShareEntity.class); } - /** - * Returns the last known location for a share - * - * @param secretId The secret id that identifies a share - * @return The location - * @throws NotFoundException if there is no share for the location - */ - @PermitAll - public Location getLastLocation(String secretId) { - ShareEntity shareEntity = getShareEntityBySecretId(secretId); - if (shareEntity == null) throw new NotFoundException(); - return new LocationConverter(true).convert(LocationEntity.findLastLocation(em, shareEntity.getDevice().getId())); - } } diff --git a/service/ejb/src/main/java/com/maptology/service/session/StartupBean.java b/service/ejb/src/main/java/com/maptology/service/session/StartupBean.java new file mode 100644 index 0000000..7c7cc69 --- /dev/null +++ b/service/ejb/src/main/java/com/maptology/service/session/StartupBean.java @@ -0,0 +1,31 @@ +package com.maptology.service.session; + +import javax.annotation.PostConstruct; +import javax.ejb.DependsOn; +import javax.ejb.Singleton; +import javax.ejb.Startup; +import javax.inject.Inject; + +/** + * The bean that initializes the database + * using a configurable data session bean. + * This allows us to use a different data + * initializer for testing and for the + * final deployment. + * + * @author Marcus + */ +@Startup +@Singleton +@DependsOn({"LogSessionBean"}) +public class StartupBean { + + @Inject + protected IDataSessionBean dataSession; + + @PostConstruct + public void onConstruct() { + dataSession.init(); + } + +} diff --git a/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java b/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java index d6cf277..2d57994 100644 --- a/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java +++ b/service/ejb/src/main/java/com/maptology/service/session/UserSessionBean.java @@ -1,6 +1,5 @@ package com.maptology.service.session; -import java.security.Principal; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -8,11 +7,9 @@ import java.util.Map; import java.util.Set; import java.util.logging.Level; -import javax.annotation.Resource; import javax.annotation.security.DeclareRoles; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; -import javax.ejb.SessionContext; import javax.ejb.Stateful; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; @@ -26,6 +23,7 @@ import com.maptology.api.user.UserRegistration; import com.maptology.service.conversion.UserConverter; import com.maptology.service.crypto.SecureHash; import com.maptology.service.crypto.SecureToken; +import com.maptology.service.crypto.TokenType; import com.maptology.service.entity.AbstractEntity; import com.maptology.service.entity.EntityConflictException; import com.maptology.service.entity.EntityForbiddenException; @@ -49,7 +47,7 @@ import com.maptology.service.template.EmailTemplate; @Stateful @RequestScoped @DeclareRoles({ Roles.ADMIN, Roles.USER }) -public class UserSessionBean extends AbstractSessionBean { +public class UserSessionBean extends AbstractPrincipalSessionBean { /** * The maximum attempts to create a secure random token. This @@ -57,13 +55,6 @@ public class UserSessionBean extends AbstractSessionBean { * wrong with the secure token implementation. */ private static final int MAXIMUM_ATTEMPTS = 5; - - /** - * The context to lookup prinicpals and roles - * of a caller. - */ - @Resource - private SessionContext sessionContext; /** * The bean to send out emails. @@ -83,7 +74,7 @@ public class UserSessionBean extends AbstractSessionBean { */ @PermitAll public User loginUser(String login, String password) { - UserEntity user = UserEntity.findByLogin(em, login); + UserEntity user = findUser(login); if (user == null || user.isDeleted() || user.isSuspended()) return null; boolean verified = false; for (EmailEntity email: user.getEmails()) { @@ -102,6 +93,16 @@ public class UserSessionBean extends AbstractSessionBean { } } + /** + * Finds a particular user by its login name. + * + * @param login The login. + * @return The user entity or null. + */ + @PermitAll + public UserEntity findUser(String login) { + return UserEntity.findByLogin(em, login); + } /** * Returns the account of the user that is currently logged in. @@ -112,27 +113,11 @@ public class UserSessionBean extends AbstractSessionBean { */ @RolesAllowed({ Roles.USER }) public User getCurrentUser() throws EntityForbiddenException, EntityNotFoundException { - Principal p = sessionContext.getCallerPrincipal(); - if (p == null) throw new EntityForbiddenException(UserEntity.class, null, "Cannot access current user for unauthorized user."); - String login = p.getName(); - UserEntity u = findUserEntity(login); + UserEntity u = getPrincipalUser(); if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Cannot access current user."); if (u.isDeleted() || u.isSuspended()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Cannot access suspended or deleted user."); return new UserConverter(true).convert(u); } - - - /** - * Returns the current user entity. Returns null, when there is no authenticated user. - * - * @return The user or null, if no user is logged in. - */ - @PermitAll - public UserEntity getCurrentUserEntity() { - Principal p = sessionContext.getCallerPrincipal(); - if (p== null) return null; - return findUserEntity(p.getName()); - } /** * Modifies the current user. @@ -145,9 +130,7 @@ public class UserSessionBean extends AbstractSessionBean { */ @RolesAllowed({ Roles.USER }) public User setCurrentUser(User user, long expirationTime) throws EntityConflictException, EntityForbiddenException, EntityNotFoundException { - Principal p = sessionContext.getCallerPrincipal(); - if (p == null) throw new EntityForbiddenException(UserEntity.class, null, "User modification rejected for unauthorized user."); - UserEntity u = UserEntity.findByLogin(em, p.getName()); + UserEntity u = getPrincipalUser(); if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "User modification rejected for non-existing account."); if (u.isSuspended() || u.isDeleted()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "User modification rejected for suspended or deleted user."); if (u.getId() != user.getId() || user.getModificationTime() != u.getModificationTime()) throw new EntityConflictException(UserEntity.class, u.getId(), "Parallel user modification detected."); @@ -170,27 +153,14 @@ public class UserSessionBean extends AbstractSessionBean { */ @RolesAllowed({ Roles.USER }) public User setCurrentPassword(String password) throws EntityForbiddenException, EntityNotFoundException { - Principal p = sessionContext.getCallerPrincipal(); - if (p == null) throw new EntityForbiddenException(UserEntity.class, null, "Password modification rejected for unauthorized user."); - UserEntity u = UserEntity.findByLogin(em, p.getName()); + UserEntity u = getPrincipalUser(); if (u == null) throw new EntityNotFoundException(UserEntity.class, null, "Password modification rejected for non-existing account."); if (u.isSuspended() || u.isDeleted()) throw new EntityForbiddenException(UserEntity.class, u.getId(), "Password modification rejected for suspended or deleted user."); setPassword(u, password); em.flush(); return new UserConverter(true).convert(u); } - - /** - * Returns the user entity by login. - * - * @param login The login. - * @return The user or null, if the user does not exist. - */ - @PermitAll - public UserEntity findUserEntity(String login) { - return UserEntity.findByLogin(em, login); - } - + /** * Returns the time stamp of the last modification to the set of users. * @@ -211,6 +181,28 @@ public class UserSessionBean extends AbstractSessionBean { public UserPage getAllUsers(PageConfig config, boolean filtered) { return getAll(UserEntity.class, config, new OrderCriterion("id"), filtered, new UserPage(), new UserConverter(filtered)); } + + /** + * Finds a page of users by a search term. + * + * @param config The page configuration. + * @param term The term. + * @param filtered The filtered flag. + * @return The page of users. + */ + @RolesAllowed({Roles.ADMIN }) + public UserPage searchUsers(PageConfig config, String term, boolean filtered) { + long count = UserEntity.countByTerm(em, term, filtered); + UserPage page = new UserPage(); + page.setOffset(config.getOffset()); + page.setSize(config.getSize()); + page.setTotal((int)count); + if (count > config.getOffset()) { + UserConverter c = new UserConverter(filtered); + page.getElements().addAll(c.convert(UserEntity.findByTerm(em, term, config, filtered))); + } + return page; + } /** @@ -261,14 +253,14 @@ public class UserSessionBean extends AbstractSessionBean { */ @RolesAllowed({ Roles.ADMIN }) public User addUser(User user, long expirationTime) throws EntityConflictException { - UserEntity existing = findUserEntity(user.getLogin()); + UserEntity existing = UserEntity.findByLogin(em, user.getLogin()); if (existing != null) throw new EntityConflictException(UserEntity.class, existing.getId(), "Added user with login '" + user.getLogin() + "' already exists."); UserEntity u = new UserEntity(); // set the users identity and name u.setLogin(user.getLogin()); u.setName(user.getName()); - // set the user password to some random string - setPassword(u, SecureToken.createToken()); + // set the user password to some long random string + setPassword(u, SecureToken.createToken(TokenType.INTERNAL)); u.setSuspended(user.isSuspended()); // ignore the deleted flag here setRoles(u, user.getRoles()); @@ -395,6 +387,7 @@ public class UserSessionBean extends AbstractSessionBean { if (e == null && email.isDeleted()) continue; if (e == null) { e = addEmail(user, email.getAddress(), email.isCorrespondence()); + em.persist(e); // need to persist before creating code (!) if (email.isVerified()) { e.setVerified(true); } else { @@ -403,7 +396,6 @@ public class UserSessionBean extends AbstractSessionBean { EmailMessage msg = EmailTemplate.NEW_EMAIL.getMessage(new EmailAssignment(c.getValue(), user.getName())); emailSession.sendEmail(email.getAddress(), msg.getSubject(), msg.getBody()); } - em.persist(e); } else { // update the existing state e.setCorrespondence(email.isCorrespondence()); @@ -594,12 +586,12 @@ public class UserSessionBean extends AbstractSessionBean { * cannot be created. */ protected CodeEntity createCode(CodeType type, EmailEntity email, long expirationTime) { - String token = SecureToken.createToken(); + String token = SecureToken.createToken(TokenType.EXTERNAL); int attempts = 0; while (CodeEntity.findByValue(em, token) != null) { attempts += 1; if (attempts < MAXIMUM_ATTEMPTS) { - token = SecureToken.createToken(); + token = SecureToken.createToken(TokenType.EXTERNAL); } else { // prevent endless loops if something is terribly wrong throw new RuntimeException("Failed to generate a unique token after " + attempts + " tries."); diff --git a/service/ejb/src/test/java/com/maptology/service/test/login/LoginModule.java b/service/ejb/src/test/java/com/maptology/service/test/login/LoginModule.java new file mode 100644 index 0000000..9bfd766 --- /dev/null +++ b/service/ejb/src/test/java/com/maptology/service/test/login/LoginModule.java @@ -0,0 +1,171 @@ +package com.maptology.service.test.login; + +import java.security.Principal; +import java.security.acl.Group; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.persistence.EntityManager; +import javax.security.auth.login.LoginException; + +import org.jboss.security.SecurityContextAssociation; +import org.jboss.security.SimpleGroup; +import org.jboss.security.auth.spi.UsernamePasswordLoginModule; + +import com.maptology.api.access.Roles; +import com.maptology.service.entity.device.DeviceEntity; +import com.maptology.service.entity.user.RoleEntity; +import com.maptology.service.entity.user.UserEntity; +import com.maptology.service.principal.MaptologyPrincipal; + +/** + * A simple login module that is used for testing. It assigns the + * password "password" for all users, so this can be used consistently. + * In addition, it allows encoding users and devices into a single + * login name by combining the username with the device secret in + * the following form: (login):(device). + * + * @author Marcus + */ +public class LoginModule extends UsernamePasswordLoginModule { + + /** + * The roles that we will assign to the user. + */ + private List roles = new ArrayList<>(); + + /** + * The logger. + */ + private Logger log = Logger.getLogger(getClass().getName()); + + @Override + public boolean login() throws LoginException { + if (super.login()) { + Principal p = getIdentity(); + if (p instanceof MaptologyPrincipal) { + MaptologyPrincipal mp = (MaptologyPrincipal)p; + // abort the login if device and user are not set (!) + return mp.getUser() != null || mp.getUser() != null; + } + } + return false; + } + + @Override + public boolean logout() throws LoginException { + boolean result = super.logout(); + for (Group g: getRoleSets()) { + subject.getPrincipals().remove(g); + } + // this is probably hacky: clear the security context + SecurityContextAssociation.clearSecurityContext(); + return result; + } + + + + @Override + protected Principal createIdentity(String username) throws Exception { + String[] loginDevice = getLoginDevice(username); + Long user = null; + Long device = null; + String name1 = ""; + String name2 = ""; + // this will be running inside the application's current + // transaction which could potentially be problematic + EntityManager em = getEntityManager(); + UserEntity ue = UserEntity.findByLogin(em, loginDevice[0]); + if (ue != null) { + user = ue.getId(); + name1 = ue.getLogin(); + for (RoleEntity re : ue.getRoles()) { + roles.add(re.getName()); + } + } + DeviceEntity de = DeviceEntity.findByToken(em, loginDevice[1]); + if (de != null) { + name2 = de.getToken(); + device = de.getId(); + roles.add(Roles.DEVICE); + } + return new MaptologyPrincipal(name1 + ":" + name2, user, device); + } + + /** + * Parses the login name and the device token from the + * username string provided to the auth module. + * + * @param username The username (consisting of login:token). + * @return An array with the login and the token. + */ + private String[] getLoginDevice(String username) { + String[] loginAndDevice = new String[] { "", "" }; + if (username != null) { + int idx = username.indexOf(':'); + if (idx != -1) { + loginAndDevice[0] = username.substring(0, idx); + loginAndDevice[1] = username.substring(idx + 1, username.length()); + } else { + loginAndDevice[0] = username; + } + } + return loginAndDevice; + } + + + + @Override + public boolean commit() throws LoginException { + System.out.println("Login ok is: " + loginOk); + if (loginOk) { + subject.getPrincipals().clear(); + } + return super.commit(); + } + + @Override + protected Group[] getRoleSets() throws LoginException { + SimpleGroup group = new SimpleGroup("Roles"); + for (final String r: roles) { + group.addMember(new Principal() { + @Override + public String getName() { + return r; + } + @Override + public String toString() { + return r; + } + }); + } + return new Group[] { group }; + } + + @Override + protected String getUsersPassword() throws LoginException { + return "password"; + } + + /** + * Returns the entity manager for the maptology datastore. + * + * @return The entity manager or null, if the entity manager cannot be found. + */ + private EntityManager getEntityManager() { + try { + Context context = new InitialContext(); + return (EntityManager)context.lookup("java:app/maptology/datastore"); + } catch (NamingException e) { + log.log(Level.SEVERE, "Failed to resolve entity manager.", e); + return null; + } + } + + +} diff --git a/service/ejb/src/test/java/com/maptology/service/test/login/package-info.java b/service/ejb/src/test/java/com/maptology/service/test/login/package-info.java new file mode 100644 index 0000000..c47adcd --- /dev/null +++ b/service/ejb/src/test/java/com/maptology/service/test/login/package-info.java @@ -0,0 +1,7 @@ +/** + * This package contains a login module that enables + * testing of ejbs. + * + * @author Marcus + */ +package com.maptology.service.test.login; \ No newline at end of file diff --git a/service/ejb/src/test/java/com/maptology/service/test/session/AbstractSessionTest.java b/service/ejb/src/test/java/com/maptology/service/test/session/AbstractSessionTest.java index 52f7578..e9a59fd 100644 --- a/service/ejb/src/test/java/com/maptology/service/test/session/AbstractSessionTest.java +++ b/service/ejb/src/test/java/com/maptology/service/test/session/AbstractSessionTest.java @@ -90,25 +90,40 @@ public abstract class AbstractSessionTest { * @param user The user's login. */ public void executeAs(String user, Runnable r) { - + executeAs(user, null, r); + } + + /** + * Tries to login into the system using the specified user + * and device secret. Either one of which can be null. + * + * @param user The user login (which may be null, if device is set). + * @param device The device token (which may be null, if user is set). + * @param r The runnable to execute + */ + public void executeAs(String user, String device, Runnable r) { try { + user = (user==null)?"":user; + device = (device==null)?"":device; + String login = user + ":" + device; + log.log(Level.INFO, "Creating login context."); - LoginContext ctx = new LoginContext(SECURITY_DOMAIN, new UsernamePasswordHandler(user, "password".toCharArray())); + LoginContext ctx = new LoginContext(SECURITY_DOMAIN, new UsernamePasswordHandler(login, "password".toCharArray())); try { - log.log(Level.INFO, "Login as '" + user + "'."); + log.log(Level.INFO, "Login as '" + login + "'."); ctx.login(); log.log(Level.INFO, "Subject is:\n" + ctx.getSubject().toString()); log.log(Level.INFO, "Executing test."); r.run(); } finally { - log.log(Level.INFO, "Logout as '" + user + "'."); + log.log(Level.INFO, "Logout as '" + login + "'."); ctx.logout(); } } catch (LoginException e) { - Assert.assertEquals("Login exception during login for '" + user + "'.", null, e); + Assert.assertEquals("Login exception during login for '" + user + ":" + device + "'.", null, e); } catch (RuntimeException e) { - Assert.assertEquals("Runtime exception during test with '" + user + "'.", null, e); - } + Assert.assertEquals("Runtime exception during test with '" + user + ":" + device + "'.", null, e); + } } diff --git a/service/ejb/src/test/java/com/maptology/service/test/session/DeviceSessionTest.java b/service/ejb/src/test/java/com/maptology/service/test/session/DeviceSessionTest.java index 16b6b68..99de905 100644 --- a/service/ejb/src/test/java/com/maptology/service/test/session/DeviceSessionTest.java +++ b/service/ejb/src/test/java/com/maptology/service/test/session/DeviceSessionTest.java @@ -1,16 +1,22 @@ package com.maptology.service.test.session; -import com.maptology.api.PageConfig; -import com.maptology.api.device.Device; -import com.maptology.api.device.DevicePage; -import com.maptology.service.session.DeviceSessionBean; +import javax.inject.Inject; + import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -import javax.ejb.EJBAccessException; -import javax.inject.Inject; +import com.maptology.api.PageConfig; +import com.maptology.api.device.Device; +import com.maptology.api.device.DeviceHandle; +import com.maptology.api.device.DeviceInfo; +import com.maptology.api.device.DevicePage; +import com.maptology.api.device.OperatingSystem; +import com.maptology.api.user.User; +import com.maptology.service.entity.EntityForbiddenException; +import com.maptology.service.session.DeviceSessionBean; +import com.maptology.service.session.UserSessionBean; /** * Tests the device session bean @@ -23,75 +29,188 @@ public class DeviceSessionTest extends AbstractSessionTest { @Inject DeviceSessionBean deviceSession; + @Inject + UserSessionBean userSession; + + /** - * Tests, whether a user with role admin can create a device. + * Retrieves the number of devices in the database by loging in + * as admin. This method should not be called while a user is + * logged in. + * + * @return The number of devices. + */ + private int getDeviceCountAsAdmin() { + int[] result = new int[1]; + executeAs("admin", new Runnable() { + @Override + public void run() { + DevicePage page = deviceSession.getAllDevices(new PageConfig(), false); + result[0] = page.getTotal(); + } + }); + return result[0]; + } + + /** + * Tests the addition of a new device with */ @Test - public void testAddDeviceAsAdmin() { - executeAs("admin", new Runnable() { + public void testAddDeviceWithoutUser() { + int initialDevices = getDeviceCountAsAdmin(); + DeviceInfo info = new DeviceInfo(); + info.setDevice("device"); + info.setManufacturer("manufacturer"); + info.setModel("model"); + info.setOs(OperatingSystem.ANDROID); + final DeviceHandle handle = deviceSession.addDevice(info); + Assert.assertEquals("Device should be set.", info.getDevice(), handle.getDevice()); + Assert.assertEquals("Manufacturer should be set.", info.getManufacturer(), handle.getManufacturer()); + Assert.assertEquals("Model should be set.", info.getModel(), handle.getModel()); + Assert.assertEquals("OS should be set.", info.getOs(), handle.getOs()); + Assert.assertNotNull("Token should be set.", handle.getToken()); + Assert.assertNull("User should be null.", handle.getUser()); + executeAs(null, handle.getToken(), new Runnable() { @Override public void run() { - Device device = deviceSession.addDevice(new Device()); - Assert.assertNotNull("Returned device should not be null.", device); - Assert.assertTrue("Id should be set.", device.getId() > 0); - Assert.assertNotNull("AuthToken should be set.", device.getAuthToken()); + try { + Device device = deviceSession.getCurrentDevice(); + Assert.assertEquals("Should have same id.", handle.getId(), device.getId()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } }); + Assert.assertEquals("Should have one more device.", initialDevices + 1, getDeviceCountAsAdmin()); } /** - * Tests, whether a client without user authentication can create a device. + * Tests the addition of new devices. */ @Test - public void testAddDeviceAsAnonymous() { - Device device = deviceSession.addDevice(new Device()); - Assert.assertNotNull("Returned device should not be null.", device); - Assert.assertTrue("Id should be set.", device.getId() > 0); - Assert.assertNotNull("AuthToken should be set.", device.getAuthToken()); - } - - /** - * Tests, whether a user with role user can create a device. - */ - @Test - public void testAddDeviceAsUser() { - executeAs("handte", new Runnable() { + public void testAddDeviceWithUser() { + int initialDevices = getDeviceCountAsAdmin(); + final DeviceInfo info = new DeviceInfo(); + info.setDevice("device"); + info.setManufacturer("manufacturer"); + info.setModel("model"); + info.setOs(OperatingSystem.ANDROID); + final DeviceHandle[] handle = new DeviceHandle[1]; + executeAs("handte", new Runnable() { + @Override + public void run() { + try { + User user = userSession.getCurrentUser(); + handle[0] = deviceSession.addDevice(info); + Assert.assertEquals("Device should be set.", info.getDevice(), handle[0].getDevice()); + Assert.assertEquals("Manufacturer should be set.", info.getManufacturer(), handle[0].getManufacturer()); + Assert.assertEquals("Model should be set.", info.getModel(), handle[0].getModel()); + Assert.assertEquals("OS should be set.", info.getOs(), handle[0].getOs()); + Assert.assertNotNull("Token should be set.", handle[0].getToken()); + Assert.assertEquals("User should be handte.", user.getId(), handle[0].getUser().longValue()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } + }); + executeAs(null, handle[0].getToken(), new Runnable() { @Override public void run() { - Device device = deviceSession.addDevice(new Device()); - Assert.assertNotNull("Returned device should not be null.", device); - Assert.assertTrue("Id should be set.", device.getId() > 0); - Assert.assertNotNull("AuthToken should be set.", device.getAuthToken()); + try { + Device device = deviceSession.getCurrentDevice(); + Assert.assertEquals("Should have same id.", handle[0].getId(), device.getId()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } }); + Assert.assertEquals("Should have one more device.", initialDevices + 1, getDeviceCountAsAdmin()); } - + @Test - public void testGetAllAsUser() { - executeAs("handte", new Runnable() { - @Override - public void run() { - try { - deviceSession.getAll(new PageConfig(0, 10), false); - } catch (EJBAccessException e) { - return; - } - Assert.fail("Should not be accessible to users."); - } - }); + public void testGetOwnDeviceAndOther() { + final DeviceInfo info = new DeviceInfo(); + info.setDevice("device"); + info.setManufacturer("manufacturer"); + info.setModel("model"); + info.setOs(OperatingSystem.ANDROID); + final DeviceHandle handleOther = deviceSession.addDevice(info); + executeAs("handte", new Runnable() { + @Override + public void run() { + // create device and access (should succeed) + try { + final DeviceHandle handleMine = deviceSession.addDevice(info); + Device device = deviceSession.getDevice(handleMine.getId()); + Assert.assertNotNull("Should not be null.", device); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + // create other user's device (should fail) + try { + deviceSession.getDevice(handleOther.getId()); + Assert.fail("Should throw forbidden."); + } catch (EntityForbiddenException e) { + Assert.assertNotNull("Should have exception.", e); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } + }); + executeAs("admin", new Runnable() { + @Override + public void run() { + // admin should be able to access other user's device + try { + Device device = deviceSession.getDevice(handleOther.getId()); + Assert.assertNotNull("Should not be null.", device); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } + }); } - + @Test - public void testGetAllAsAdmin() { - executeAs("admin", new Runnable() { - @Override - public void run() { - try { - deviceSession.getAll(new PageConfig(0, 10), false); - } catch (EJBAccessException e) { - Assert.fail("Should be accessible to admins."); - } - } - }); + public void testCreateAndDeleteDevice() { + final DeviceHandle[] handleMine = new DeviceHandle[1]; + final int[] devices = new int[1]; + executeAs("handte", new Runnable() { + @Override + public void run() { + final DeviceInfo info = new DeviceInfo(); + info.setDevice("device"); + info.setManufacturer("manufacturer"); + info.setModel("model"); + info.setOs(OperatingSystem.ANDROID); + // create device + try { + devices[0] = deviceSession.getAllDevicesForCurrentUser(new PageConfig(), true).getTotal(); + handleMine[0] = deviceSession.addDevice(info); + Device device = deviceSession.getDevice(handleMine[0].getId()); + Assert.assertNotNull("Should not be null.", device); + Assert.assertEquals("Should have a new device in page.", devices[0] + 1, deviceSession.getAllDevicesForCurrentUser(new PageConfig(), true).getTotal()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } + }); + executeAs("handte", handleMine[0].getToken(), new Runnable() { + @Override + public void run() { + try { + deviceSession.deleteCurrentDevice(); + Assert.assertEquals("Deleted device should be gone from page.", devices[0], deviceSession.getAllDevicesForCurrentUser(new PageConfig(), true).getTotal()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + + } + }); } + + + } diff --git a/service/ejb/src/test/java/com/maptology/service/test/session/ShareSessionTest.java b/service/ejb/src/test/java/com/maptology/service/test/session/ShareSessionTest.java index 5c7b465..539d9ab 100644 --- a/service/ejb/src/test/java/com/maptology/service/test/session/ShareSessionTest.java +++ b/service/ejb/src/test/java/com/maptology/service/test/session/ShareSessionTest.java @@ -1,10 +1,28 @@ package com.maptology.service.test.session; +import com.maptology.api.device.DeviceHandle; +import com.maptology.api.device.DeviceInfo; +import com.maptology.api.device.OperatingSystem; +import com.maptology.api.location.Availability; +import com.maptology.api.location.Coordinate; +import com.maptology.api.location.Location; +import com.maptology.api.location.LocationUpdate; +import com.maptology.api.location.ReleasedLocation; +import com.maptology.api.share.Share; +import com.maptology.api.share.ShareInfo; +import com.maptology.api.user.User; +import com.maptology.service.session.DeviceSessionBean; +import com.maptology.service.session.LocationSessionBean; import com.maptology.service.session.ShareSessionBean; +import com.maptology.service.session.UserSessionBean; + import org.jboss.arquillian.junit.Arquillian; +import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; +import java.util.ArrayList; + import javax.inject.Inject; /** @@ -16,9 +34,108 @@ public class ShareSessionTest extends AbstractSessionTest { @Inject private ShareSessionBean shareSession; - //TODO implement test cases + @Inject + private DeviceSessionBean deviceSession; + + @Inject + private UserSessionBean userSession; + + @Inject + private LocationSessionBean locationSession; + @Test - public void mockTest() { + public void testShareLocation() { + // create a new device for handte + final DeviceHandle[] handle = new DeviceHandle[1]; + executeAs("handte", new Runnable() { + @Override + public void run() { + try { + DeviceInfo info = new DeviceInfo(); + info.setDevice("device"); + info.setManufacturer("manufacturer"); + info.setModel("model"); + info.setOs(OperatingSystem.ANDROID); + User user = userSession.getCurrentUser(); + handle[0] = deviceSession.addDevice(info); + Assert.assertEquals("Device should be set.", info.getDevice(), handle[0].getDevice()); + Assert.assertEquals("Manufacturer should be set.", info.getManufacturer(), handle[0].getManufacturer()); + Assert.assertEquals("Model should be set.", info.getModel(), handle[0].getModel()); + Assert.assertEquals("OS should be set.", info.getOs(), handle[0].getOs()); + Assert.assertNotNull("Token should be set.", handle[0].getToken()); + Assert.assertEquals("User should be handte.", user.getId(), handle[0].getUser().longValue()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } + }); + // create a new share + Share[] share = new Share[1]; + executeAs(null, handle[0].getToken(), new Runnable() { + @Override + public void run() { + try { + long now = System.currentTimeMillis(); + long expire = now + 1000000; + ShareInfo info = new ShareInfo(); + info.setDestination("destination"); + info.setExpirationTime(expire); + info.setMessage("message"); + share[0] = shareSession.createShare(info); + Assert.assertEquals("Destination should match.", info.getDestination(), share[0].getDestination()); + Assert.assertEquals("Message should match.", info.getMessage(), share[0].getMessage()); + Assert.assertEquals("Expiration should match.", info.getExpirationTime(), share[0].getExpirationTime()); + Assert.assertNotNull("Token should be set.", share[0].getToken()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } + }); + // perform a location update + executeAs("handte", handle[0].getToken(), new Runnable() { + @Override + public void run() { + try { + long time = System.currentTimeMillis(); + LocationUpdate update = new LocationUpdate(); + update.setLocations(new ArrayList<>()); + ReleasedLocation location = new ReleasedLocation(); + location.setProvider("me"); + location.setAvailability(Availability.FRESH); + location.setAnalyzable(true); + location.setTimestamp(time); + location.setVersion(0); + location.setCoordinate(new Coordinate(5, 6)); + update.getLocations().add(location); + locationSession.addLocations(update); + Location lastLocation = locationSession.getDeviceLocation(handle[0].getId()); + Assert.assertEquals("Longitude should be set.", location.getCoordinate().getLongitude(), lastLocation.getCoordinate().getLongitude(), 0.001); + Assert.assertEquals("Latitude should be set.", location.getCoordinate().getLatitude(), lastLocation.getCoordinate().getLatitude(), 0.001); + Assert.assertEquals("Availability should be set.", location.getAvailability(), lastLocation.getAvailability()); + Assert.assertEquals("Timestamp should be set.", location.getTimestamp(), lastLocation.getTimestamp()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + } + }); + // get the share info with the token + try { + ShareInfo info = shareSession.getShareInfo(share[0].getToken(), share[0].getCreationTime()); + Assert.assertEquals("Destination should match.", share[0].getDestination(), info.getDestination()); + Assert.assertEquals("Message should match.", share[0].getMessage(), info.getMessage()); + Assert.assertEquals("Expiration should match.", share[0].getExpirationTime(), info.getExpirationTime()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } + // get the location with the token + try { + Location location = locationSession.getShareLocation(share[0].getToken(), share[0].getCreationTime()); + Assert.assertEquals("Longitude should be set.", 5, location.getCoordinate().getLongitude(), 0.001); + Assert.assertEquals("Latitude should be set.", 6, location.getCoordinate().getLatitude(), 0.001); + Assert.assertEquals("Availability should be set.", Availability.FRESH, location.getAvailability()); + } catch (Exception e) { + Assert.assertNull("Should not receive an exception.", e); + } } } diff --git a/service/ejb/src/test/java/com/maptology/service/test/session/UserSessionTest.java b/service/ejb/src/test/java/com/maptology/service/test/session/UserSessionTest.java index 2bdd723..a84864a 100644 --- a/service/ejb/src/test/java/com/maptology/service/test/session/UserSessionTest.java +++ b/service/ejb/src/test/java/com/maptology/service/test/session/UserSessionTest.java @@ -64,6 +64,21 @@ public class UserSessionTest extends AbstractSessionTest { }); } + @Test + public void testFindByTerm() { + executeAs("admin", new Runnable() { + + @Override + public void run() { + UserPage page1 = userSession.searchUsers(new PageConfig(0, 10), "dmi", false); + Assert.assertTrue("Should have at least one result.", page1.getElements().size() > 0); + Assert.assertTrue("Should have at least one result.", page1.getTotal() > 0); + + } + }); + } + + /** * Tests that it is not possible to register two users with the same login. */ @@ -320,7 +335,7 @@ public class UserSessionTest extends AbstractSessionTest { user.setLogin("adduser"); User created = userSession.addUser(user, expiration); Assert.assertNull("User without correspondence email should not be added.", created); - Assert.assertNull("Database should not contain non-added user.", userSession.findUserEntity("adduser")); + Assert.assertNull("Database should not contain non-added user.", userSession.findUser("adduser")); Assert.assertEquals("Invalid addition should not result in email.", emails, emailSession.getEntries().size()); user.getEmails().get(0).setCorrespondence(true); user.getEmails().add(new Email("marcus.handte@gmail.com")); @@ -342,7 +357,7 @@ public class UserSessionTest extends AbstractSessionTest { user.getEmails().get(1).setAddress("marcus@handte.org"); User created = userSession.addUser(user, expiration); Assert.assertNull("User duplicate email should not be added.", created); - Assert.assertNull("Database should not contain non-added user.", userSession.findUserEntity("adduser2")); + Assert.assertNull("Database should not contain non-added user.", userSession.findUser("adduser2")); Assert.assertEquals("Invalid addition should not result in email.", emails, emailSession.getEntries().size()); } catch (Exception e) { Assert.assertNull("Should not raise exception.", e); diff --git a/service/ejb/src/test/resources/META-INF/beans.xml b/service/ejb/src/test/resources/META-INF/beans.xml index 41c9698..844a472 100644 --- a/service/ejb/src/test/resources/META-INF/beans.xml +++ b/service/ejb/src/test/resources/META-INF/beans.xml @@ -6,6 +6,7 @@ http://jboss.org/schema/weld/beans http://jboss.org/schema/weld/beans_1_1.xsd"> + com.maptology.service.session.DebugDataSessionBean com.maptology.service.session.DebugEmailSessionBean diff --git a/service/ejb/src/test/resources/wildfly.xml b/service/ejb/src/test/resources/wildfly.xml index 9960c31..ccdc8e8 100644 --- a/service/ejb/src/test/resources/wildfly.xml +++ b/service/ejb/src/test/resources/wildfly.xml @@ -331,15 +331,18 @@ + + + + diff --git a/service/swarm/src/main/java/com/maptology/service/app/MaptologySwarmApplication.java b/service/swarm/src/main/java/com/maptology/service/app/MaptologySwarmApplication.java index 0530f11..2eeab98 100644 --- a/service/swarm/src/main/java/com/maptology/service/app/MaptologySwarmApplication.java +++ b/service/swarm/src/main/java/com/maptology/service/app/MaptologySwarmApplication.java @@ -10,7 +10,9 @@ import io.swagger.jaxrs.config.BeanConfig; import io.swagger.jaxrs.config.SwaggerContextService; import io.swagger.jaxrs.listing.SwaggerSerializers; import io.swagger.models.Swagger; +import io.swagger.models.auth.ApiKeyAuthDefinition; import io.swagger.models.auth.BasicAuthDefinition; +import io.swagger.models.auth.In; /** * An extended version of the maptology application @@ -28,6 +30,7 @@ public class MaptologySwarmApplication extends MaptologyApplication { */ public MaptologySwarmApplication() { BeanConfig beanConfig = new BeanConfig(); + beanConfig.setTitle("Maptology Api"); beanConfig.setVersion("in-memory"); beanConfig.setSchemes(new String[] { "http" }); beanConfig.setHost("localhost:8090"); @@ -41,6 +44,8 @@ public class MaptologySwarmApplication extends MaptologyApplication { admin.setDescription("Operations requiring admin privileges."); swagger.securityDefinition("user", user); swagger.securityDefinition("admin", admin); + ApiKeyAuthDefinition device = new ApiKeyAuthDefinition("Authorization", In.HEADER); + swagger.securityDefinition("device", device); beanConfig.configure(swagger); new SwaggerContextService().updateSwagger(swagger); } diff --git a/service/swarm/src/main/java/com/maptology/service/rest/MaptologySwaggerListing.java b/service/swarm/src/main/java/com/maptology/service/rest/MaptologySwaggerListing.java index c6d9493..ea45e5f 100644 --- a/service/swarm/src/main/java/com/maptology/service/rest/MaptologySwaggerListing.java +++ b/service/swarm/src/main/java/com/maptology/service/rest/MaptologySwaggerListing.java @@ -3,6 +3,7 @@ package com.maptology.service.rest; import java.util.Collections; import java.util.Enumeration; +import javax.annotation.security.PermitAll; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.ws.rs.GET; @@ -76,6 +77,7 @@ public class MaptologySwaggerListing extends BaseApiListingResource { @GET @Produces({ MediaType.APPLICATION_JSON }) @ApiOperation(value = "The swagger definition in json format.", hidden = true) + @PermitAll public Response getListing() throws JsonProcessingException { return getListingJsonResponse(app, context, sc, headers, uriInfo); } diff --git a/service/swarm/src/main/java/com/maptology/service/swarm/MaptologySwarm.java b/service/swarm/src/main/java/com/maptology/service/swarm/MaptologySwarm.java index a9b7405..2bf2f4b 100644 --- a/service/swarm/src/main/java/com/maptology/service/swarm/MaptologySwarm.java +++ b/service/swarm/src/main/java/com/maptology/service/swarm/MaptologySwarm.java @@ -55,7 +55,7 @@ public class MaptologySwarm { deployment.addPackages(true, "org.reflections"); deployment.addPackages(true, "io.swagger"); // add swagger ui from webapp folder - //deployment.merge(ShrinkWrap.create(ExplodedImporter.class).importDirectory("src/main/webapp/").as(GenericArchive.class),"/"); + deployment.merge(ShrinkWrap.create(ExplodedImporter.class).importDirectory("src/main/webapp/").as(GenericArchive.class),"/"); // add manifest deployment.addAsManifestResource(new StringAsset(getManifest()), "MANIFEST.MF"); // add code diff --git a/service/swarm/src/main/resources/beans.xml b/service/swarm/src/main/resources/beans.xml index cf63db8..ff77527 100644 --- a/service/swarm/src/main/resources/beans.xml +++ b/service/swarm/src/main/resources/beans.xml @@ -6,6 +6,7 @@ http://jboss.org/schema/weld/beans http://jboss.org/schema/weld/beans_1_1.xsd"> + com.maptology.service.session.DebugDataSessionBean com.maptology.service.session.DebugEmailSessionBean diff --git a/service/war/src/main/java/com/maptology/service/access/AccessControlFilter.java b/service/war/src/main/java/com/maptology/service/access/AccessControlFilter.java index 0a6baa7..1d73798 100644 --- a/service/war/src/main/java/com/maptology/service/access/AccessControlFilter.java +++ b/service/war/src/main/java/com/maptology/service/access/AccessControlFilter.java @@ -49,6 +49,7 @@ public class AccessControlFilter implements ContainerRequestFilter { log.log(Level.SEVERE, "Method " + m.getName() + " in " + m.getDeclaringClass() + " does not specify any security (use @PermitAll) to allow all callers."); requestContext.abortWith(Response.status(Status.INTERNAL_SERVER_ERROR).build()); } else { + log.log(Level.FINE, "Validating access for " + m.getName() + "."); boolean success; try { if (roles != null) { @@ -65,6 +66,7 @@ public class AccessControlFilter implements ContainerRequestFilter { success = false; } if (! success) { + log.log(Level.INFO, "Aborting call due to security check."); requestContext.abortWith(Response.status(Status.FORBIDDEN).build()); } } @@ -82,10 +84,15 @@ public class AccessControlFilter implements ContainerRequestFilter { public boolean isFulfilled(RolesAllowed roles) { if (roles.value().length == 0) return true; for (String r: roles.value()) { + log.log(Level.FINER, "Testing whether user is in role: " + r); if (request.isUserInRole(r)) { + log.log(Level.FINER, "Success."); return true; + } else { + log.log(Level.FINER, "Failure."); } } + log.log(Level.FINER, "All roles failed."); return false; } diff --git a/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthModule.java b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthModule.java index 535ef57..554006a 100644 --- a/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthModule.java +++ b/service/war/src/main/java/com/maptology/service/auth/MaptologyAuthModule.java @@ -1,15 +1,11 @@ package com.maptology.service.auth; -import com.maptology.api.access.Roles; -import com.maptology.service.auth.basic.BasicAuthCredential; -import com.maptology.service.auth.bearer.BearerAuthCredential; -import com.maptology.service.auth.http.AbstractHttpServletAuthModule; -import com.maptology.service.auth.http.HttpServletMessageInfo; -import com.maptology.service.crypto.SecureHash; -import com.maptology.service.entity.device.DeviceEntity; -import com.maptology.service.entity.user.RoleEntity; -import com.maptology.service.entity.user.UserEntity; -import com.maptology.service.session.MaptologyPrincipal; +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; @@ -26,11 +22,17 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.transaction.UserTransaction; import javax.ws.rs.core.HttpHeaders; -import java.io.IOException; -import java.security.Principal; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; + +import com.maptology.api.access.Roles; +import com.maptology.service.auth.basic.BasicAuthCredential; +import com.maptology.service.auth.bearer.BearerAuthCredential; +import com.maptology.service.auth.http.AbstractHttpServletAuthModule; +import com.maptology.service.auth.http.HttpServletMessageInfo; +import com.maptology.service.crypto.SecureHash; +import com.maptology.service.entity.device.DeviceEntity; +import com.maptology.service.entity.user.RoleEntity; +import com.maptology.service.entity.user.UserEntity; +import com.maptology.service.principal.MaptologyPrincipal; /** * The server authentication module that @@ -47,11 +49,6 @@ public class MaptologyAuthModule extends AbstractHttpServletAuthModule { * The "magic" parameter that enables challenges. */ public static final String PARAMETER_CHALLENGE = "testAuth"; - - /** - * Field in header that contains the token used for device authentication - */ - public static final String DEVICE_AUTHORIZATION_HEADER = "Device-Authorization"; /** @@ -61,111 +58,95 @@ public class MaptologyAuthModule extends AbstractHttpServletAuthModule { @Override protected AuthStatus validateRequest(HttpServletMessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException { + // only perform auth, if it is mandatory + if (! messageInfo.isAuthMandatory()) { + return AuthStatus.SUCCESS; + } + + // extract credentials HttpServletRequest request = messageInfo.getRequest(); - - - boolean success = false; - - List rolesList = new LinkedList<>(); - - Long deviceId = null; - String login = null; - - BearerAuthCredential bearerAuthCredential = BearerAuthCredential.valueOf(request.getHeader(DEVICE_AUTHORIZATION_HEADER)); - - BasicAuthCredential basicAuthCredential = BasicAuthCredential.valueOf(request.getHeader(HttpHeaders.AUTHORIZATION)); - - // then we handle requests without credentials - if (basicAuthCredential == null && bearerAuthCredential == null) { - if (!messageInfo.isAuthMandatory()) { - // no auth needed, so this is ok - return AuthStatus.SUCCESS; - } else if (requiresAuthChallenge(request)) { + BearerAuthCredential deviceCredential = BearerAuthCredential.valueOf(request.getHeader(HttpHeaders.AUTHORIZATION)); + BasicAuthCredential userCredential = BasicAuthCredential.valueOf(request.getHeader(HttpHeaders.AUTHORIZATION)); + + // handle unspecified credentials + if (userCredential == null && deviceCredential == null) { + if (requiresAuthChallenge(request)) { return sendUnauthorized(messageInfo, "Access not allowed."); } else { return sendForbidden(messageInfo, "Access not allowed."); } - } - - - log.log(Level.INFO, "Validating request for '" + (basicAuthCredential == null ? "" : basicAuthCredential.getUsername()) + "' to " + request.getRequestURI()); - Principal principal = request.getUserPrincipal(); - // first we try to resume a session - if (principal != null && (basicAuthCredential == null || principal.getName().equals(basicAuthCredential.getUsername()))) { - log.log(Level.INFO, "Resuming previous session for '" + principal.getName() + "'."); - try { - messageInfo.setRegisterSession(true); - callbackHandler.handle(new Callback[]{new CallerPrincipalCallback(clientSubject, principal)}); - return AuthStatus.SUCCESS; - } catch (Exception ex) { - log.log(Level.WARNING, "Failed to resume sssion for '" + principal.getName() + "'.", ex); - return sendServerError(messageInfo, "Failed to resume session."); - } - } - - - if (bearerAuthCredential != null) { - //try to authenticate an device using a provided token + + // initialize authentication state + boolean success = false; + Set roles = new HashSet<>(); + + // perform device authentication + Long device = null; + String deviceName = null; + if (deviceCredential != null) { log.log(Level.INFO, "Validating device token"); EntityManager em = getEntityManager(); if (em == null) { return sendServerError(messageInfo, "Device database not available."); } - DeviceEntity device = getDevice(em, bearerAuthCredential.getToken()); - if (device == null) { - log.log(Level.INFO, "Device does not exist."); - } else if (device.isDeleted()) { - log.log(Level.INFO, "Device is deleted."); + DeviceEntity entity = getDevice(em, deviceCredential.getToken()); + if (entity == null) { + log.log(Level.INFO, "Device '" + deviceCredential.getToken() +"' does not exist."); + } else if (entity.isDeleted()) { + log.log(Level.INFO, "Device " + entity.getId() + " is deleted."); } else { - deviceId = device.getId(); - rolesList.add(Roles.DEVICE); + device = entity.getId(); + deviceName = entity.getToken(); + roles.add(Roles.DEVICE); success = true; - log.log(Level.INFO, "Successful device authentication"); + log.log(Level.INFO, "Device " + entity.getId() + " authenticated."); } } - - - if (basicAuthCredential != null) { - // now we try to login with credentials + + + // perform user authentication + Long user = null; + String userName = null; + if (userCredential != null) { EntityManager em = getEntityManager(); UserTransaction ta = getUserTransaction(); if (em == null || ta == null) { return sendServerError(messageInfo, "User database not available."); } - UserEntity user = getUser(em, ta, basicAuthCredential.getUsername()); - if (user == null) { - log.log(Level.INFO, "User '" + basicAuthCredential.getUsername() + "' does not exist."); - } else if (user.isDeleted()) { - log.log(Level.INFO, "User '" + basicAuthCredential.getUsername() + "' is deleted."); - } else if (user.isSuspended()) { - log.log(Level.INFO, "User '" + basicAuthCredential.getUsername() + "' is suspended."); + UserEntity entity = getUser(em, ta, userCredential.getUsername()); + if (entity == null) { + log.log(Level.INFO, "User '" + userCredential.getUsername() + "' does not exist."); + } else if (entity.isDeleted()) { + log.log(Level.INFO, "User '" + userCredential.getUsername() + "' is deleted."); + } else if (entity.isSuspended()) { + log.log(Level.INFO, "User '" + userCredential.getUsername() + "' is suspended."); } else { - SecureHash hash = new SecureHash(user.getIterations(), user.getSalt(), user.getHash()); - if (hash.verify(basicAuthCredential.getPassword())) { - String[] roles = new String[user.getRoles().size()]; - Iterator it = user.getRoles().iterator(); - for (int i = 0; i < roles.length; i++) { - roles[i] = it.next().getName(); + SecureHash hash = new SecureHash(entity.getIterations(), entity.getSalt(), entity.getHash()); + if (hash.verify(userCredential.getPassword())) { + for (RoleEntity re: entity.getRoles()) { + roles.add(re.getName()); } - Collections.addAll(rolesList, roles); - login = user.getLogin(); + userName = entity.getLogin(); + user = entity.getId(); success = true; - log.log(Level.INFO, "User login for " + basicAuthCredential.getUsername() + "."); + log.log(Level.INFO, "User '" + userCredential.getUsername() + "' authenticated."); } else { - log.log(Level.INFO, "User '" + basicAuthCredential.getUsername() + "' provided wrong password."); + log.log(Level.INFO, "User '" + userCredential.getUsername() + "' provided wrong password."); } } } - - - if (success || !messageInfo.isAuthMandatory()) { + + // create principal or issue error + if (success) { + String name = (userName==null?"":userName) + ":" + (deviceName==null?"":deviceName); try { + MaptologyPrincipal principal = new MaptologyPrincipal(name, user, device); + log.log(Level.INFO, "Creating principal: " + principal); callbackHandler.handle(new Callback[]{ - new CallerPrincipalCallback(clientSubject, new MaptologyPrincipal(login, deviceId)), - new GroupPrincipalCallback(clientSubject, rolesList.toArray(new String[rolesList.size()])) + new CallerPrincipalCallback(clientSubject, principal), + new GroupPrincipalCallback(clientSubject, roles.toArray(new String[roles.size()])) }); - messageInfo.setRegisterSession(true); } catch (Exception e) { log.log(Level.SEVERE, "Fatal processing error.", e); return sendServerError(messageInfo, "Login failed."); @@ -229,7 +210,7 @@ public class MaptologyAuthModule extends AbstractHttpServletAuthModule { */ private DeviceEntity getDevice(EntityManager em, String authToken) { try { - return DeviceEntity.findByAuthToken(em, authToken); + return DeviceEntity.findByToken(em, authToken); } catch (Exception e) { log.log(Level.WARNING, "Device query failed.", e); } diff --git a/service/war/src/main/java/com/maptology/service/rest/DeviceResource.java b/service/war/src/main/java/com/maptology/service/rest/DeviceResource.java index 5e5287c..441fc0c 100644 --- a/service/war/src/main/java/com/maptology/service/rest/DeviceResource.java +++ b/service/war/src/main/java/com/maptology/service/rest/DeviceResource.java @@ -1,19 +1,28 @@ package com.maptology.service.rest; -import com.maptology.api.PageConfig; -import com.maptology.api.device.Device; -import com.maptology.api.device.IDeviceService; -import com.maptology.api.device.Location; -import com.maptology.service.session.DeviceSessionBean; -import com.maptology.service.session.LocationSessionBean; +import java.net.URI; +import java.util.logging.Logger; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; -import javax.ws.rs.core.*; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.EntityTag; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import com.maptology.api.PageConfig; +import com.maptology.api.device.Device; +import com.maptology.api.device.DeviceHandle; +import com.maptology.api.device.DeviceInfo; +import com.maptology.api.device.IDeviceService; +import com.maptology.service.entity.EntityForbiddenException; +import com.maptology.service.entity.EntityNotFoundException; +import com.maptology.service.session.DeviceSessionBean; /** * Implementation of the DeviceService @@ -23,93 +32,130 @@ import java.util.logging.Logger; @RequestScoped public class DeviceResource implements IDeviceService { - /** - * The device session bean that will be injected by the ejb container. - */ - @EJB - DeviceSessionBean deviceSession; + /** + * The device session bean that will be injected by the ejb container. + */ + @EJB + DeviceSessionBean deviceSession; - /** - * The location session bean that will be injected by the ejb container. - */ - @EJB - LocationSessionBean locationSession; + /** + * The request that will be injected by the jax-rs runtime. + */ + @Context + Request request; - /** - * The request that will be injected by the jax-rs runtime. - */ - @Context - Request request; + /** + * The uri info to build location urls. + */ + @Context + UriInfo uriInfo; - /** - * The uri info to build location urls. - */ - @Context - UriInfo uriInfo; + /** + * A logger injected by CDI. + */ + @Inject + Logger log; - /** - * A logger injected by CDI. - */ - @Inject - Logger log; + @Override + public Response createDevice(DeviceInfo info) { + DeviceHandle result = deviceSession.addDevice(info); + UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder(); + URI location = uriBuilder.path(Long.toString(result.getId())).build(); + return Response.status(Status.CREATED).entity(result).contentLocation(location).build(); + } - @Override - public Response createDevice() { - log.log(Level.INFO, "Received a post request to create a new device."); + @Override + public Response getCurrentDevice() { + try { + Device device = deviceSession.getCurrentDevice(); + EntityTag tag = new EntityTag(Long.toString(device.getModificationTime())); + ResponseBuilder r = request.evaluatePreconditions(tag); + if (r == null) { + r = Response.ok(device); + } + return r.tag(tag).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - Device result = deviceSession.addDevice(new Device()); + @Override + public Response deleteCurrentDevice() { + try { + deviceSession.deleteCurrentDevice(); + return Response.ok().build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder(); - URI location = uriBuilder - .path(Long.toString(result.getId())) - .build(); - return Response - .status(Response.Status.CREATED) - .entity(result) - .contentLocation(location) - .build(); - } + @Override + public Response getCurrentUserDevices(PageConfig config) { + try { + long timestamp = deviceSession.getLastModifiedDeviceForCurrentUser(); + EntityTag tag = new EntityTag(Long.toString(timestamp)); + ResponseBuilder builder = request.evaluatePreconditions(tag); + if (builder == null) { + builder = Response.ok(deviceSession.getAllDevicesForCurrentUser(config, true)); + } + return builder.tag(tag).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.INTERNAL_SERVER_ERROR).build(); + } + } - @Override - public Response getDevices(PageConfig pageConfig) { - log.log(Level.INFO, "Received a get request for a device page."); + @Override + public Response deleteDevice(long id) { + try { + deviceSession.deleteDevice(id); + return Response.ok().build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - long timestamp = deviceSession.getLastModified(); - EntityTag tag = new EntityTag(Long.toString(timestamp)); - Response.ResponseBuilder builder = request.evaluatePreconditions(tag); - if (builder == null) { - builder = Response - .ok(deviceSession.getAll(pageConfig, true)); - } - return builder - .tag(tag) - .build(); - } + @Override + public Response getDevice(long id) { + try { + Device result = deviceSession.getDevice(id); + EntityTag tag = new EntityTag(Long.toString(result.getModificationTime())); + ResponseBuilder builder = request.evaluatePreconditions(tag); + if (builder == null) { + builder = Response.ok(result); + } + return builder.tag(tag).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - @Override - public Response deleteCurrentDevice() { - return null; - } + @Override + public Response getDevices(PageConfig pageConfig) { + long timestamp = deviceSession.getLastModifiedDevice(); + EntityTag tag = new EntityTag(Long.toString(timestamp)); + ResponseBuilder builder = request.evaluatePreconditions(tag); + if (builder == null) { + builder = Response.ok(deviceSession.getAllDevices(pageConfig, false)); + } + return builder.tag(tag).build(); + } - @Override - public Response deleteDevice(long id) { - log.log(Level.INFO, "Received a delete request for a device."); + @Override + public Response setDevice(long id, Device device) { + try { + Device result = deviceSession.setDevice(id, device); + return Response.ok(result).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } + } - Device device = deviceSession.removeDevice(id); - if (device != null) { - return Response - .ok(device) - .build(); - } else { - return Response - .status(Response.Status.NOT_FOUND) - .build(); - } - } - - @Override - public Response setDeviceLocation(Location location) { - locationSession.addLocation(location); - return Response.ok().build(); - } } diff --git a/service/war/src/main/java/com/maptology/service/rest/LocationResource.java b/service/war/src/main/java/com/maptology/service/rest/LocationResource.java new file mode 100644 index 0000000..17cdbd2 --- /dev/null +++ b/service/war/src/main/java/com/maptology/service/rest/LocationResource.java @@ -0,0 +1,91 @@ +package com.maptology.service.rest; + +import java.util.logging.Logger; + +import javax.ejb.EJB; +import javax.inject.Inject; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.core.Response.Status; + +import com.maptology.api.location.ILocationService; +import com.maptology.api.location.Location; +import com.maptology.api.location.LocationUpdate; +import com.maptology.service.app.MaptologyTime; +import com.maptology.service.entity.EntityForbiddenException; +import com.maptology.service.entity.EntityNotFoundException; +import com.maptology.service.session.LocationSessionBean; + +/** + * The resource to manage locations. + * + * @author Marcus + * + */ +public class LocationResource implements ILocationService { + + + /** + * The session bean to access shares. + */ + @EJB + LocationSessionBean locationSession; + + /** + * The request that will be injected by the jax-rs runtime. + */ + @Context + Request request; + + /** + * The uri info to build location urls. + */ + @Context + UriInfo uriInfo; + + /** + * A logger injected by CDI. + */ + @Inject + Logger log; + + @Override + public Response getShareLocation(String token) { + try { + MaptologyTime time = new MaptologyTime(); + Location location = locationSession.getShareLocation(token, time.getNow()); + return Response.ok(location).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } + + @Override + public Response addLocations(LocationUpdate update) { + try { + locationSession.addLocations(update); + return Response.ok().build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } + + @Override + public Response getDeviceLocation(long id) { + try { + return Response.ok(locationSession.getDeviceLocation(id)).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } + + +} diff --git a/service/war/src/main/java/com/maptology/service/rest/ShareResource.java b/service/war/src/main/java/com/maptology/service/rest/ShareResource.java index f281832..7b6a113 100644 --- a/service/war/src/main/java/com/maptology/service/rest/ShareResource.java +++ b/service/war/src/main/java/com/maptology/service/rest/ShareResource.java @@ -1,21 +1,27 @@ package com.maptology.service.rest; -import com.maptology.api.PageConfig; -import com.maptology.api.share.IShareService; -import com.maptology.api.share.Share; -import com.maptology.api.share.ShareCreationRequest; -import com.maptology.service.conversion.ShareConverter; -import com.maptology.service.entity.share.ShareEntity; -import com.maptology.service.session.ShareSessionBean; +import java.net.URI; +import java.util.logging.Logger; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; -import javax.ws.rs.NotFoundException; -import javax.ws.rs.core.*; -import java.net.URI; -import java.util.logging.Level; -import java.util.logging.Logger; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.EntityTag; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import com.maptology.api.share.IShareService; +import com.maptology.api.share.Share; +import com.maptology.api.share.ShareInfo; +import com.maptology.service.app.MaptologyTime; +import com.maptology.service.entity.EntityForbiddenException; +import com.maptology.service.entity.EntityNotFoundException; +import com.maptology.service.session.ShareSessionBean; /** * Implementation of the share service @@ -25,8 +31,11 @@ import java.util.logging.Logger; @RequestScoped public class ShareResource implements IShareService { + /** + * The session bean to access shares. + */ @EJB - private ShareSessionBean shareSessionBean; + ShareSessionBean shareSession; /** * The request that will be injected by the jax-rs runtime. @@ -38,71 +47,78 @@ public class ShareResource implements IShareService { * The uri info to build location urls. */ @Context - private UriInfo uriInfo; + UriInfo uriInfo; /** * A logger injected by CDI. */ @Inject - private Logger log; + Logger log; - private ShareConverter converter = new ShareConverter(true); + @Override + public Response createShare(ShareInfo shareInfo) { + try { + Share result = shareSession.createShare(shareInfo); + UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder(); + URI location = uriBuilder.path(Long.toString(result.getId())).build(); + return Response.status(Status.CREATED).entity(result).contentLocation(location).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - @Override - public Response createShare(ShareCreationRequest shareRequest) { + @Override + public Response setShare(long id, Share share) { + try { + return Response.ok(shareSession.setShare(id, share)).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - log.log(Level.INFO, "Received a post request to create a new share."); + @Override + public Response deleteShare(long id) { + try { + shareSession.deleteShare(id); + return Response.ok().build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - ShareEntity share = shareSessionBean.createShare(shareRequest.getSecretId(), shareRequest.getExpirationTime()); - UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder(); - URI location = uriBuilder - .path(Long.toString(share.getId())) - .build(); - return Response - .status(Response.Status.CREATED) - .entity(converter.convert(share)) - .contentLocation(location) - .build(); - } + @Override + public Response getShareInfo(String token) { + MaptologyTime time = new MaptologyTime(); + try { + ShareInfo info = shareSession.getShareInfo(token, time.getNow()); + return Response.ok(info).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } + } + @Override + public Response getShare(long id) { + try { + Share share = shareSession.getShare(id); + EntityTag tag = new EntityTag(Long.toString(share.getModificationTime())); + ResponseBuilder builder = request.evaluatePreconditions(tag); + if (builder == null) { + builder = Response.ok(share); + } + return builder.tag(tag).build(); + } catch (EntityNotFoundException e) { + return Response.status(Status.NOT_FOUND).build(); + } catch (EntityForbiddenException e) { + return Response.status(Status.FORBIDDEN).build(); + } + } - @Override - public Response getShares(PageConfig pageConfig) { - - log.log(Level.INFO, "Received a get request for a share page."); - - //TODO enable caching using etags - - return Response.ok(shareSessionBean.getAllForUser(pageConfig, true)).build(); - - } - - @Override - public Response deleteShare(long id) { - - log.log(Level.INFO, "Received a get request for deleting the share with the id " + id); - - shareSessionBean.deleteShare(id); - return Response.status(Response.Status.OK).build(); - } - - @Override - public Response getShare(String secretId) { - Share share = shareSessionBean.getShareBySecretId(secretId); - - if (share == null) throw new NotFoundException(); - - EntityTag tag = new EntityTag(Long.toString(share.getModificationTime())); - Response.ResponseBuilder builder = request.evaluatePreconditions(tag); - if (builder == null) { - builder = Response.ok(share); - } - return builder.tag(tag).build(); - } - - @Override - public Response getShareLocation(String secretId) { - return Response.ok(shareSessionBean.getLastLocation(secretId)).build(); - } } diff --git a/service/war/src/main/java/com/maptology/service/rest/UserResource.java b/service/war/src/main/java/com/maptology/service/rest/UserResource.java index fdc57ae..b4b0ae6 100644 --- a/service/war/src/main/java/com/maptology/service/rest/UserResource.java +++ b/service/war/src/main/java/com/maptology/service/rest/UserResource.java @@ -87,6 +87,21 @@ public class UserResource implements IUserService { return builder.tag(tag).build(); } + @Override + public Response searchUsers(PageConfig pageConfig, String term) { + log.log(Level.INFO, "Received a get request for find users."); + long timestamp = userSession.getLastModifiedUser(); + EntityTag tag = new EntityTag(Long.toString(timestamp)); + ResponseBuilder builder = request.evaluatePreconditions(tag); + if (builder == null) { + log.log(Level.INFO, "Computing the search result page."); + builder = Response.ok(userSession.searchUsers(pageConfig, term, false)); + } else { + log.log(Level.INFO, "Client's search result page is still valid."); + } + return builder.tag(tag).build(); + } + @Override public Response getCurrentUser() { log.log(Level.INFO, "Received a get request for the current user."); @@ -99,6 +114,7 @@ public class UserResource implements IUserService { } return builder.tag(tag).build(); } catch (EntityException e) { + log.log(Level.WARNING, "Cannot access user.", e); return Response.status(Status.FORBIDDEN).build(); } } @@ -129,7 +145,6 @@ public class UserResource implements IUserService { } } - @Override public Response addUser(User user) { try { @@ -227,7 +242,5 @@ public class UserResource implements IUserService { return Response.status(Status.FORBIDDEN).build(); } } - - } diff --git a/service/war/src/main/webapp/WEB-INF/web.xml b/service/war/src/main/webapp/WEB-INF/web.xml index 171acc1..a989ac5 100644 --- a/service/war/src/main/webapp/WEB-INF/web.xml +++ b/service/war/src/main/webapp/WEB-INF/web.xml @@ -26,4 +26,5 @@ index.html + diff --git a/service/war/src/test/java/com/maptology/service/test/WarDeployment.java b/service/war/src/test/java/com/maptology/service/test/WarDeployment.java index efbf772..d643caa 100644 --- a/service/war/src/test/java/com/maptology/service/test/WarDeployment.java +++ b/service/war/src/test/java/com/maptology/service/test/WarDeployment.java @@ -26,6 +26,7 @@ public class WarDeployment { public static JavaArchive createEjb() { return ShrinkWrap.create(JavaArchive.class, "ejb.jar") // name used in ear (see application.xml) .addPackages(true, "com.maptology.api") + .addPackages(true, "com.maptology.service.principal") .addPackages(true, "com.maptology.service.conversion") .addPackages(true, "com.maptology.service.crypto") .addPackages(true, "com.maptology.service.entity") diff --git a/service/war/src/test/java/com/maptology/service/test/rest/AbstractResourceTest.java b/service/war/src/test/java/com/maptology/service/test/rest/AbstractResourceTest.java index 43c3e7c..21913a0 100644 --- a/service/war/src/test/java/com/maptology/service/test/rest/AbstractResourceTest.java +++ b/service/war/src/test/java/com/maptology/service/test/rest/AbstractResourceTest.java @@ -1,6 +1,5 @@ package com.maptology.service.test.rest; -import com.maptology.service.auth.MaptologyAuthModule; import com.maptology.service.test.WarDeployment; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.resteasy.client.jaxrs.BasicAuthentication; @@ -78,7 +77,7 @@ public class AbstractResourceTest { */ public ResteasyWebTarget getTarget(String deviceToken) { return getTarget().register((ClientRequestFilter) clientRequestContext -> { - clientRequestContext.getHeaders().putSingle(MaptologyAuthModule.DEVICE_AUTHORIZATION_HEADER, "Bearer " + deviceToken); + clientRequestContext.getHeaders().putSingle("Authorization", "Bearer " + deviceToken); }); } diff --git a/service/war/src/test/java/com/maptology/service/test/rest/DeviceResourceTest.java b/service/war/src/test/java/com/maptology/service/test/rest/DeviceResourceTest.java index 2e451d1..87dee24 100644 --- a/service/war/src/test/java/com/maptology/service/test/rest/DeviceResourceTest.java +++ b/service/war/src/test/java/com/maptology/service/test/rest/DeviceResourceTest.java @@ -1,17 +1,15 @@ package com.maptology.service.test.rest; -import com.maptology.api.PageConfig; -import com.maptology.api.device.Device; -import com.maptology.api.device.DevicePage; -import com.maptology.api.device.IDeviceService; -import com.maptology.api.device.Location; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.Response; + import org.jboss.arquillian.junit.Arquillian; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.Response; +import com.maptology.api.PageConfig; +import com.maptology.api.device.IDeviceService; @RunWith(Arquillian.class) public class DeviceResourceTest extends AbstractResourceTest { @@ -19,184 +17,171 @@ public class DeviceResourceTest extends AbstractResourceTest { @Test public void testPermissionsAsUser() { IDeviceService service = getTarget("handte", "secure").proxy(IDeviceService.class); - - { - Response get = service.getDevices(new PageConfig(0, 5)); - Assert.assertEquals("GET devices should be forbidden.", HttpServletResponse.SC_FORBIDDEN, get.getStatus()); - } - { - Response post = service.createDevice(); - Assert.assertNotEquals("POST devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, post.getStatus()); - - Response delete = service.deleteDevice(post.readEntity(Device.class).getId()); - Assert.assertEquals("DELETE device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, delete.getStatus()); - } - { - Response deleteCurrent = service.deleteCurrentDevice(); - Assert.assertEquals("DELETE current device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); - } - { - Response setLocation = service.setDeviceLocation(new Location()); - Assert.assertEquals("SET current device location should be forbidden.", HttpServletResponse.SC_FORBIDDEN, setLocation.getStatus()); - } - } - - @Test - public void testPermissionsAsAdmin() { - IDeviceService service = getTarget("admin", "admin").proxy(IDeviceService.class); - - { - Response get = service.getDevices(new PageConfig(0, 5)); - Assert.assertNotEquals("GET devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, get.getStatus()); - } - { - Response post = service.createDevice(); - Assert.assertNotEquals("POST devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, post.getStatus()); - - Response delete = service.deleteDevice(post.readEntity(Device.class).getId()); - Assert.assertNotEquals("DELETE device should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, delete.getStatus()); - } - { - Response deleteCurrent = service.deleteCurrentDevice(); - Assert.assertEquals("DELETE current device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); - } - { - Response setLocation = service.setDeviceLocation(new Location()); - Assert.assertEquals("SET current device location should be forbidden.", HttpServletResponse.SC_FORBIDDEN, setLocation.getStatus()); - } - } - - @Test - public void testPermissionsAsDevice() { - Device device = getTarget().proxy(IDeviceService.class).createDevice().readEntity(Device.class); - Assert.assertNotNull("Create device should work. Therefore device shouldn't be null.", device); - - IDeviceService service = getTarget(device.getAuthToken()).proxy(IDeviceService.class); - - { - Response get = service.getDevices(new PageConfig(0, 5)); - Assert.assertEquals("GET devices should be forbidden.", HttpServletResponse.SC_FORBIDDEN, get.getStatus()); - } - { - Response post = service.createDevice(); - Assert.assertNotEquals("POST devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, post.getStatus()); - - Response delete = service.deleteDevice((post.readEntity(Device.class)).getId()); - Assert.assertEquals("DELETE device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, delete.getStatus()); - } - { - Response deleteCurrent = service.deleteCurrentDevice(); - Assert.assertNotEquals("DELETE current device should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); - } - { - Response setLocation = service.setDeviceLocation(new Location()); - Assert.assertNotEquals("SET current device location should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, setLocation.getStatus()); - } - } - - @Test - public void testPermissionsAnonymous() { - IDeviceService service = getTarget().proxy(IDeviceService.class); - - { - Response get = service.getDevices(new PageConfig(0, 5)); - Assert.assertEquals("GET devices should be forbidden.", HttpServletResponse.SC_FORBIDDEN, get.getStatus()); - } - { - Response post = service.createDevice(); - Assert.assertNotEquals("POST devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, post.getStatus()); - - Response delete = service.deleteDevice(post.readEntity(Device.class).getId()); - Assert.assertEquals("DELETE device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, delete.getStatus()); - } - { - Response deleteCurrent = service.deleteCurrentDevice(); - Assert.assertEquals("DELETE current device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); - } - { - Response setLocation = service.setDeviceLocation(new Location()); - Assert.assertEquals("SET current device location should be forbidden.", HttpServletResponse.SC_FORBIDDEN, setLocation.getStatus()); - } - } - - @Test - public void - testCreateDeviceAsAnonymous() { - IDeviceService service = getTarget().proxy(IDeviceService.class); - - Response r = service.createDevice(); - Assert.assertEquals("Should return 201 CREATED.", HttpServletResponse.SC_CREATED, r.getStatus()); - - String locationHeader = r.getHeaderString("Content-Location"); - Assert.assertNotNull("Should return Content-Location header.", locationHeader); - Assert.assertFalse("Content-Location header should not be empty string.", locationHeader.isEmpty()); - - Device d = r.readEntity(Device.class); - Assert.assertNotNull("Should return device.", d); - Assert.assertTrue("Response should contain id.", d.getId() > 0); - Assert.assertNull("Response should not contain user login.", d.getUserLogin()); - Assert.assertNotNull("Response should contain auth token.", d.getAuthToken()); - } - - @Test - public void testCreateDeviceAsUser() { - IDeviceService service = getTarget("handte", "secure").proxy(IDeviceService.class); - - Response r = service.createDevice(); - Assert.assertEquals("Should return 201 CREATED.", HttpServletResponse.SC_CREATED, r.getStatus()); - - Device d = r.readEntity(Device.class); - Assert.assertNotNull("Should return device.", d); - Assert.assertEquals("Response should contain correct user login.", d.getUserLogin(), "handte"); - Assert.assertNotNull("Response should contain auth token.", d.getAuthToken()); - } - - @Test - public void testGetDevices() { - IDeviceService service = getTarget("admin", "admin").proxy(IDeviceService.class); - IDeviceService serviceAsAnonymous = getTarget().proxy(IDeviceService.class); - long addedId = serviceAsAnonymous.createDevice().readEntity(Device.class).getId(); // have at least one device - - Response r = service.getDevices(new PageConfig(0, 100)); - Assert.assertEquals("Should return 200 OK.", HttpServletResponse.SC_OK, r.getStatus()); - - DevicePage page = r.readEntity(DevicePage.class); - Assert.assertNotNull("Should return device page.", page); - - Device addedDevice = null; - // test for each device - for (Device d : page.getElements()) { - Assert.assertNull("Should not contain auth token.", d.getAuthToken()); - // find created device in page - if (d.getId() == addedId) addedDevice = d; - } - - Assert.assertNotNull("Should contain created device", addedDevice); - } - - @Test - public void testDeleteCurrentDevice() { - // TODO test - } - - @Test - public void testDeleteDevice() { - IDeviceService service = getTarget("admin", "admin").proxy(IDeviceService.class); - IDeviceService serviceAsAnonymous = getTarget().proxy(IDeviceService.class); - long addedId = serviceAsAnonymous.createDevice().readEntity(Device.class).getId(); // get valid device - - Response r = service.deleteDevice(addedId); - Assert.assertEquals("Should return 200 OK.", HttpServletResponse.SC_OK, r.getStatus()); - - Device device = r.readEntity(Device.class); - Assert.assertNotNull("Should return device.", device); - Assert.assertEquals("Should return the deleted device.", addedId, device.getId()); - Assert.assertTrue("Returned device should be set to deleted.", device.isDeleted()); - Assert.assertNull("Should not contain auth token.", device.getAuthToken()); - } - - @Test - public void testSetDeviceLocation() { - // TODO test + // check get devices fails + Response getDevices = service.getDevices(new PageConfig(0, 5)); + Assert.assertEquals("GET devices should be forbidden.", HttpServletResponse.SC_FORBIDDEN, getDevices.getStatus()); + // check delete current fails + Response deleteCurrent = service.deleteCurrentDevice(); + Assert.assertEquals("DELETE current device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); } +// +// @Test +// public void testPermissionsAsAdmin() { +// IDeviceService service = getTarget("admin", "admin").proxy(IDeviceService.class); +// +// { +// Response get = service.getDevices(new PageConfig(0, 5)); +// Assert.assertNotEquals("GET devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, get.getStatus()); +// } +// { +// Response post = service.createDevice(); +// Assert.assertNotEquals("POST devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, post.getStatus()); +// +// Response delete = service.deleteDevice(post.readEntity(Device.class).getId()); +// Assert.assertNotEquals("DELETE device should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, delete.getStatus()); +// } +// { +// Response deleteCurrent = service.deleteCurrentDevice(); +// Assert.assertEquals("DELETE current device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); +// } +// { +// Response setLocation = service.setDeviceLocation(new Location()); +// Assert.assertEquals("SET current device location should be forbidden.", HttpServletResponse.SC_FORBIDDEN, setLocation.getStatus()); +// } +// } +// +// @Test +// public void testPermissionsAsDevice() { +// Device device = getTarget().proxy(IDeviceService.class).createDevice().readEntity(Device.class); +// Assert.assertNotNull("Create device should work. Therefore device shouldn't be null.", device); +// +// IDeviceService service = getTartget(device.getAuthToken()).proxy(IDeviceService.class); +// +// { +// Response get = service.getDevices(new PageConfig(0, 5)); +// Assert.assertEquals("GET devices should be forbidden.", HttpServletResponse.SC_FORBIDDEN, get.getStatus()); +// } +// { +// Response post = service.createDevice(); +// Assert.assertNotEquals("POST devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, post.getStatus()); +// +// Response delete = service.deleteDevice((post.readEntity(Device.class)).getId()); +// Assert.assertEquals("DELETE device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, delete.getStatus()); +// } +// { +// Response deleteCurrent = service.deleteCurrentDevice(); +// Assert.assertNotEquals("DELETE current device should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); +// } +// { +// Response setLocation = service.setDeviceLocation(new Location()); +// Assert.assertNotEquals("SET current device location should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, setLocation.getStatus()); +// } +// } +// +// @Test +// public void testPermissionsAnonymous() { +// IDeviceService service = getTarget().proxy(IDeviceService.class); +// +// { +// Response get = service.getDevices(new PageConfig(0, 5)); +// Assert.assertEquals("GET devices should be forbidden.", HttpServletResponse.SC_FORBIDDEN, get.getStatus()); +// } +// { +// Response post = service.createDevice(); +// Assert.assertNotEquals("POST devices should not be forbidden.", HttpServletResponse.SC_FORBIDDEN, post.getStatus()); +// +// Response delete = service.deleteDevice(post.readEntity(Device.class).getId()); +// Assert.assertEquals("DELETE device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, delete.getStatus()); +// } +// { +// Response deleteCurrent = service.deleteCurrentDevice(); +// Assert.assertEquals("DELETE current device should be forbidden.", HttpServletResponse.SC_FORBIDDEN, deleteCurrent.getStatus()); +// } +// { +// Response setLocation = service.setDeviceLocation(new Location()); +// Assert.assertEquals("SET current device location should be forbidden.", HttpServletResponse.SC_FORBIDDEN, setLocation.getStatus()); +// } +// } +// +// @Test +// public void +// testCreateDeviceAsAnonymous() { +// IDeviceService service = getTarget().proxy(IDeviceService.class); +// +// Response r = service.createDevice(); +// Assert.assertEquals("Should return 201 CREATED.", HttpServletResponse.SC_CREATED, r.getStatus()); +// +// String locationHeader = r.getHeaderString("Content-Location"); +// Assert.assertNotNull("Should return Content-Location header.", locationHeader); +// Assert.assertFalse("Content-Location header should not be empty string.", locationHeader.isEmpty()); +// +// Device d = r.readEntity(Device.class); +// Assert.assertNotNull("Should return device.", d); +// Assert.assertTrue("Response should contain id.", d.getId() > 0); +// Assert.assertNull("Response should not contain user login.", d.getUserLogin()); +// Assert.assertNotNull("Response should contain auth token.", d.getAuthToken()); +// } +// +// @Test +// public void testCreateDeviceAsUser() { +// IDeviceService service = getTarget("handte", "secure").proxy(IDeviceService.class); +// +// Response r = service.createDevice(); +// Assert.assertEquals("Should return 201 CREATED.", HttpServletResponse.SC_CREATED, r.getStatus()); +// +// Device d = r.readEntity(Device.class); +// Assert.assertNotNull("Should return device.", d); +// Assert.assertEquals("Response should contain correct user login.", d.getUserLogin(), "handte"); +// Assert.assertNotNull("Response should contain auth token.", d.getAuthToken()); +// } +// +// @Test +// public void testGetDevices() { +// IDeviceService service = getTarget("admin", "admin").proxy(IDeviceService.class); +// IDeviceService serviceAsAnonymous = getTarget().proxy(IDeviceService.class); +// long addedId = serviceAsAnonymous.createDevice().readEntity(Device.class).getId(); // have at least one device +// +// Response r = service.getDevices(new PageConfig(0, 100)); +// Assert.assertEquals("Should return 200 OK.", HttpServletResponse.SC_OK, r.getStatus()); +// +// DevicePage page = r.readEntity(DevicePage.class); +// Assert.assertNotNull("Should return device page.", page); +// +// Device addedDevice = null; +// // test for each device +// for (Device d : page.getElements()) { +// Assert.assertNull("Should not contain auth token.", d.getAuthToken()); +// // find created device in page +// if (d.getId() == addedId) addedDevice = d; +// } +// +// Assert.assertNotNull("Should contain created device", addedDevice); +// } +// +// @Test +// public void testDeleteCurrentDevice() { +// // TODO test +// } +// +// @Test +// public void testDeleteDevice() { +// IDeviceService service = getTarget("admin", "admin").proxy(IDeviceService.class); +// IDeviceService serviceAsAnonymous = getTarget().proxy(IDeviceService.class); +// long addedId = serviceAsAnonymous.createDevice().readEntity(Device.class).getId(); // get valid device +// +// Response r = service.deleteDevice(addedId); +// Assert.assertEquals("Should return 200 OK.", HttpServletResponse.SC_OK, r.getStatus()); +// +// Device device = r.readEntity(Device.class); +// Assert.assertNotNull("Should return device.", device); +// Assert.assertEquals("Should return the deleted device.", addedId, device.getId()); +// Assert.assertTrue("Returned device should be set to deleted.", device.isDeleted()); +// Assert.assertNull("Should not contain auth token.", device.getAuthToken()); +// } +// +// @Test +// public void testSetDeviceLocation() { +// // TODO test +// } + } diff --git a/web/angular/pom.xml b/web/angular/pom.xml index acb0008..04076bb 100644 --- a/web/angular/pom.xml +++ b/web/angular/pom.xml @@ -109,4 +109,12 @@ + + + + com.maptology + api + ${project.version} + + diff --git a/web/angular/src/app/views/components/map/map.component.ts b/web/angular/src/app/views/components/map/map.component.ts index 7e87554..2071811 100755 --- a/web/angular/src/app/views/components/map/map.component.ts +++ b/web/angular/src/app/views/components/map/map.component.ts @@ -98,7 +98,7 @@ export class MapComponent implements OnInit { } setMapPosition(location: Location, zoom: number) { - const latLang = new LatLng(location.lat, location.lon); + const latLang = new LatLng(location.coordinate.latitude, location.coordinate.longitude); this.map.panTo(latLang, this.zoomPanOptions); this.setMapMarker(latLang); }