Search in sources :

Example 1 with NoUserException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException 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 NoUserException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException in project isaac-api by isaacphysics.

the class EventsFacade method createReservationsForGivenUsers.

/**
 * Add event reservations for the given users.
 *
 * @param request
 *            - so we can determine who is making the request
 * @param eventId
 *            - event id
 * @param userIds
 *            - the users to reserve spaces for
 * @return the list of bookings/reservations
 */
@POST
@Path("{event_id}/reservations")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add event reservations for the given users.")
public final Response createReservationsForGivenUsers(@Context final HttpServletRequest request, @PathParam("event_id") final String eventId, final List<Long> userIds) {
    RegisteredUserDTO reservingUser;
    IsaacEventPageDTO event;
    try {
        event = this.getRawEventDTOById(eventId);
    } catch (SegueDatabaseException | ContentManagerException e) {
        event = null;
    }
    if (null == event) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "No event found with this ID.").toResponse();
    }
    if (!EventBookingManager.eventAllowsGroupBookings(event)) {
        return new SegueErrorResponse(Status.FORBIDDEN, "This event does not accept group bookings.").toResponse();
    }
    List<RegisteredUserDTO> usersToReserve = Lists.newArrayList();
    try {
        reservingUser = userManager.getCurrentRegisteredUser(request);
        if (!Arrays.asList(Role.TEACHER, Role.EVENT_LEADER, Role.EVENT_MANAGER, Role.ADMIN).contains(reservingUser.getRole())) {
            return SegueErrorResponse.getIncorrectRoleResponse();
        }
        // Enforce permission
        for (Long userId : userIds) {
            RegisteredUserDTO userToReserve = userManager.getUserDTOById(userId);
            if (userAssociationManager.hasPermission(reservingUser, userToReserve)) {
                usersToReserve.add(userToReserve);
            } else {
                return new SegueErrorResponse(Status.FORBIDDEN, "You do not have permission to book or reserve some of these users onto this event.").toResponse();
            }
        }
        List<EventBookingDTO> bookings = bookingManager.requestReservations(event, usersToReserve, reservingUser);
        this.getLogManager().logEvent(reservingUser, request, SegueServerLogType.EVENT_RESERVATIONS_CREATED, ImmutableMap.of(EVENT_ID_FKEY_FIELDNAME, event.getId(), USER_ID_FKEY_FIELDNAME, reservingUser.getId(), USER_ID_LIST_FKEY_FIELDNAME, userIds.toArray(), BOOKING_STATUS_FIELDNAME, BookingStatus.RESERVED.toString()));
        return Response.ok(this.mapper.mapAsList(bookings, EventBookingDTO.class)).build();
    } catch (NoUserLoggedInException e) {
        return SegueErrorResponse.getNotLoggedInResponse();
    } catch (SegueDatabaseException e) {
        String errorMsg = "Database error occurred while trying to reserve space for a user onto an event.";
        log.error(errorMsg, e);
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, errorMsg).toResponse();
    } catch (EventIsFullException e) {
        return new SegueErrorResponse(Status.CONFLICT, "There are not enough spaces available for this event. Please try again with fewer users.").toResponse();
    } catch (EventGroupReservationLimitException e) {
        return new SegueErrorResponse(Status.CONFLICT, String.format("You can only request a maximum of %d student reservations for this event.", event.getGroupReservationLimit())).toResponse();
    } catch (EventDeadlineException e) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "The booking deadline for this event has passed. No more bookings or reservations are being accepted.").toResponse();
    } catch (DuplicateBookingException e) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "One of the users requested is already booked or reserved on this event. Unable to create a duplicate booking.").toResponse();
    } catch (NoUserException e) {
        return SegueErrorResponse.getResourceNotFoundResponse("Unable to locate one of the users specified.");
    }
}
Also used : EventIsFullException(uk.ac.cam.cl.dtg.isaac.api.managers.EventIsFullException) DuplicateBookingException(uk.ac.cam.cl.dtg.isaac.api.managers.DuplicateBookingException) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) EventBookingDTO(uk.ac.cam.cl.dtg.isaac.dto.eventbookings.EventBookingDTO) DetailedEventBookingDTO(uk.ac.cam.cl.dtg.isaac.dto.eventbookings.DetailedEventBookingDTO) NoUserLoggedInException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserLoggedInException) SegueErrorResponse(uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse) RegisteredUserDTO(uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO) EventDeadlineException(uk.ac.cam.cl.dtg.isaac.api.managers.EventDeadlineException) IsaacEventPageDTO(uk.ac.cam.cl.dtg.isaac.dto.IsaacEventPageDTO) EventGroupReservationLimitException(uk.ac.cam.cl.dtg.isaac.api.managers.EventGroupReservationLimitException) ContentManagerException(uk.ac.cam.cl.dtg.segue.dao.content.ContentManagerException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation)

