Skip to content
This repository was archived by the owner on Apr 22, 2022. It is now read-only.

Commit 2d29608

Browse files
committed
add authsessions to be saved in sessionsGraph (new) and its corresponding tests
1 parent 76153c5 commit 2d29608

File tree

13 files changed

+212
-79
lines changed

13 files changed

+212
-79
lines changed

src/main/java/accounts/FrameworkUserManager.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import java.util.Iterator;
1010
import java.util.List;
1111

12+
import javax.ws.rs.core.Cookie;
13+
1214
import org.apache.commons.codec.digest.DigestUtils;
1315
import org.apache.log4j.Logger;
1416
import org.codehaus.jackson.JsonNode;
@@ -651,8 +653,17 @@ public String getDescribedIn(String graph) throws Exception {
651653
* @return user profile object if token valid and null if the opposite
652654
* @throws Exception
653655
*/
656+
657+
public UserProfile validate(Cookie userc, String token) throws Exception {
658+
if (userc == null || token == null)
659+
return null;
660+
String userstr = URLDecoder.decode(userc.getValue(), "utf-8");
661+
return validate(userstr, token);
662+
}
663+
654664
public UserProfile validate(String userc, String token) throws Exception {
655665
String userstr = URLDecoder.decode(userc, "utf-8");
666+
656667
log.debug(" userstr: " + userstr + " token:" + token);
657668
Gson gson = new Gson();
658669
UserProfile user = gson.fromJson(userstr, UserProfile.class);

src/main/java/authentication/FrameworkConfiguration.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ public class FrameworkConfiguration {
5050
private String accountsGraph = "";
5151
private String settingsGraph = "";
5252
private String jobsGraph = "";
53+
private String authSessionsGraph = "";
5354
private String initialSettingsGraph = "";
5455
private String groupsGraph = "";
5556
private String frameworkUri;
@@ -190,6 +191,8 @@ else if ("groups".equals(soln.get("label").asLiteral().getString()))
190191
instance.setGroupsGraph(soln.get("name").toString());
191192
else if ("jobs".equals(soln.get("label").asLiteral().getString()))
192193
instance.setJobsGraph(soln.get("name").toString());
194+
else if ("sessions".equals(soln.get("label").asLiteral().getString()))
195+
instance.setAuthSessionsGraph(soln.get("name").toString());
193196
}
194197
qexec.close();
195198
}
@@ -390,4 +393,12 @@ public void setJobsGraph(String jobsGraph) {
390393
this.jobsGraph = jobsGraph;
391394
}
392395

396+
public String getAuthSessionsGraph() {
397+
return authSessionsGraph;
398+
}
399+
400+
public void setAuthSessionsGraph(String authSessionsGraph) {
401+
this.authSessionsGraph = authSessionsGraph;
402+
}
403+
393404
}

src/main/java/rest/AuthorizedSessions.java

Lines changed: 111 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,24 @@
77
import java.io.OutputStreamWriter;
88
import java.io.Writer;
99
import java.util.ArrayList;
10-
import java.util.Hashtable;
10+
import java.util.Iterator;
1111
import java.util.List;
1212
import java.util.Map.Entry;
1313
import java.util.UUID;
1414

1515
import javax.servlet.ServletContext;
1616
import javax.servlet.ServletException;
1717
import javax.ws.rs.CookieParam;
18+
import javax.ws.rs.DELETE;
1819
import javax.ws.rs.GET;
1920
import javax.ws.rs.POST;
2021
import javax.ws.rs.PUT;
2122
import javax.ws.rs.Path;
2223
import javax.ws.rs.PathParam;
2324
import javax.ws.rs.Produces;
24-
import javax.ws.rs.QueryParam;
2525
import javax.ws.rs.WebApplicationException;
2626
import javax.ws.rs.core.Context;
27+
import javax.ws.rs.core.Cookie;
2728
import javax.ws.rs.core.MediaType;
2829
import javax.ws.rs.core.Response;
2930
import javax.ws.rs.core.StreamingOutput;
@@ -41,12 +42,17 @@
4142
import org.apache.http.impl.client.HttpClients;
4243
import org.apache.http.message.BasicNameValuePair;
4344
import org.apache.log4j.Logger;
45+
import org.codehaus.jackson.JsonNode;
46+
import org.codehaus.jackson.map.ObjectMapper;
4447

48+
import rdf.SecureRdfStoreManagerImpl;
4549
import util.ObjectPair;
4650
import accounts.FrameworkUserManager;
51+
import accounts.UserProfile;
4752
import authentication.FrameworkConfiguration;
4853

4954
import com.google.gson.JsonObject;
55+
import com.ontos.ldiw.vocabulary.LDIWO;
5056

