/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package murban.exerciser.api.controllers;
import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import murban.exerciser.api.dao.TokenFacade;
import murban.exerciser.api.models.Token;
/**
* REST Web Service
*
* @author PSYcho
*/
@Path("tokens")
@Produces("application/json")
public class TokenController {
@Context
private UriInfo context;
@EJB
private TokenFacade tokenFacade;
/**
* Creates a new instance of SecurityController
*/
public TokenController() {
}
@GET
@Path("/{userid}")
public Response getToken(@PathParam("userid") String userid, @HeaderParam("ApiKey") String ApiKey) {
if (ApiKey == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("ApiKey is required").build();
}
try {
if (!isValidApiKey(ApiKey)) {
return Response.status(Response.Status.BAD_REQUEST).entity("Invalid API key").build();
}
} catch (Exception ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
}
if (userid == null || userid.length() < 3) {
return Response.status(Response.Status.BAD_REQUEST).entity("userid is required with min. length 3 characters").build();
}
Token token = tokenFacade.createToken(userid);
return Response.status(Response.Status.OK).entity(token).build();
}
private boolean isValidApiKey(String key) throws Exception {
String api_key = System.getProperty("API_KEY");
if (api_key == null){
throw new Exception("API_KEY is not setup");
}
return key.equals(System.getProperty("API_KEY"));
}
}