Search in sources :

Example 81 with User

use of org.opencastproject.security.api.User in project opencast by opencast.

the class AuthenticationSuccessHandler method onAuthenticationSuccess.

/**
 * {@inheritDoc}
 *
 * @see org.springframework.security.web.authentication.AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
 */
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
    /* If the user originally attempted to access a specific URI other than /, but was forwarded to the login page,
     * redirect the user back to that initial URI. But only if the request target was a user interface any not some kind
     * of data. */
    HttpSession session = request.getSession();
    String initialRequestUri = (String) session.getAttribute(INITIAL_REQUEST_PATH);
    session.removeAttribute(INITIAL_REQUEST_PATH);
    if (initialRequestUri != null && initialRequestUri.toLowerCase().contains(".htm")) {
        response.sendRedirect(initialRequestUri);
        return;
    }
    // If there are no configured welcome pages, send the user to /
    if (welcomePages == null || welcomePages.isEmpty()) {
        response.sendRedirect(ROOT);
        return;
    }
    // Look for a welcome page for one of this user's roles
    User currentUser = securityService.getUser();
    for (Role role : currentUser.getRoles()) {
        if (welcomePages.containsKey(role.getName())) {
            response.sendRedirect(welcomePages.get(role.getName()));
            return;
        }
    }
    // None of the user's roles are in the welcome pages map, so try the wildcard. If that's not present, redirect to /
    response.sendRedirect(welcomePages.getOrDefault(WILDCARD, ROOT));
}
Also used : Role(org.opencastproject.security.api.Role) User(org.opencastproject.security.api.User) HttpSession(javax.servlet.http.HttpSession)

Example 82 with User

use of org.opencastproject.security.api.User in project opencast by opencast.

the class SecurityServiceSpringImpl method getUser.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.security.api.SecurityService#getUser()
 */
@Override
public User getUser() throws IllegalStateException {
    Organization org = getOrganization();
    if (org == null)
        throw new IllegalStateException("No organization is set in security context");
    User delegatedUser = delegatedUserHolder.get();
    if (delegatedUser != null) {
        return delegatedUser;
    }
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(org);
    if (auth != null) {
        Object principal = auth.getPrincipal();
        if ((principal != null) && (principal instanceof UserDetails)) {
            UserDetails userDetails = (UserDetails) principal;
            User user = null;
            // If user exists, fetch it from the userDirectory
            if (userDirectory != null) {
                user = userDirectory.loadUser(userDetails.getUsername());
                if (user == null) {
                    logger.debug("Authenticated user '{}' could not be found in any of the current UserProviders. Continuing anyway...", userDetails.getUsername());
                }
            } else {
                logger.debug("No UserDirectory was found when trying to search for user '{}'", userDetails.getUsername());
            }
            // Add the roles (authorities) in the security context
            Set<JaxbRole> roles = new HashSet<JaxbRole>();
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
            if (authorities != null) {
                for (GrantedAuthority ga : authorities) {
                    roles.add(new JaxbRole(ga.getAuthority(), jaxbOrganization));
                }
            }
            if (user == null) {
                // No user was found. Create one to hold the auth information from the security context
                user = new JaxbUser(userDetails.getUsername(), null, jaxbOrganization, roles);
            } else {
                // Combine the existing user with the roles in the security context
                user = JaxbUser.fromUser(user, roles);
            }
            // Save the user to retrieve it quicker the next time(s) this method is called (by this thread)
            delegatedUserHolder.set(user);
            return user;
        }
    }
    // Return the anonymous user by default
    return SecurityUtil.createAnonymousUser(jaxbOrganization);
}
Also used : JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) Organization(org.opencastproject.security.api.Organization) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) GrantedAuthority(org.springframework.security.core.GrantedAuthority) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) UserDetails(org.springframework.security.core.userdetails.UserDetails) JaxbRole(org.opencastproject.security.api.JaxbRole) Authentication(org.springframework.security.core.Authentication) HashSet(java.util.HashSet)

Example 83 with User

use of org.opencastproject.security.api.User in project opencast by opencast.

the class IndexServiceImplTest method setupSecurityService.

private SecurityService setupSecurityService(String username, String org) {
    // Setup Security Service, Organization and User
    Organization organization = EasyMock.createNiceMock(Organization.class);
    EasyMock.expect(organization.getId()).andReturn(org).anyTimes();
    EasyMock.replay(organization);
    User user = EasyMock.createMock(User.class);
    EasyMock.expect(user.getOrganization()).andReturn(organization).anyTimes();
    EasyMock.expect(user.getUsername()).andReturn(username);
    EasyMock.replay(user);
    SecurityService securityService = EasyMock.createMock(SecurityService.class);
    EasyMock.expect(securityService.getOrganization()).andReturn(organization).anyTimes();
    EasyMock.expect(securityService.getUser()).andReturn(user);
    EasyMock.replay(securityService);
    return securityService;
}
Also used : Organization(org.opencastproject.security.api.Organization) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) SecurityService(org.opencastproject.security.api.SecurityService)

Example 84 with User

use of org.opencastproject.security.api.User in project opencast by opencast.

the class AbstractEventEndpoint method createEventCommentReply.