5157
/**
5258
*
@@ -59,17 +65,20 @@ public class AuthorizedSessions {
5965
private static final Logger log = Logger.getLogger(AuthorizedSessions.class);
6066

6167
private FrameworkUserManager frameworkUserManager;
62-
private ObjectPair<String, String> rdfStoreUser;
63-
// TODO: the information of this map has to be stored in the user settings
64-
// graph instead
65-
public static Hashtable<String, String> map = new Hashtable<String, String>();
68+
private String sessionsGraph;
6669
private String endpoint;
6770

71+
private SecureRdfStoreManagerImpl frameworkRdfStoreManager;
72+
6873
public AuthorizedSessions(@Context ServletContext context) throws ServletException {
6974
try {
70-
frameworkUserManager = FrameworkConfiguration.getInstance(context)
71-
.getFrameworkUserManager();
75+
FrameworkConfiguration frameworkConfig = FrameworkConfiguration.getInstance(context);
76+
frameworkUserManager = frameworkConfig.getFrameworkUserManager();
77+
sessionsGraph = frameworkConfig.getAuthSessionsGraph();
7278
endpoint = FrameworkConfiguration.getInstance(context).getAuthSparqlEndpoint();
79+
frameworkRdfStoreManager = new SecureRdfStoreManagerImpl(frameworkConfig
80+
.getAuthSparqlEndpoint(), frameworkConfig.getAuthSparqlUser(), frameworkConfig
81+
.getAuthSparqlPassword());
7382
} catch (FileNotFoundException e) {
7483
log.error(e);
7584
e.printStackTrace();
@@ -83,35 +92,47 @@ public AuthorizedSessions(@Context ServletContext context) throws ServletExcepti
8392

8493
@PUT
8594
@Produces(MediaType.APPLICATION_JSON)
86-
public Response create(@QueryParam("username") String username,
95+
public Response create(@CookieParam(value = "user") Cookie userc,
8796
@CookieParam(value = "token") String token) {
8897

8998
/*
9099
* authenticates the user, throw exception if failed
91100
*/
92-
log.debug("user:" + username + " token:" + token);
93-
boolean checkToken = false;
101+
UserProfile userProfile;
94102
try {
95-
checkToken = frameworkUserManager.checkToken(username, token);
96-
if (!checkToken)
97-
return Response.status(Response.Status.UNAUTHORIZED).build();
98-
rdfStoreUser = frameworkUserManager.getRdfStoreUser(username, token);
99-
103+
// authenticates the user, throw exception if fail
104+
userProfile = frameworkUserManager.validate(userc, token);
105+
if (userProfile == null)
106+
return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials")
107+
.build();
108+
log.info(" user: " + userProfile.getUsername());
100109
} catch (Exception e) {
101110
log.error(e);
102111
e.printStackTrace();
103112
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
104113
.build();
105114
}
106115
/*
107-
* generates a session for the user
116+
* generates a session for the user and stores it in the sessions graph
117+
* <accountURI> LDIWO.sessionToken
118+
* "1fe39ef0-6987-11e4-9803-0800200c9a66"^^xsd:string
108119
*/
109120
String sessionToken = UUID.randomUUID().toString();
110-
map.put(sessionToken, rdfStoreUser.getFirst() + ":" + rdfStoreUser.getSecond());
111-
log.debug(map.toString());
121+
122+
String query = "INSERT INTO <" + sessionsGraph + "> { <" + userProfile.getAccountURI()
123+
+ "> <" + LDIWO.sessionToken + "> \"" + sessionToken + "\"^^xsd:string . }";
124+
log.debug(query);
125+
126+
try {
127+
frameworkRdfStoreManager.execute(query, "json");
128+
} catch (Exception e) {
129+
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
130+
.build();
131+
}
132+
112133
JsonObject body = new JsonObject();
113134
body.addProperty("endpoint", "rest/session/" + sessionToken);
114-
return Response.ok(body.toString(), MediaType.APPLICATION_JSON).build();
135+
return Response.status(Response.Status.CREATED).entity(body.toString()).build();
115136
}
116137

