Search in sources :

Example 1 with EmailVerificationStatus

use of uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus in project isaac-api by isaacphysics.

the class FacebookAuthenticator method getUserInfo.

@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference) throws NoUserException, AuthenticatorSecurityException {
    Credential credentials = credentialStore.get(internalProviderReference);
    if (verifyAccessTokenIsValid(credentials)) {
        log.debug("Successful Verification of access token with provider.");
    } else {
        log.error("Unable to verify access token - it could be an indication of fraud.");
        throw new AuthenticatorSecurityException("Access token is invalid - the client id returned by the identity provider does not match ours.");
    }
    FacebookUser userInfo = null;
    try {
        GenericUrl url = new GenericUrl(USER_INFO_URL + "?fields=" + requestedFields);
        url.set("access_token", credentials.getAccessToken());
        userInfo = JsonLoader.load(inputStreamToString(url.toURL().openStream()), FacebookUser.class, true);
        log.debug("Retrieved User info from Facebook");
    } catch (IOException e) {
        log.error("An IO error occurred while trying to retrieve user information: " + e);
    }
    if (userInfo != null && userInfo.getId() != null) {
        EmailVerificationStatus emailStatus = userInfo.isVerified() ? EmailVerificationStatus.VERIFIED : EmailVerificationStatus.NOT_VERIFIED;
        String email = userInfo.getEmail();
        if (null == email) {
            email = userInfo.getId() + "-facebook";
            emailStatus = EmailVerificationStatus.DELIVERY_FAILED;
            log.warn("No email address provided by Facebook! Using (" + email + ") instead");
        }
        return new UserFromAuthProvider(userInfo.getId(), userInfo.getFirstName(), userInfo.getLastName(), email, emailStatus, null, null, null);
    } else {
        throw new NoUserException("No user could be created from provider details!");
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) AuthenticatorSecurityException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticatorSecurityException) UserFromAuthProvider(uk.ac.cam.cl.dtg.isaac.dos.users.UserFromAuthProvider) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) EmailVerificationStatus(uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus) FacebookUser(uk.ac.cam.cl.dtg.isaac.dos.users.FacebookUser)

Example 2 with EmailVerificationStatus

use of uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus in project isaac-api by isaacphysics.

the class UserAccountManager method processEmailVerification.

/**
 * processEmailVerification.
 * @param userId
 *            - the user id
 *
 * @param token
 *            - token used to verify email address
 *
 * @return - whether the token is valid or not
 * @throws SegueDatabaseException
 *             - exception if token cannot be validated
 * @throws InvalidTokenException - if something is wrong with the token provided
 * @throws NoUserException - if the user does not exist.
 */
public RegisteredUserDTO processEmailVerification(final Long userId, final String token) throws SegueDatabaseException, InvalidTokenException, NoUserException {
    IPasswordAuthenticator authenticator = (IPasswordAuthenticator) this.registeredAuthProviders.get(AuthenticationProvider.SEGUE);
    RegisteredUser user = this.findUserById(userId);
    if (null == user) {
        log.warn(String.format("Received an invalid email token request for (%s)", userId));
        throw new NoUserException("No user found with this userId!");
    }
    if (!userId.equals(user.getId())) {
        log.warn(String.format("Received an invalid email token request by (%s) - provided bad userid", user.getId()));
        throw new InvalidTokenException();
    }
    EmailVerificationStatus evStatus = user.getEmailVerificationStatus();
    if (evStatus == EmailVerificationStatus.VERIFIED && user.getEmail().equals(user.getEmailToVerify())) {
        log.warn(String.format("Received a duplicate email verification request for (%s) - already verified", user.getEmail()));
        return this.convertUserDOToUserDTO(user);
    }
    if (authenticator.isValidEmailVerificationToken(user, token)) {
        user.setEmailVerificationStatus(EmailVerificationStatus.VERIFIED);
        user.setEmail(user.getEmailToVerify());
        user.setEmailVerificationToken(null);
        user.setEmailToVerify(null);
        user.setLastUpdated(new Date());
        // Save user
        RegisteredUser createOrUpdateUser = this.database.createOrUpdateUser(user);
        log.info(String.format("Email verification for user (%s) has completed successfully.", createOrUpdateUser.getId()));
        return this.convertUserDOToUserDTO(createOrUpdateUser);
    } else {
        log.warn(String.format("Received an invalid email verification token for (%s) - invalid token", userId));
        throw new InvalidTokenException();
    }
}
Also used : IPasswordAuthenticator(uk.ac.cam.cl.dtg.segue.auth.IPasswordAuthenticator) EmailVerificationStatus(uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus) RegisteredUser(uk.ac.cam.cl.dtg.isaac.dos.users.RegisteredUser) Date(java.util.Date)

