Merge remote-tracking branch 'origin/master'
lbs-gitea/maptology/master There was a failure building this commit

This commit is contained in:
Arman Arzani
2017-12-14 21:32:20 +01:00
15 changed files with 424 additions and 69 deletions
@@ -24,13 +24,13 @@ public class Device extends Entity {
@NotNull
@XmlAttribute(required = true)
@ApiModelProperty(value = "The secret device token. The token is used for authenticating the device.", required = true)
private String secret;
private String authToken;
public String getSecret() {
return secret;
public String getAuthToken() {
return authToken;
}
public void setSecret(String secret) {
this.secret = secret;
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
}
@@ -1,8 +1,10 @@
package com.maptology.api.device;
import com.maptology.api.PageConfig;
import com.maptology.api.access.Roles;
import io.swagger.annotations.*;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
@@ -26,77 +28,82 @@ public interface IDeviceService {
*
* @return The newly created device.
*/
@PUT
@Path("device")
@ApiOperation(value = "Creates a new device")
@POST
@Path("devices")
@ApiOperation(value = "Creates a new device.",
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)
})
Response createDevice();
// 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 devices from a user or all devices currently registered if the user is an admin.
* Returns all currently registered devices
*
* @return A list of devices
*/
@GET // TODO: this is not a good design decision as the function now has two meanings, consider splitting it into 2 functions
@Path("device")
@ApiOperation(value = "Get all devices from the current user. This method return all currently registered devices if the user is an admin.", authorizations = @Authorization("device"))
@GET
@Path("devices")
@ApiOperation(value = "Returns all currently registered devices", authorizations = @Authorization("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."),
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter.")
})
@RolesAllowed({Roles.ADMIN})
Response getDevices(@BeanParam @Valid PageConfig pageConfig);
/**
* This method deletes the current device
*/
@DELETE
@Path("devices/current")
@ApiOperation(value = "Deletes the current device", authorizations = {@Authorization("device")})
@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 // TODO: split into admin and device, device will not require any id
@Path("device/{id}")
@ApiOperation(value = "Deletes a device", authorizations = {@Authorization("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_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);
/**
* Get the last known location of a device
*
* @param id The id of the device
* @return The last known location
*/
@GET // TODO: split into two methods, one for admin and one for user
@Path("device/{id}/location")
@ApiOperation(value = "Returns the last known location of a device", authorizations = {@Authorization("device")})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successfully"),
@ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device does not exists"),
@ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Insufficient privileges")
})
Response getDeviceLocation(@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 id The id of the device
* @param location The location to set
*/
@POST // TODO: why provide device id?
@Path("device/{id}/location")
@ApiOperation(value = "Updates the last known location of a device", authorizations = {@Authorization("device")})
@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", response = Location.class),
@ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The device does not exists"),
@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.")
})
Response setDeviceLocation(@ApiParam(value = "The device id", required = true) @PathParam("id") @Valid @Min(0) long id,
@ApiParam(value = "The location to set", required = true) @Valid Location location);
@RolesAllowed({Roles.DEVICE})
Response setDeviceLocation(@ApiParam(value = "The location to set", required = true) @Valid Location location);
}
@@ -1,9 +1,11 @@
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.RolesAllowed;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.Min;
@@ -29,13 +31,14 @@ public interface IShareService {
* @param share The share to create
*/
@PUT
@Path("share")
@Path("shares")
@ApiOperation(value = "Creates a new share", authorizations = {@Authorization("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.")
})
@RolesAllowed({Roles.DEVICE})
Response createShare(@ApiParam(value = "The share to create", required = true) @Valid Share share);
/**
@@ -45,13 +48,14 @@ public interface IShareService {
* @return A list of all received shares for an user
*/
@GET
@Path("share")
@ApiOperation(value = "Get all received shares for an user", authorizations = {@Authorization("device")})
@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_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);
/**
@@ -60,7 +64,7 @@ public interface IShareService {
* @param id The id of the share to delete
*/
@DELETE
@Path("share/{id}")
@Path("shares/{secretId: [A-Za-z0-9]+}")
@ApiOperation(value = "Delete a share", authorizations = {@Authorization("device")})
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful."),
@@ -68,7 +72,8 @@ public interface IShareService {
@ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Invalid request parameter."),
@ApiResponse(code = HttpServletResponse.SC_NOT_FOUND, message = "The share does not exists"),
})
Response deleteShare(@ApiParam(value = "The share id", required = true) @PathParam("id") @Valid @Min(0) long id);
@RolesAllowed({Roles.DEVICE})
Response deleteShare(@ApiParam(value = "The share id", required = true) @PathParam("secretId") @Valid @Min(0) long id);
/**
* Get a share
@@ -77,7 +82,7 @@ public interface IShareService {
* @return The requested share
*/
@GET
@Path("share/{secretId: [A-Za-z0-9]+}")
@Path("shares/{secretId: [A-Za-z0-9]+}")
@ApiOperation(value = "Get a share")
@ApiResponses({
@ApiResponse(code = HttpServletResponse.SC_OK, message = "The request was successful.", response = Share.class),
@@ -95,7 +100,8 @@ public interface IShareService {
* @return The last known location
*/
@GET
@Path("share/{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)
@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),
@@ -0,0 +1,56 @@
package com.maptology.service.conversion;
import com.maptology.api.device.Device;
import com.maptology.service.entity.device.DeviceEntity;
/**
* Creates a device from a device entity.
* The secret field is excluded
*/
public class DeviceConverter extends AbstractEntityConverter<DeviceEntity, Device> {
/**
* A flag to indicate whether the returned objects should contain the secret.
*/
private final boolean includeAuthToken;
/**
* Creates a new entity converter.
*
* @param filtered A flag to indicate whether
* deleted objects should be filtered.
*/
public DeviceConverter(boolean filtered) {
this(filtered, false);
}
/**
* 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
if (includeAuthToken) {
device.setAuthToken(source.getAuthToken());
}
return device;
}
}
@@ -22,9 +22,20 @@ public class SecureToken {
* @throws SecureException Thrown if the random number generator fails.
*/
public static String createToken() {
return encodeToken(generateToken(SIZE));
return createToken(SIZE);
}
/**
* Creates a new random urlsafe token, based on a token with the specified size in bytes.
*
* @param baseBytes The size in bytes.
* @return The new random urlsafe token.
* @throws SecureException Thrown if the random number generator fails.
*/
public static String createToken(int baseBytes) {
return encodeToken(generateToken(baseBytes));
}
/**
* Generates a random token.
*
@@ -0,0 +1,54 @@
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 javax.persistence.*;
/**
* The entity to store devices.
*
* @author Philipp
*/
@Entity
@Table(name = "device",
indexes = {
@Index(columnList = "deleted,modificationTime", unique = false),
@Index(columnList = "authToken", unique = true)
})
public class DeviceEntity extends AbstractEntity {
/**
* The user that this device belongs to.
*/
@ManyToOne(fetch = FetchType.LAZY)
private UserEntity user;
/**
* The auth token to be used when authenticating the device.
* Can only be generated by the server.
*/
@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);
}
}
@@ -0,0 +1,42 @@
package com.maptology.service.session;
import com.maptology.api.device.Device;
import com.maptology.service.conversion.DeviceConverter;
import com.maptology.service.entity.device.DeviceEntity;
import com.maptology.service.entity.user.UserEntity;
import javax.annotation.security.PermitAll;
import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.enterprise.context.RequestScoped;
/**
* A stateful session bean to manage devices.
*
* @author Philipp
*/
@Stateful
@RequestScoped
public class DeviceSessionBean extends AbstractSessionBean {
@EJB
UserSessionBean userSession;
/**
* Adds a new device to the database.
*
* @return The new device, also containing the secret to be used for authentication.
*/
@PermitAll
public Device addDevice(Device device) {
UserEntity userEntity = userSession.getCurrentUserEntity();
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);
}
}
@@ -115,10 +115,23 @@ public class UserSessionBean extends AbstractSessionBean {
Principal p = sessionContext.getCallerPrincipal();
if (p == null) throw new EntityForbiddenException(UserEntity.class, null, "Cannot access current user for unauthorized user.");
String login = p.getName();
User u = findUser(login, true);
UserEntity u = findUserEntity(login);
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 u;
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());
}
/**
@@ -168,18 +181,14 @@ public class UserSessionBean extends AbstractSessionBean {
}
/**
* Returns the user by login. The result is optionally filtered
* by deleted accounts. This method is intended for testing.
* Returns the user entity by login.
*
* @param login The login.
* @param filtered True to not return deleted users.
* @return The user or null, if the user is not found or deleted.
* @return The user or null, if the user does not exist.
*/
@PermitAll
public User findUser(String login, boolean filtered) {
UserEntity user = UserEntity.findByLogin(em, login);
UserConverter c = new UserConverter(filtered);
return c.convert(user);
public UserEntity findUserEntity(String login) {
return UserEntity.findByLogin(em, login);
}
/**
@@ -252,7 +261,7 @@ public class UserSessionBean extends AbstractSessionBean {
*/
@RolesAllowed({ Roles.ADMIN })
public User addUser(User user, long expirationTime) throws EntityConflictException {
User existing = findUser(user.getLogin(), false);
UserEntity existing = findUserEntity(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
@@ -603,5 +612,4 @@ public class UserSessionBean extends AbstractSessionBean {
c.setExpirationTime(expirationTime);
return c;
}
}
@@ -0,0 +1,65 @@
package com.maptology.service.test.session;
import com.maptology.api.device.Device;
import com.maptology.service.session.DeviceSessionBean;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
/**
* Tests the device session bean
*
* @author Philipp
*/
@RunWith(Arquillian.class)
public class DeviceSessionTest extends AbstractSessionTest {
@Inject
DeviceSessionBean deviceSession;
/**
* Tests, whether a user with role admin can create a device.
*/
@Test
public void canAddDeviceAsAdmin() {
executeAs("admin", 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());
}
});
}
/**
* Tests, whether a client without user authentication can create a device.
*/
@Test
public void canAddDeviceAsAnonymous() {
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 canAddDeviceAsUser() {
executeAs("handte", 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());
}
});
}
}
@@ -320,7 +320,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.findUser("adduser", false));
Assert.assertNull("Database should not contain non-added user.", userSession.findUserEntity("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 +342,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.findUser("adduser2", false));
Assert.assertNull("Database should not contain non-added user.", userSession.findUserEntity("adduser2"));
Assert.assertEquals("Invalid addition should not result in email.", emails, emailSession.getEntries().size());
} catch (Exception e) {
Assert.assertNull("Should not raise exception.", e);
+16
View File
@@ -46,4 +46,20 @@
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<!-- compile backend code to 1.8 (no android here) -->
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
@@ -7,10 +7,7 @@ import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import com.maptology.service.access.AccessControlFilter;
import com.maptology.service.rest.LogResource;
import com.maptology.service.rest.NoticeResource;
import com.maptology.service.rest.UserResource;
import com.maptology.service.rest.VersionResource;
import com.maptology.service.rest.*;
/**
* The application is the main entry point of JAX-RS.
@@ -29,6 +26,7 @@ public class MaptologyApplication extends Application {
classes.add(NoticeResource.class);
classes.add(LogResource.class);
classes.add(VersionResource.class);
classes.add(DeviceResource.class);
return classes;
}
@@ -0,0 +1,86 @@
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 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;
/**
* Implementation of the DeviceService
*
* @author Philipp
*/
@RequestScoped
public class DeviceResource implements IDeviceService {
/**
* The device session bean that will be injected by the ejb container.
*/
@EJB
DeviceSessionBean deviceSession;
/**
* 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 createDevice() {
log.log(Level.INFO, "Received a post request to create a new device.");
Device result = deviceSession.addDevice(new Device());
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 getDevices(PageConfig pageConfig) {
return null;
}
@Override
public Response deleteCurrentDevice() {
return null;
}
@Override
public Response deleteDevice(long id) {
return null;
}
@Override
public Response setDeviceLocation(Location location) {
return null;
}
}
@@ -9,7 +9,7 @@
<p class="text-muted">Sign In to your account</p>
<div class="input-group mb-2">
<span class="input-group-addon"><i class="icon-user"></i></span>
<input type="text" class="form-control" placeholder="Username" name="login" [(ngModel)]="login" pattern="([a-zA-Z0-9]){5,32}" required #loginModel="ngModel">
<input type="text" class="form-control" placeholder="Username" name="login" [(ngModel)]="login" pattern="([a-zA-Z0-9]){5,32}" required #loginModel="ngModel" (keyup)="loginOnEnter($event)">
</div>
<div class="input-group mb-3" *ngIf="loginForm.dirty && loginModel.errors?.required || loginForm.dirty && loginModel.errors?.pattern">
@@ -17,13 +17,13 @@
Please specify your login.
</div>
<div class="alert alert-warning p-1 m-0" *ngIf="loginForm.dirty && loginModel.errors?.pattern">
Minimum 5, maximu 32 characters (only letters and numbers).
Minimum 5, maximum 32 characters (only letters and numbers).
</div>
</div>
<div class="input-group mb-2">
<span class="input-group-addon"><i class="icon-lock"></i></span>
<input type="password" class="form-control" placeholder="Password" name="password" [(ngModel)]="password" required #passwordModel="ngModel">
<input type="password" class="form-control" placeholder="Password" name="password" [(ngModel)]="password" required #passwordModel="ngModel" (keyup)="loginOnEnter($event)">
</div>
<div class="input-group mb-3" *ngIf="loginForm.dirty && passwordModel.errors?.required">
@@ -55,5 +55,11 @@ export class LoginComponent implements OnInit {
registerButton() {
this.router.navigate(['/pages/register']);
}
loginOnEnter($event: KeyboardEvent): void {
if($event.keyCode===13){
this.requestLogin();
}
}
}