use of uk.ac.cam.cl.dtg.isaac.dos.users.AnonymousUser in project isaac-api by isaacphysics.
the class UserAccountManager method getAnonymousUserDO.
/**
* Retrieves anonymous user information if it is available.
*
* @param request
* - request containing session information.
* @return An anonymous user containing any anonymous question attempts (which could be none)
*/
private AnonymousUser getAnonymousUserDO(final HttpServletRequest request) throws SegueDatabaseException {
AnonymousUser user;
// no session exists so create one.
if (request.getSession().getAttribute(ANONYMOUS_USER) == null) {
String anonymousUserId = getAnonymousUserIdFromRequest(request);
user = new AnonymousUser(anonymousUserId);
user.setDateCreated(new Date());
// add the user reference to the session
request.getSession().setAttribute(ANONYMOUS_USER, anonymousUserId);
this.temporaryUserCache.storeAnonymousUser(user);
} else {
// reuse existing one
if (request.getSession().getAttribute(ANONYMOUS_USER) instanceof String) {
String userId = (String) request.getSession().getAttribute(ANONYMOUS_USER);
user = this.temporaryUserCache.getById(userId);
if (null == user) {
// the session must have expired. Create a new user and run this method again.
// this probably won't happen often as the session expiry and the cache should be timed correctly.
request.getSession().removeAttribute(ANONYMOUS_USER);
log.warn("Anonymous user session expired so creating a" + " new one - this should not happen often if cache settings are correct.");
return this.getAnonymousUserDO(request);
}
} else {
// this means that someone has put the wrong type in to the session variable.
throw new ClassCastException("Unable to get AnonymousUser from session.");
}
}
return user;
}
use of uk.ac.cam.cl.dtg.isaac.dos.users.AnonymousUser in project isaac-api by isaacphysics.
the class UserManagerTest method authenticateCallback_checkNewUserIsAuthenticated_createInternalUserAccount.
/**
* Check that a new (unseen) user is registered when seen with 3rd party authenticator.
*
* @throws Exception
* -
*/
@Test
public final void authenticateCallback_checkNewUserIsAuthenticated_createInternalUserAccount() throws Exception {
IOAuth2Authenticator dummyAuth = createMock(FacebookAuthenticator.class);
UserAccountManager userManager = buildTestUserManager(AuthenticationProvider.TEST, dummyAuth);
UserAuthenticationManager authManager = buildTestAuthenticationManager(AuthenticationProvider.TEST, dummyAuth);
// method param setup for method under test
HttpSession dummySession = createMock(HttpSession.class);
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
String someDomain = "http://www.somedomain.com/";
String someClientId = "someClientId";
String someAuthCode = "someAuthCode";
String someState = "someState";
StringBuffer sb = new StringBuffer(someDomain + "?state=" + someState + "&code=" + someAuthCode);
String validQueryStringFromProvider = "client_id=" + someClientId + "&redirect_uri=" + someDomain;
String fullResponseUrlFromProvider = someDomain + "?state=" + someState + "&code=" + someAuthCode + "?client_id=" + someClientId + "&redirect_uri=" + someDomain;
String someProviderGeneratedLookupValue = "MYPROVIDERREF";
String someProviderUniqueUserId = "USER-1";
Long someSegueUserId = 533L;
String someSegueAnonymousUserId = "9284723987anonymous83924923";
AnonymousUser au = new AnonymousUser();
au.setSessionId(someSegueAnonymousUserId);
expect(this.dummyUserCache.storeAnonymousUser(au)).andReturn(au).atLeastOnce();
expect(this.dummyUserCache.getById(au.getSessionId())).andReturn(au).atLeastOnce();
AnonymousUserDTO someAnonymousUserDTO = new AnonymousUserDTO();
someAnonymousUserDTO.setSessionId(someSegueAnonymousUserId);
String validOAuthProvider = "test";
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 500);
String validDateString = sdf.format(calendar.getTime());
expect(request.getSession()).andReturn(dummySession).atLeastOnce();
// empty as not logged in.
Cookie[] cookieWithoutSessionInfo = {};
expect(request.getCookies()).andReturn(cookieWithoutSessionInfo).times(2);
// session
expect(dummySession.getAttribute(Constants.ANONYMOUS_USER)).andReturn(someSegueAnonymousUserId).atLeastOnce();
// id
// Mock CSRF checks
expect(dummySession.getAttribute(Constants.STATE_PARAM_NAME)).andReturn(CSRF_TEST_VALUE).atLeastOnce();
expect(request.getParameter(Constants.STATE_PARAM_NAME)).andReturn(CSRF_TEST_VALUE).atLeastOnce();
// Mock URL params extract stuff
expect(request.getQueryString()).andReturn(validQueryStringFromProvider).atLeastOnce();
expect(request.getRequestURL()).andReturn(sb);
// Mock extract auth code call
expect(dummyAuth.extractAuthCode(fullResponseUrlFromProvider)).andReturn(someAuthCode);
// Mock exchange code for token call
expect(dummyAuth.exchangeCode(someAuthCode)).andReturn(someProviderGeneratedLookupValue).atLeastOnce();
expect(((IFederatedAuthenticator) dummyAuth).getAuthenticationProvider()).andReturn(AuthenticationProvider.TEST).atLeastOnce();
// User object back from provider
UserFromAuthProvider providerUser = new UserFromAuthProvider(someProviderUniqueUserId, "TestFirstName", "TestLastName", "test@test.com", EmailVerificationStatus.VERIFIED, Role.STUDENT, new Date(), Gender.MALE);
// Mock get User Information from provider call
expect(((IFederatedAuthenticator) dummyAuth).getUserInfo(someProviderGeneratedLookupValue)).andReturn(providerUser).atLeastOnce();
// Expect this to be a new user and to register them (i.e. return null
// from database)
expect(dummyDatabase.getByLinkedAccount(AuthenticationProvider.TEST, someProviderUniqueUserId)).andReturn(null).atLeastOnce();
RegisteredUser mappedUser = new RegisteredUser(null, "TestFirstName", "testLastName", "test@test.com", Role.STUDENT, new Date(), Gender.MALE, new Date(), null, null, null, null);
mappedUser.setSessionToken(0);
expect(dummyDatabase.getAuthenticationProvidersByUsers(Collections.singletonList(mappedUser))).andReturn(new HashMap<RegisteredUser, List<AuthenticationProvider>>() {
{
put(mappedUser, Lists.newArrayList(AuthenticationProvider.GOOGLE));
}
}).atLeastOnce();
expect(dummyDatabase.getSegueAccountExistenceByUsers(Collections.singletonList(mappedUser))).andReturn(ImmutableMap.of(mappedUser, false)).atLeastOnce();
RegisteredUserDTO mappedUserDTO = new RegisteredUserDTO();
expect(dummyMapper.map(providerUser, RegisteredUser.class)).andReturn(mappedUser).atLeastOnce();
expect(dummyMapper.map(mappedUser, RegisteredUserDTO.class)).andReturn(mappedUserDTO).atLeastOnce();
expect(dummyMapper.map(au, AnonymousUserDTO.class)).andReturn(someAnonymousUserDTO).anyTimes();
// handle duplicate account check.
expect(dummyDatabase.getByEmail(providerUser.getEmail())).andReturn(null).once();
// A main part of the test is to check the below call happens
expect(dummyDatabase.registerNewUserWithProvider(mappedUser, AuthenticationProvider.TEST, someProviderUniqueUserId)).andReturn(mappedUser).atLeastOnce();
mappedUser.setId(someSegueUserId);
expect(dummyDatabase.getById(someSegueUserId)).andReturn(mappedUser);
Map<String, String> sessionInformation = getSessionInformationAsAMap(authManager, someSegueUserId.toString(), validDateString, mappedUser.getSessionToken());
Cookie[] cookieWithSessionInfo = getCookieArray(sessionInformation);
// Expect a session to be created
response.addCookie(cookieWithSessionInfo[0]);
expectLastCall().once();
expect(request.getCookies()).andReturn(cookieWithSessionInfo).anyTimes();
dummyQuestionDatabase.mergeAnonymousQuestionAttemptsIntoRegisteredUser(someAnonymousUserDTO, mappedUserDTO);
expectLastCall().once();
expect(dummyQueue.getEmailTemplateDTO("email-template-registration-confirmation-federated")).andReturn(new EmailTemplateDTO()).once();
dummyQueue.sendTemplatedEmailToUser(anyObject(), anyObject(), anyObject(), anyObject());
expectLastCall().once();
replay(dummySession, request, dummyAuth, dummyQuestionDatabase, dummyMapper, dummyDatabase, dummyLocalAuth, dummyQueue, dummyUserCache);
// Act
RegisteredUserDTO u = userManager.authenticateCallback(request, response, validOAuthProvider, false);
// Assert
verify(dummySession, request, dummyAuth, dummyQuestionDatabase);
assertTrue(u instanceof RegisteredUserDTO);
}
use of uk.ac.cam.cl.dtg.isaac.dos.users.AnonymousUser in project isaac-api by isaacphysics.
the class UserAccountManager method logUserIn.
/**
* Logs the user in and creates the signed sessions.
*
* @param request
* - for the session to be attached
* @param response
* - for the session to be attached.
* @param user
* - the user who is being logged in.
* @param rememberMe
* Boolean to indicate whether or not this cookie expiry duration should be long or short
* @throws SegueDatabaseException - if there is a problem with the database.
* @return the DTO version of the user.
*/
private RegisteredUserDTO logUserIn(final HttpServletRequest request, final HttpServletResponse response, final RegisteredUser user, final boolean rememberMe) throws SegueDatabaseException {
AnonymousUser anonymousUser = this.getAnonymousUserDO(request);
if (anonymousUser != null) {
log.debug(String.format("Anonymous User (%s) located during login - need to merge question information", anonymousUser.getSessionId()));
}
// now we want to clean up any data generated by the user while they weren't logged in.
mergeAnonymousUserWithRegisteredUser(anonymousUser, user);
return this.convertUserDOToUserDTO(this.userAuthenticationManager.createUserSession(request, response, user, rememberMe));
}
use of uk.ac.cam.cl.dtg.isaac.dos.users.AnonymousUser in project isaac-api by isaacphysics.
the class PgAnonymousUsers method getById.
@Override
public AnonymousUser getById(final String id) throws SegueDatabaseException {
String query = "SELECT * FROM temporary_user_store WHERE id = ?";
try (Connection conn = database.getDatabaseConnection();
PreparedStatement pst = conn.prepareStatement(query)) {
pst.setString(1, id);
try (ResultSet result = pst.executeQuery()) {
// are there any results
if (!result.isBeforeFirst()) {
return null;
}
result.next();
AnonymousUser userToReturn = new AnonymousUser(result.getString("id"), result.getTimestamp("created"), result.getTimestamp("last_updated"));
updateLastUpdatedDate(userToReturn);
return userToReturn;
}
} catch (SQLException e) {
throw new SegueDatabaseException("Postgres exception while trying to get anonymous user", e);
}
}
Aggregations