Finalized security, distinguish between internal and external users, etc

This commit is contained in:
Nikolaos Laskaris 2017-10-20 13:03:55 +03:00
parent 08a4abc9ff
commit 2364d10c0e
10 changed files with 97 additions and 23 deletions

View File

@ -9,7 +9,10 @@ public interface UserInfoDao extends Dao<UserInfo, UUID> {
public UserInfo getByIdAndMail(String identification, String email); public UserInfo getByIdAndMail(String identification, String email);
public UserInfo getByMail(String email);
public UserInfo getByAuthenticationId(String authentication); public UserInfo getByAuthenticationId(String authentication);
public UserInfo getByUsername(String username);
} }

View File

@ -50,4 +50,38 @@ public class UserInfoDaoImpl extends JpaDao<UserInfo, UUID> implements UserInfoD
} }
@Override
public UserInfo getByMail(String email) {
String queryString = "FROM UserInfo userInfo where userInfo.email = :email";
TypedQuery<UserInfo> typedQuery = entityManager.createQuery(queryString, UserInfo.class);
typedQuery.setParameter("email", email);
try {
return typedQuery.getSingleResult();
}
catch(Exception ex) { //no need to distinguish between exceptions for the moment
return null;
}
}
@Override
public UserInfo getByUsername(String username) {
String queryString = "select ui from UserInfo ui join UserAuth ui.authentication ua where ua.username=:username";
TypedQuery<UserInfo> typedQuery = entityManager.createQuery(queryString, UserInfo.class);
typedQuery.setParameter("username", username);
try {
return typedQuery.getSingleResult();
}
catch(Exception ex) { //no need to distinguish between exceptions for the moment
return null;
}
}
} }

View File