Example 3 with EmailVerificationStatus

use of uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus in project isaac-api by isaacphysics.

the class AdminFacade method modifyUsersEmailVerificationStatus.

/**
 * This method will allow users' email verification status to be changed en-mass.
 *
 * @param request
 *            - to help determine access rights.
 * @param emailVerificationStatus
 *            - new emailVerificationStatus.
 * @param emails
 *            - a list of user emails that need to be changed
 * @param checkEmailsExistBeforeApplying
 *            - tells us whether to check whether all emails exist before applying
 * @return Success shown by returning an ok response
 */
@POST
@Path("/users/change_email_verification_status/{emailVerificationStatus}/{checkEmailsExistBeforeApplying}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public synchronized Response modifyUsersEmailVerificationStatus(@Context final HttpServletRequest request, @PathParam("emailVerificationStatus") final String emailVerificationStatus, @PathParam("checkEmailsExistBeforeApplying") final boolean checkEmailsExistBeforeApplying, final List<String> emails) {
    try {
        RegisteredUserDTO requestingUser = userManager.getCurrentRegisteredUser(request);
        if (!isUserAnAdminOrEventManager(userManager, requestingUser)) {
            return new SegueErrorResponse(Status.FORBIDDEN, "You must be staff to access this endpoint.").toResponse();
        }
        EmailVerificationStatus requestedEmailVerificationStatus = EmailVerificationStatus.valueOf(emailVerificationStatus);
        if (emails.contains(requestingUser.getEmail())) {
            return new SegueErrorResponse(Status.FORBIDDEN, "Aborted - you cannot modify yourself.").toResponse();
        }
        if (checkEmailsExistBeforeApplying) {
            // fail fast - break if any of the users given already have the role they are being elevated to
            for (String email : emails) {
                RegisteredUserDTO user = this.userManager.getUserDTOByEmail(email);
                if (null == user) {
                    log.error(String.format("No user could be found with email (%s)", email));
                    throw new NoUserException("No user found with this email.");
                }
            }
        }
        for (String email : emails) {
            this.userManager.updateUserEmailVerificationStatus(email, requestedEmailVerificationStatus);
        }
    } catch (NoUserLoggedInException e) {
        return SegueErrorResponse.getNotLoggedInResponse();
    } catch (NoUserException e) {
        log.error("NoUserException when attempting to change users verification status.", e);
        return new SegueErrorResponse(Status.BAD_REQUEST, "One or more users could not be found").toResponse();
    } catch (SegueDatabaseException e) {
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Could not save new email verification status to the database").toResponse();
    }
    return Response.ok().build();
}
Also used : SegueErrorResponse(uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse) RegisteredUserDTO(uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) EmailVerificationStatus(uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus) NoUserLoggedInException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserLoggedInException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 4 with EmailVerificationStatus

use of uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus in project isaac-api by isaacphysics.

the class GoogleAuthenticator method getUserInfo.