Example 3 with NoUserException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException in project isaac-api by isaacphysics.

the class EventsFacade method cancelBooking.

/**
 * This function allows cancellation of a booking.
 *
 * @param request
 *            - so we can determine if the user is logged in
 * @param eventId
 *            - event id
 * @param userId
 *            - user id
 * @return the new booking
 */
@DELETE
@Path("{event_id}/bookings/{user_id}/cancel")
@Produces(MediaType.APPLICATION_JSON)
@GZIP
@ApiOperation(value = "Cancel a user's booking on an event.")
public final Response cancelBooking(@Context final HttpServletRequest request, @PathParam("event_id") final String eventId, @PathParam("user_id") final Long userId) {
    try {
        IsaacEventPageDTO event = getRawEventDTOById(eventId);
        RegisteredUserDTO userLoggedIn = this.userManager.getCurrentRegisteredUser(request);
        RegisteredUserDTO userOwningBooking;
        if (null == userId) {
            userOwningBooking = userLoggedIn;
        } else {
            userOwningBooking = this.userManager.getUserDTOById(userId);
        }
        if (event.getDate() != null && new Date().after(event.getDate())) {
            return new SegueErrorResponse(Status.BAD_REQUEST, "You cannot cancel a booking on an event that has already started.").toResponse();
        }
        // if the user id is null then it means they are changing their own booking.
        if (userId != null) {
            if (!(bookingManager.isUserAbleToManageEvent(userLoggedIn, event) || bookingManager.isReservationMadeByRequestingUser(userLoggedIn, userOwningBooking, event))) {
                return SegueErrorResponse.getIncorrectRoleResponse();
            }
        }
        Set<BookingStatus> cancelableStatuses = new HashSet<>(Arrays.asList(BookingStatus.CONFIRMED, BookingStatus.WAITING_LIST, BookingStatus.RESERVED));
        if (!bookingManager.hasBookingWithAnyOfStatuses(eventId, userOwningBooking.getId(), cancelableStatuses)) {
            return new SegueErrorResponse(Status.BAD_REQUEST, "User is not booked on this event.").toResponse();
        }
        bookingManager.cancelBooking(event, userOwningBooking);
        if (!userOwningBooking.equals(userLoggedIn)) {
            this.getLogManager().logEvent(userLoggedIn, request, SegueServerLogType.ADMIN_EVENT_BOOKING_CANCELLED, ImmutableMap.of(EVENT_ID_FKEY_FIELDNAME, event.getId(), USER_ID_FKEY_FIELDNAME, userOwningBooking.getId()));
        } else {
            this.getLogManager().logEvent(userLoggedIn, request, SegueServerLogType.EVENT_BOOKING_CANCELLED, ImmutableMap.of(EVENT_ID_FKEY_FIELDNAME, event.getId()));
        }
        return Response.noContent().build();
    } catch (NoUserLoggedInException e) {
        return SegueErrorResponse.getNotLoggedInResponse();
    } catch (SegueDatabaseException e) {
        String errorMsg = "Database error occurred while trying to delete an event booking.";
        log.error(errorMsg, e);
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, errorMsg).toResponse();
    } catch (ContentManagerException e) {
        log.error("Error during event request", e);
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Error locating the content you requested.").toResponse();
    } catch (NoUserException e) {
        return SegueErrorResponse.getResourceNotFoundResponse("Unable to locate user specified.");
    }
}
Also used : SegueErrorResponse(uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse) RegisteredUserDTO(uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) IsaacEventPageDTO(uk.ac.cam.cl.dtg.isaac.dto.IsaacEventPageDTO) BookingStatus(uk.ac.cam.cl.dtg.isaac.dos.eventbookings.BookingStatus) Date(java.util.Date) ContentManagerException(uk.ac.cam.cl.dtg.segue.dao.content.ContentManagerException) HashSet(java.util.HashSet) NoUserLoggedInException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserLoggedInException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) GZIP(org.jboss.resteasy.annotations.GZIP)

Example 4 with NoUserException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException in project isaac-api by isaacphysics.

the class EventsFacade method recordEventAttendance.