117138
@GET
@@ -127,18 +148,43 @@ public Response post(@PathParam("sessionToken") String sessionToken, @Context Ur
127148
throws Exception {
128149

129150
log.info(sessionToken);
130-
log.debug(AuthorizedSessions.map.toString());
151+
String username = "";
152+
/*
153+
* retrieves form user that created that session and the rdfUser and
154+
* paswword for that user
155+
*/
156+
try {
157+
String query = "SELECT ?user FROM <" + sessionsGraph + "> WHERE { ?user " + " <"
158+
+ LDIWO.sessionToken + "> \"" + sessionToken + "\"^^xsd:string .}";
159+
log.debug(query);
160+
161+
String result = frameworkRdfStoreManager.execute(query, "json");
162+
log.debug(result);
163+
ObjectMapper mapper = new ObjectMapper();
164+
JsonNode rootNode = mapper.readTree(result);
165+
Iterator<JsonNode> bindingsIter = rootNode.path("results").path("bindings")
166+
.getElements();
131167

132-
String userLogin = AuthorizedSessions.map.get(sessionToken);
133-
log.debug(userLogin);
134-
if (userLogin == null) {
135-
return Response.status(Response.Status.UNAUTHORIZED).build();
168+
if (bindingsIter.hasNext()) {
169+
JsonNode bindingNode = bindingsIter.next();
170+
username = bindingNode.get("user").path("value").getTextValue();
171+
}
172+
173+
} catch (Exception e) {
174+
log.error(e);
175+
e.printStackTrace();
176+
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
177+
.build();
136178
}
179+
log.debug("user:" + username + "-");
180+
if (username.equals(""))
181+
return Response.status(Response.Status.NOT_FOUND).build();
182+
183+
ObjectPair<String, String> rdfStoreUser = frameworkUserManager.getRdfStoreUser(username);
137184

138185
// create a context with credentials
139-
String[] creds = userLogin.split(":");
140-
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(creds[0],
141-
creds[1]);
186+
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(rdfStoreUser
187+
.getFirst(), rdfStoreUser.getSecond());
142188
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
143189
credsProvider.setCredentials(AuthScope.ANY, credentials);
144190
HttpClientContext context = HttpClientContext.create();
@@ -170,4 +216,41 @@ public void write(OutputStream os) throws IOException, WebApplicationException {
170216
return Response.ok(stream).build();
171217

172218
}
219+
220+
@DELETE
221+
@Path("{sessionToken}")
222+
public Response delete(@PathParam("sessionToken") String sessionToken,
223+
@CookieParam(value = "user") Cookie userc, @CookieParam(value = "token") String token) {
224+
225+
/*
226+
* authenticates the user, throw exception if failed
227+
*/
228+
UserProfile userProfile;
229+
try {
230+
// authenticates the user, throw exception if fail
231+
userProfile = frameworkUserManager.validate(userc, token);
232+
if (userProfile == null)
233+
return Response.status(Response.Status.UNAUTHORIZED).entity("Invalid credentials")
234+
.build();
235+
log.info(" user: " + userProfile.getUsername());
236+
} catch (Exception e) {
237+
log.error(e);
238+
e.printStackTrace();
239+
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
240+
.build();
241+
}
242+
243+
String query = "DELETE FROM <http://generator.geoknow.eu/resource/sessionsGraph> {?s ?p ?o} "
244+
+ "WHERE { ?s ?p ?o . FILTER(str(?o) = \"" + sessionToken + "\") } ";
245+
log.debug(query);
246+
247+
try {
248+
log.info(frameworkRdfStoreManager.execute(query, "json"));
249+
} catch (Exception e) {
250+
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
251+
.build();
252+
}
253+
254+
return Response.ok().build();
255+
}
173256
}

src/main/java/setup/RDFStoreSetupManager.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ public void setUp(FrameworkConfiguration config, boolean reset) throws Exception
111111

112112
log.info("System Initialization ");
113113

114-
// create user
114+
// create framework RDF user
115115
userManager.createUser(config.getAuthSparqlUser(), config.getAuthSparqlPassword());
116116
userManager.setDefaultRdfPermissions(config.getAuthSparqlUser(), 3);
117117
userManager.grantRole(config.getAuthSparqlUser(), "SPARQL_UPDATE");
@@ -137,6 +137,7 @@ public void setUp(FrameworkConfiguration config, boolean reset) throws Exception
137137
frameworkRdfStoreManager.createGraph(config.getGroupsGraph());
138138
frameworkRdfStoreManager.createGraph(config.getInitialSettingsGraph());
139139
frameworkRdfStoreManager.createGraph(config.getJobsGraph());
140+
frameworkRdfStoreManager.createGraph(config.getAuthSessionsGraph());
140141

141142
// Make graphs accessible to framework user only
142143
userManager.setDefaultRdfPermissions("nobody", 0);
@@ -148,6 +149,8 @@ public void setUp(FrameworkConfiguration config, boolean reset) throws Exception
148149
userManager.setRdfGraphPermissions(config.getAuthSparqlUser(), config
149150
.getInitialSettingsGraph(), 3);
150151
userManager.setRdfGraphPermissions(config.getAuthSparqlUser(), config.getJobsGraph(), 3);
152+
userManager.setRdfGraphPermissions(config.getAuthSparqlUser(), config
153+
.getAuthSessionsGraph(), 3);
151154

152155
// settings model
153156
Model settingsModel = ModelFactory.createDefaultModel();
@@ -286,14 +289,15 @@ public void clear(FrameworkConfiguration config) throws Exception {
286289
rdfStoreManager.dropGraph(config.getGroupsGraph());
287290
rdfStoreManager.dropGraph(config.getInitialSettingsGraph());
288291
rdfStoreManager.dropGraph(config.getJobsGraph());
292+
rdfStoreManager.dropGraph(config.getAuthSessionsGraph());
289293

290294
// drop sparql user
291295
log.debug("Drop system SPARQL user");
292296
virtuosoUserManager.dropUser(config.getAuthSparqlUser());
293297
}
294298

295299
public boolean isSetUp() {
296-
log.info("Checking if " + initFile.getPath() + initFile.getName() + " exists");
300+
log.info("Checking if " + initFile.getPath() + " exists");
297301
return initFile.exists();
298302
}
299303
}

0 commit comments

Comments
 (0)