@POST
@Path("{eventId}/comment/{commentId}/reply")
@RestQuery(name = "createeventcommentreply", description = "Creates an event comment reply", returnDescription = "The updated comment as JSON.", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "commentId", isRequired = true, description = "The comment identifier", type = STRING) }, restParameters = { @RestParameter(name = "text", isRequired = true, description = "The comment reply text", type = TEXT), @RestParameter(name = "resolved", isRequired = false, description = "Flag defining if this reply solve or not the comment.", type = BOOLEAN) }, reponses = { @RestResponse(responseCode = SC_NOT_FOUND, description = "The event or comment to extend with a reply has not been found."), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "If no text is set."), @RestResponse(responseCode = SC_OK, description = "The updated comment as JSON.") })
public Response createEventCommentReply(@PathParam("eventId") String eventId, @PathParam("commentId") long commentId, @FormParam("text") String text, @FormParam("resolved") Boolean resolved) throws Exception {
    if (StringUtils.isBlank(text))
        return Response.status(Status.BAD_REQUEST).build();
    Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
    if (optEvent.isNone())
        return notFound("Cannot find an event with id '%s'.", eventId);
    EventComment comment = null;
    try {
        comment = getEventCommentService().getComment(commentId);
        EventComment updatedComment;
        if (resolved != null && resolved) {
            // If the resolve flag is set to true, change to comment to resolved
            updatedComment = EventComment.create(comment.getId(), comment.getEventId(), comment.getOrganization(), comment.getText(), comment.getAuthor(), comment.getReason(), true, comment.getCreationDate(), new Date(), comment.getReplies());
        } else {
            updatedComment = comment;
        }
        User author = getSecurityService().getUser();
        EventCommentReply reply = EventCommentReply.create(Option.<Long>none(), text, author);
        updatedComment.addReply(reply);
        updatedComment = getEventCommentService().updateComment(updatedComment);
        List<EventComment> comments = getEventCommentService().getComments(eventId);
        getIndexService().updateCommentCatalog(optEvent.get(), comments);
        return Response.ok(updatedComment.toJson().toJson()).build();
    } catch (Exception e) {
        logger.warn("Could not create event comment reply on comment {}: {}", comment, ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(e);
    }
}
Also used : EventComment(org.opencastproject.event.comment.EventComment) User(org.opencastproject.security.api.User) WebApplicationException(javax.ws.rs.WebApplicationException) Event(org.opencastproject.index.service.impl.index.event.Event) Date(java.util.Date) EventCommentReply(org.opencastproject.event.comment.EventCommentReply) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 85 with User

use of org.opencastproject.security.api.User in project opencast by opencast.

the class AbstractEventEndpoint method createEventComment.

@POST
@Path("{eventId}/comment")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "createeventcomment", description = "Creates a comment related to the event given by the identifier", returnDescription = "The comment related to the event as JSON", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "text", isRequired = true, description = "The comment text", type = TEXT), @RestParameter(name = "resolved", isRequired = false, description = "The comment resolved status", type = RestParameter.Type.BOOLEAN), @RestParameter(name = "reason", isRequired = false, description = "The comment reason", type = STRING) }, reponses = { @RestResponse(description = "The comment has been created.", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "If no text ist set.", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) })
public Response createEventComment(@PathParam("eventId") String eventId, @FormParam("text") String text, @FormParam("reason") String reason, @FormParam("resolved") Boolean resolved) throws Exception {
    Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
    if (optEvent.isNone())
        return notFound("Cannot find an event with id '%s'.", eventId);
    if (StringUtils.isBlank(text))
        return Response.status(Status.BAD_REQUEST).build();
    User author = getSecurityService().getUser();
    try {
        EventComment createdComment = EventComment.create(Option.<Long>none(), eventId, getSecurityService().getOrganization().getId(), text, author, reason, BooleanUtils.toBoolean(reason));
        createdComment = getEventCommentService().updateComment(createdComment);
        List<EventComment> comments = getEventCommentService().getComments(eventId);
        getIndexService().updateCommentCatalog(optEvent.get(), comments);
        return Response.created(getCommentUrl(eventId, createdComment.getId().get())).entity(createdComment.toJson().toJson()).build();
    } catch (Exception e) {
        logger.error("Unable to create a comment on the event {}: {}", eventId, ExceptionUtils.getStackTrace(e));
        throw new WebApplicationException(e);
    }
}
Also used : EventComment(org.opencastproject.event.comment.EventComment) User(org.opencastproject.security.api.User) WebApplicationException(javax.ws.rs.WebApplicationException) Event(org.opencastproject.index.service.impl.index.event.Event) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

User (org.opencastproject.security.api.User)156 Organization (org.opencastproject.security.api.Organization)61 JaxbUser (org.opencastproject.security.api.JaxbUser)60 JaxbRole (org.opencastproject.security.api.JaxbRole)49 DefaultOrganization (org.opencastproject.security.api.DefaultOrganization)44 SecurityService (org.opencastproject.security.api.SecurityService)43 NotFoundException (org.opencastproject.util.NotFoundException)32 Before (org.junit.Before)31 Test (org.junit.Test)27 ArrayList (java.util.ArrayList)26 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)24 JaxbOrganization (org.opencastproject.security.api.JaxbOrganization)23 AccessControlList (org.opencastproject.security.api.AccessControlList)21 Role (org.opencastproject.security.api.Role)21 UserDirectoryService (org.opencastproject.security.api.UserDirectoryService)21 HashSet (java.util.HashSet)20 OrganizationDirectoryService (org.opencastproject.security.api.OrganizationDirectoryService)18 JpaUser (org.opencastproject.security.impl.jpa.JpaUser)17 IOException (java.io.IOException)16 MediaPackage (org.opencastproject.mediapackage.MediaPackage)16