@ -241,6 +241,7 @@ public class DMPs {
dMPDao.delete(d); dMPDao.delete(d);
return ResponseEntity.status(HttpStatus.CREATED).body("DELETED!"); return ResponseEntity.status(HttpStatus.CREATED).body("DELETED!");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not Delete DMP!\""); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not Delete DMP!\"");
} }
@ -249,8 +250,6 @@ public class DMPs {
// OLD ONES, USED BY THE EMBEDDED (simple) UI OF THIS SERVICE // OLD ONES, USED BY THE EMBEDDED (simple) UI OF THIS SERVICE
@RequestMapping(method = RequestMethod.POST, value = { "/setDMPByForm" }, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces="text/plain") @RequestMapping(method = RequestMethod.POST, value = { "/setDMPByForm" }, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces="text/plain")
public @ResponseBody ResponseEntity<Object> setDMPByForm(@RequestBody MultiValueMap<String,String> formData) { public @ResponseBody ResponseEntity<Object> setDMPByForm(@RequestBody MultiValueMap<String,String> formData) {

View File

@ -4,6 +4,7 @@ import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors;
import javax.transaction.Transactional; import javax.transaction.Transactional;
@ -45,6 +46,7 @@ import entities.Dataset;
import entities.DatasetProfile; import entities.DatasetProfile;
import entities.DatasetProfileRuleset; import entities.DatasetProfileRuleset;
import entities.DatasetProfileViewstyle; import entities.DatasetProfileViewstyle;
import entities.Organisation;
import entities.Project; import entities.Project;
import helpers.Transformers; import helpers.Transformers;
import responses.RestResponse; import responses.RestResponse;
@ -101,13 +103,25 @@ public class Datasets {
*/ */
@RequestMapping(method = RequestMethod.GET, value = { "/getAllDatasets" }) @RequestMapping(method = RequestMethod.GET, value = { "/getAllDatasets" })
public @ResponseBody ResponseEntity<Object> getAllDatasets(){ public @ResponseBody ResponseEntity<Object> getAllDatasets(){
try { try {
List<Dataset> allDatasets = datasetDao.getAll(); List<Dataset> allDatasets = datasetDao.getAll();
return ResponseEntity.status(HttpStatus.OK).body(new ObjectMapper().writeValueAsString(allDatasets));
//sorry for that, spring-jersey serialisation has issues when performed on tables, so -> custom
List<String> datasetsStrL = allDatasets.parallelStream().map((datasetObj) -> {
try {
return objectMapper.writeValueAsString(datasetObj);
} catch (JsonProcessingException e) {
return "";
}
}).collect(Collectors.toList());
return new ResponseEntity<Object>("["+String.join(",", datasetsStrL)+"]", HttpStatus.OK);
} }
catch(Exception ex) { catch(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Serialization issue: "+ex.getMessage()); return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }

View File

@ -154,6 +154,7 @@ public class Projects {
projectDao.delete(p); projectDao.delete(p);
return ResponseEntity.status(HttpStatus.CREATED).body("{\"msg\":\"Deleted Project entity!\"}"); return ResponseEntity.status(HttpStatus.CREATED).body("{\"msg\":\"Deleted Project entity!\"}");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not Delete Project!\"}"); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("{\"msg\":\"Could not Delete Project!\"}");
} }

View File

@ -44,18 +44,14 @@ public class CustomAuthenticationProvider implements AuthenticationProvider {
else else
throw new AuthenticationServiceException("The appropriate http headers have not been set. Please check!"); throw new AuthenticationServiceException("The appropriate http headers have not been set. Please check!");
UserInfo userInfo;
try { try {
tokenValidator.validateToken(token); userInfo = tokenValidator.validateToken(token);
} catch (NonValidTokenException e) { } catch (NonValidTokenException e) {
System.out.println("Could not validate a user by his token! Reason: "+e.getMessage()); System.out.println("Could not validate a user by his token! Reason: "+e.getMessage());
throw new AuthenticationServiceException("Token validation failed - Not a valid token"); throw new AuthenticationServiceException("Token validation failed - Not a valid token");
} }
//store to database if new
// UserInfo existingUserInfo = userInfoDao.getByKey(userInfo.getId(), userInfo.getEmail());
// if(existingUserInfo == null)
// userInfoDao.create(userInfo);
// if reached this point, authentication is ok, so return just an instance with whatever. // if reached this point, authentication is ok, so return just an instance with whatever.
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new ArrayList<>()); return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), new ArrayList<>());

View File

@ -3,8 +3,11 @@ package security.validators;
import java.io.IOException; import java.io.IOException;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date;
import java.util.List; import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
@ -12,6 +15,7 @@ import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.json.jackson2.JacksonFactory;
import dao.entities.UserInfoDao;
import entities.UserInfo; import entities.UserInfo;
import exceptions.NonValidTokenException; import exceptions.NonValidTokenException;
@ -20,9 +24,12 @@ public class GoogleTokenValidator implements TokenValidator {
private static final JacksonFactory jacksonFactory = new JacksonFactory(); private static final JacksonFactory jacksonFactory = new JacksonFactory();
private static final HttpTransport transport = new NetHttpTransport(); private static final HttpTransport transport = new NetHttpTransport();
@Autowired private UserInfoDao userInfoDao;
private static final List<String> clientIDs = Arrays.asList( private static final List<String> clientIDs = Arrays.asList(
"1010962018903-glegmqudqtl1lub0150vacopbu06lgsg.apps.googleusercontent.com", "1010962018903-glegmqudqtl1lub0150vacopbu06lgsg.apps.googleusercontent.com",
"" "1010962018903-glegmqudqtl1lub0150vacopbu06lgsg.apps.googleusercontent.com"
); );
private GoogleIdTokenVerifier verifier = null; private GoogleIdTokenVerifier verifier = null;
@ -38,7 +45,7 @@ public class GoogleTokenValidator implements TokenValidator {
@Override @Override
public void validateToken(String token) throws NonValidTokenException { public UserInfo validateToken(String token) throws NonValidTokenException {
GoogleIdToken idToken = null; GoogleIdToken idToken = null;
try { try {
@ -57,15 +64,29 @@ public class GoogleTokenValidator implements TokenValidator {
if(idToken == null) { if(idToken == null) {
throw new NonValidTokenException("Not a valid token"); throw new NonValidTokenException("Not a valid token");
} }
// else {
// Payload payload = idToken.getPayload(); Payload payload = idToken.getPayload();
// UserInfo userInfo = new UserInfo(payload.getSubject(), payload.getEmail(),
// payload.getEmailVerified(), (String)payload.get("name"), (String)payload.get("picture"), UserInfo userInfo = userInfoDao.getByMail(payload.getEmail());
// (String)payload.get("locale"), (String)payload.get("family_name"), (String)payload.get("given_name"), "");
// System.out.println(userInfo.toString()); if(userInfo == null) { //means not existing in db, so create one
// return userInfo; userInfo = new UserInfo();
// } userInfo.setName((String)payload.get("name"));
userInfo.setVerified_email(payload.getEmailVerified());
userInfo.setEmail(payload.getEmail());
userInfo.setCreated(new Date());
userInfo.setLastloggedin(new Date());
userInfo.setAuthorization_level(new Short("1"));
userInfo.setUsertype(new Short("1"));
userInfo = userInfoDao.create(userInfo);
}
else {
userInfo.setLastloggedin(new Date());
userInfo = userInfoDao.update(userInfo);
}
return userInfo;
} }

View File

@ -2,18 +2,22 @@ package security.validators;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import dao.entities.UserInfoDao;
import entities.UserInfo;
import exceptions.NonValidTokenException; import exceptions.NonValidTokenException;
import security.TokenSessionManager; import security.TokenSessionManager;
public class NativeTokenValidator implements TokenValidator { public class NativeTokenValidator implements TokenValidator {
@Autowired private TokenSessionManager tokenSessionManager; @Autowired private TokenSessionManager tokenSessionManager;
@Autowired private UserInfoDao userInfoDao;
@Override @Override
public void validateToken(String token) throws NonValidTokenException { public UserInfo validateToken(String token) throws NonValidTokenException {
String tokenUser = tokenSessionManager.getUser(token); String tokenUser = tokenSessionManager.getUser(token);
if(tokenUser==null || tokenUser.isEmpty()) if(tokenUser==null || tokenUser.isEmpty())
throw new NonValidTokenException("Login session has expired! Need to login again!"); throw new NonValidTokenException("Login session has expired! Need to login again!");
return userInfoDao.getByUsername(tokenUser);
} }

View File

@ -1,9 +1,10 @@
package security.validators; package security.validators;
import entities.UserInfo;
import exceptions.NonValidTokenException; import exceptions.NonValidTokenException;
public interface TokenValidator { public interface TokenValidator {
public void validateToken(String token) throws NonValidTokenException; public UserInfo validateToken(String token) throws NonValidTokenException;
} }

View File

@ -68,6 +68,7 @@
<context-param> <context-param>
<param-name>contextConfigLocation</param-name> <param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/spring-security.xml</param-value> <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/spring-security.xml</param-value>
<!-- <param-value>/WEB-INF/applicationContext.xml</param-value> -->
</context-param> </context-param>
<session-config> <session-config>
<session-timeout>30</session-timeout> <session-timeout>30</session-timeout>