@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference) throws NoUserException, AuthenticatorSecurityException {
    Credential credentials = credentialStore.getIfPresent(internalProviderReference);
    if (verifyAccessTokenIsValid(credentials)) {
        log.debug("Successful Verification of access token with provider.");
    } else {
        log.error("Unable to verify access token - it could be an indication of fraud.");
        throw new AuthenticatorSecurityException("Access token is invalid - the client id returned by the identity provider does not match ours.");
    }
    Oauth2 userInfoService = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credentials).setApplicationName(Constants.APPLICATION_NAME).build();
    Userinfo userInfo = null;
    try {
        userInfo = userInfoService.userinfo().get().execute();
        log.debug("Retrieved User info from google: " + userInfo.toPrettyString());
    } catch (IOException e) {
        log.error("An IO error occurred while trying to retrieve user information: " + e);
    }
    if (userInfo != null && userInfo.getId() != null) {
        EmailVerificationStatus emailStatus = userInfo.isVerifiedEmail() ? EmailVerificationStatus.VERIFIED : EmailVerificationStatus.NOT_VERIFIED;
        String email = userInfo.getEmail();
        if (null == email) {
            email = userInfo.getId() + "-google";
            emailStatus = EmailVerificationStatus.DELIVERY_FAILED;
            log.warn("No email address provided by Google! Using (" + email + ") instead");
        }
        return new UserFromAuthProvider(userInfo.getId(), userInfo.getGivenName(), userInfo.getFamilyName(), email, emailStatus, null, null, null);
    } else {
        throw new NoUserException("No user could be created from provider details!");
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) AuthenticatorSecurityException(uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticatorSecurityException) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) UserFromAuthProvider(uk.ac.cam.cl.dtg.isaac.dos.users.UserFromAuthProvider) Oauth2(com.google.api.services.oauth2.Oauth2) CacheBuilder(com.google.common.cache.CacheBuilder) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) Userinfo(com.google.api.services.oauth2.model.Userinfo) IOException(java.io.IOException) EmailVerificationStatus(uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory)

Example 5 with EmailVerificationStatus

use of uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus in project isaac-api by isaacphysics.

the class TwitterAuthenticator method getUserInfo.

@Override
public synchronized UserFromAuthProvider getUserInfo(final String internalProviderReference) throws NoUserException, IOException {
    Credential credentials = credentialStore.get(internalProviderReference);
    twitter.setOAuthAccessToken(new AccessToken(credentials.getAccessToken(), credentials.getRefreshToken()));
    try {
        twitter4j.User userInfo = twitter.verifyCredentials();
        if (userInfo != null) {
            // Using twitter id for email field is a hack to avoid a duplicate
            // exception due to null email field. Alistair and Steve dislike this...
            String givenName = null;
            String familyName = null;
            if (userInfo.getName() != null) {
                String[] names = userInfo.getName().split(" ");
                if (names.length > 0) {
                    givenName = names[0];
                }
                if (names.length > 1) {
                    familyName = names[1];
                }
            }
            EmailVerificationStatus emailStatus = EmailVerificationStatus.NOT_VERIFIED;
            String email = userInfo.getEmail();
            if (null == email) {
                email = userInfo.getId() + "-twitter";
                emailStatus = EmailVerificationStatus.DELIVERY_FAILED;
                log.warn("No email address provided by Twitter! Using (" + email + ") instead");
            }
            return new UserFromAuthProvider(String.valueOf(userInfo.getId()), givenName, familyName, email, emailStatus, null, null, null);
        } else {
            throw new NoUserException("No user could be created from provider details!");
        }
    } catch (TwitterException e) {
        throw new IOException(e.getMessage());
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) AccessToken(twitter4j.auth.AccessToken) UserFromAuthProvider(uk.ac.cam.cl.dtg.isaac.dos.users.UserFromAuthProvider) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) EmailVerificationStatus(uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus) IOException(java.io.IOException) TwitterException(twitter4j.TwitterException)

Aggregations

EmailVerificationStatus (uk.ac.cam.cl.dtg.isaac.dos.users.EmailVerificationStatus)5 NoUserException (uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException)4 Credential (com.google.api.client.auth.oauth2.Credential)3 IOException (java.io.IOException)3 UserFromAuthProvider (uk.ac.cam.cl.dtg.isaac.dos.users.UserFromAuthProvider)3 AuthenticatorSecurityException (uk.ac.cam.cl.dtg.segue.auth.exceptions.AuthenticatorSecurityException)2 GenericUrl (com.google.api.client.http.GenericUrl)1 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)1 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)1 Oauth2 (com.google.api.services.oauth2.Oauth2)1 Userinfo (com.google.api.services.oauth2.model.Userinfo)1 CacheBuilder (com.google.common.cache.CacheBuilder)1 Date (java.util.Date)1 Consumes (javax.ws.rs.Consumes)1 POST (javax.ws.rs.POST)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 TwitterException (twitter4j.TwitterException)1 AccessToken (twitter4j.auth.AccessToken)1 FacebookUser (uk.ac.cam.cl.dtg.isaac.dos.users.FacebookUser)1