/**
 * Allow a staff user to record event attendance.
 *
 * @param request
 *            - so we can determine if the user is logged in
 * @param eventId
 *            - event booking containing updates, must contain primary id.
 * @param userId
 *            - the user to be promoted.
 * @param attended
 *            - boolean value representing whether the user was present, true, or absent, false.
 * @return the updated booking.
 */
@POST
@Path("{event_id}/bookings/{user_id}/record_attendance")
@Produces(MediaType.APPLICATION_JSON)
@GZIP
@ApiOperation(value = "Update the attendance status of a user for an event.")
public final Response recordEventAttendance(@Context final HttpServletRequest request, @PathParam("event_id") final String eventId, @PathParam("user_id") final Long userId, @QueryParam("attended") final Boolean attended) {
    try {
        RegisteredUserDTO currentUser = this.userManager.getCurrentRegisteredUser(request);
        RegisteredUserDTO userOfInterest = this.userManager.getUserDTOById(userId);
        IsaacEventPageDTO event = this.getAugmentedEventDTOById(request, eventId);
        if (!bookingManager.isUserAbleToManageEvent(currentUser, event)) {
            return SegueErrorResponse.getIncorrectRoleResponse();
        }
        EventBookingDTO eventBookingDTO = this.bookingManager.recordAttendance(event, userOfInterest, attended);
        this.getLogManager().logEvent(currentUser, request, SegueServerLogType.ADMIN_EVENT_ATTENDANCE_RECORDED, ImmutableMap.of(EVENT_ID_FKEY_FIELDNAME, event.getId(), USER_ID_FKEY_FIELDNAME, userId, ATTENDED_FIELDNAME, attended, EVENT_DATE_FIELDNAME, event.getDate(), EVENT_TAGS_FIELDNAME, event.getTags()));
        if (event.getTags().contains("teacher")) {
            this.userBadgeManager.updateBadge(userOfInterest, UserBadgeManager.Badge.TEACHER_CPD_EVENTS_ATTENDED, eventId);
        }
        return Response.ok(eventBookingDTO).build();
    } catch (NoUserLoggedInException e) {
        return SegueErrorResponse.getNotLoggedInResponse();
    } catch (SegueDatabaseException e) {
        String errorMsg = "Database error occurred while trying to update a event booking";
        log.error(errorMsg, e);
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, errorMsg).toResponse();
    } catch (ContentManagerException e) {
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Content Database error occurred while trying to retrieve event booking information.").toResponse();
    } catch (EventBookingUpdateException e) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "Unable to modify the booking", e).toResponse();
    } catch (NoUserException e) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "The user doesn't exist, so unable to book them onto an event", e).toResponse();
    }
}
Also used : SegueErrorResponse(uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse) RegisteredUserDTO(uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) IsaacEventPageDTO(uk.ac.cam.cl.dtg.isaac.dto.IsaacEventPageDTO) EventBookingDTO(uk.ac.cam.cl.dtg.isaac.dto.eventbookings.EventBookingDTO) DetailedEventBookingDTO(uk.ac.cam.cl.dtg.isaac.dto.eventbookings.DetailedEventBookingDTO) ContentManagerException(uk.ac.cam.cl.dtg.segue.dao.content.ContentManagerException) EventBookingUpdateException(uk.ac.cam.cl.dtg.isaac.api.managers.EventBookingUpdateException) 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) ApiOperation(io.swagger.annotations.ApiOperation) GZIP(org.jboss.resteasy.annotations.GZIP)

Example 5 with NoUserException

use of uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException in project isaac-api by isaacphysics.

the class EventsFacade method promoteBooking.

/**
 * Allow a staff user to promote a existing bookings to confirmed bookings.
 *
 * @param request
 *            - so we can determine if the user is logged in
 * @param eventId
 *            - event booking containing updates, must contain primary id.
 * @param userId
 *            - the user to be promoted.
 * @param additionalInformation
 *            - additional information to be stored with this booking e.g. dietary requirements.
 * @return the updated booking.
 */
@POST
@Path("{event_id}/bookings/{user_id}/promote")
@Produces(MediaType.APPLICATION_JSON)
@GZIP
@ApiOperation(value = "Move a user from an event waiting list, reservation or cancellation to a confirmed booking.")
public final Response promoteBooking(@Context final HttpServletRequest request, @PathParam("event_id") final String eventId, @PathParam("user_id") final Long userId, final Map<String, String> additionalInformation) {
    try {
        RegisteredUserDTO currentUser = this.userManager.getCurrentRegisteredUser(request);
        RegisteredUserDTO userOfInterest = this.userManager.getUserDTOById(userId);
        IsaacEventPageDTO event = this.getAugmentedEventDTOById(request, eventId);
        if (!bookingManager.isUserAbleToManageEvent(currentUser, event)) {
            return SegueErrorResponse.getIncorrectRoleResponse();
        }
        EventBookingDTO eventBookingDTO = this.bookingManager.promoteToConfirmedBooking(event, userOfInterest);
        this.getLogManager().logEvent(currentUser, request, SegueServerLogType.ADMIN_EVENT_WAITING_LIST_PROMOTION, ImmutableMap.of(EVENT_ID_FKEY_FIELDNAME, event.getId(), USER_ID_FKEY_FIELDNAME, userId));
        return Response.ok(eventBookingDTO).build();
    } catch (NoUserLoggedInException e) {
        return SegueErrorResponse.getNotLoggedInResponse();
    } catch (SegueDatabaseException e) {
        String errorMsg = "Database error occurred while trying to update a event booking";
        log.error(errorMsg, e);
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, errorMsg).toResponse();
    } catch (ContentManagerException e) {
        return new SegueErrorResponse(Status.INTERNAL_SERVER_ERROR, "Content Database error occurred while trying to retrieve event booking information.").toResponse();
    } catch (EventIsFullException e) {
        return new SegueErrorResponse(Status.CONFLICT, "This event is already full. Unable to book the user on to it.").toResponse();
    } catch (EventBookingUpdateException e) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "Unable to modify the booking", e).toResponse();
    } catch (NoUserException e) {
        return new SegueErrorResponse(Status.BAD_REQUEST, "The user doesn't exist, so unable to book them onto an event", e).toResponse();
    }
}
Also used : EventIsFullException(uk.ac.cam.cl.dtg.isaac.api.managers.EventIsFullException) SegueErrorResponse(uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse) RegisteredUserDTO(uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO) SegueDatabaseException(uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException) NoUserException(uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException) IsaacEventPageDTO(uk.ac.cam.cl.dtg.isaac.dto.IsaacEventPageDTO) EventBookingDTO(uk.ac.cam.cl.dtg.isaac.dto.eventbookings.EventBookingDTO) DetailedEventBookingDTO(uk.ac.cam.cl.dtg.isaac.dto.eventbookings.DetailedEventBookingDTO) ContentManagerException(uk.ac.cam.cl.dtg.segue.dao.content.ContentManagerException) EventBookingUpdateException(uk.ac.cam.cl.dtg.isaac.api.managers.EventBookingUpdateException) 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) ApiOperation(io.swagger.annotations.ApiOperation) GZIP(org.jboss.resteasy.annotations.GZIP)

Aggregations

NoUserException (uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserException)54 RegisteredUserDTO (uk.ac.cam.cl.dtg.isaac.dto.users.RegisteredUserDTO)42 SegueDatabaseException (uk.ac.cam.cl.dtg.segue.dao.SegueDatabaseException)41 Path (javax.ws.rs.Path)36 SegueErrorResponse (uk.ac.cam.cl.dtg.isaac.dto.SegueErrorResponse)36 Produces (javax.ws.rs.Produces)34 NoUserLoggedInException (uk.ac.cam.cl.dtg.segue.auth.exceptions.NoUserLoggedInException)32 ApiOperation (io.swagger.annotations.ApiOperation)31 GZIP (org.jboss.resteasy.annotations.GZIP)20 POST (javax.ws.rs.POST)19 ContentManagerException (uk.ac.cam.cl.dtg.segue.dao.content.ContentManagerException)16 Consumes (javax.ws.rs.Consumes)15 UserGroupDTO (uk.ac.cam.cl.dtg.isaac.dto.UserGroupDTO)12 GET (javax.ws.rs.GET)10 DetailedEventBookingDTO (uk.ac.cam.cl.dtg.isaac.dto.eventbookings.DetailedEventBookingDTO)10 DELETE (javax.ws.rs.DELETE)9 IsaacEventPageDTO (uk.ac.cam.cl.dtg.isaac.dto.IsaacEventPageDTO)9 Date (java.util.Date)8 EventBookingDTO (uk.ac.cam.cl.dtg.isaac.dto.eventbookings.EventBookingDTO)8 UserSummaryDTO (uk.ac.cam.cl.dtg.isaac.dto.users.UserSummaryDTO)8