public Resource next() {
   Principal nextPrincipal = principals.nextPrincipal();
   try {
     ResourceResolver resourceResolver = parent.getResourceResolver();
     if (resourceResolver != null) {
       Session session = resourceResolver.adaptTo(Session.class);
       if (session != null) {
         UserManager userManager = AccessControlUtil.getUserManager(session);
         if (userManager != null) {
           Authorizable authorizable = userManager.getAuthorizable(nextPrincipal.getName());
           if (authorizable != null) {
             String path;
             if (authorizable.isGroup()) {
               path = SYSTEM_USER_MANAGER_GROUP_PREFIX + nextPrincipal.getName();
             } else {
               path = SYSTEM_USER_MANAGER_USER_PREFIX + nextPrincipal.getName();
             }
             return new SakaiAuthorizableResource(authorizable, resourceResolver, path);
           }
         }
       }
     }
   } catch (RepositoryException re) {
     log.error("Exception while looking up authorizable resource.", re);
   }
   return null;
 }
 @RequestMapping(value = "/follow", method = RequestMethod.GET)
 public String follow(final HttpServletRequest request, Principal principal, Model model) {
   List<Follower> followers = userService.getfollowlist(principal.getName());
   model.addAttribute("cuser", principal.getName());
   model.addAttribute("followlist", followers);
   return "follow";
 }
 @Secured({"ROLE_ADMIN", "ROLE_SURVEY_ADMIN"})
 @RequestMapping(value = "/{id}", produces = "text/html")
 public String show(
     @PathVariable("id") Long id,
     HttpServletRequest httpServletRequest,
     Principal principal,
     Model uiModel) {
   log.info("show(): id=" + id);
   try {
     String login = principal.getName();
     User user = userService.user_findByLogin(login);
     // SurveyDefinitionPage surveyDefinitionPage =
     // surveySettingsService.surveyDefinitionPage_findById(id);
     // Check if the user is authorized
     if (!securityService.userIsAuthorizedToManageSurvey(id, user)) {
       log.warn(
           "Unauthorized access to url path "
               + httpServletRequest.getPathInfo()
               + " attempted by user login:"******"from IP:"
               + httpServletRequest.getLocalAddr());
       return "accessDenied";
     }
     uiModel.addAttribute("question", surveySettingsService.question_findById(id));
     uiModel.addAttribute("itemId", id);
     return "settings/questions/show";
   } catch (Exception e) {
     log.error(e.getMessage(), e);
     throw (new RuntimeException(e));
   }
 }
  @RequestMapping(
      value = "/access/{id}",
      method = RequestMethod.GET,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public String getAccessTokenById(@PathVariable("id") Long id, ModelMap m, Principal p) {

    OAuth2AccessTokenEntity token = tokenService.getAccessTokenById(id);

    if (token == null) {
      logger.error("getToken failed; token not found: " + id);
      m.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND);
      m.put(
          JsonErrorView.ERROR_MESSAGE,
          "The requested token with id " + id + " could not be found.");
      return JsonErrorView.VIEWNAME;
    } else if (!token.getAuthenticationHolder().getAuthentication().getName().equals(p.getName())) {
      logger.error("getToken failed; token does not belong to principal " + p.getName());
      m.put(HttpCodeView.CODE, HttpStatus.FORBIDDEN);
      m.put(JsonErrorView.ERROR_MESSAGE, "You do not have permission to view this token");
      return JsonErrorView.VIEWNAME;
    } else {
      m.put(JsonEntityView.ENTITY, token);
      return TokenApiView.VIEWNAME;
    }
  }
Esempio n. 5
0
  private User authenticate(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException {
    // First try to validate the principial if passed from the servlet engine
    Principal principal = request.getUserPrincipal();

    if (principal instanceof XmldbPrincipal) {
      String username = ((XmldbPrincipal) principal).getName();
      String password = ((XmldbPrincipal) principal).getPassword();

      LOG.info("Validating Principle: " + principal.getName());
      User user = pool.getSecurityManager().getUser(username);

      if (user != null) {
        if (password.equalsIgnoreCase(user.getPassword())) {
          LOG.info("Valid User: "******"Password invalid for user: "******"User not found: " + principal.getName());
      }
    }

    String auth = request.getHeader("Authorization");
    if (auth == null && defaultUser != null) {
      return defaultUser;
    }
    return authenticator.authenticate(request, response);
  }
  @RequestMapping(value = "/newtransemployee/op1", method = RequestMethod.POST)
  public ModelAndView newTransEmployeePost(
      @ModelAttribute @Valid User user,
      BindingResult result,
      final RedirectAttributes attributes,
      Principal principal)
      throws BankDeactivatedException {
    System.out.println("INSIDE trans manager post Controller for new employee .............");
    OneTimePassword otp = new OneTimePassword();
    String message;
    ModelAndView mav = new ModelAndView();
    try {
      System.out.println("\n Inside Employee signup post controller");
      if (result.hasErrors()) {
        // return new ModelAndView("hr/newhremployee", "signupemployee",employee);
        // return savedMav;
        // return new ModelAndView("hr/manager/manager","signupemployee",user);
        message = "Validation Errors observed.Please go back and fill valid information";
        mav.addObject("message", message);
        mav.setViewName("signup/saveData");
        return mav;
        // return new ModelAndView("signup/saveData", "signupemployee",user);
      }

      mav.setViewName("signup/saveData");
      message =
          "Congratulations..!! Your request has been approved. Please ask the user to check the email and login";
      user.setDepartment("TM");
      user.setRole("ROLE_TRANSACTION_EMPLOYEE");
      user.setCreatedBy(principal.getName());
      Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
      String password = otp.getPassword();
      String hashedPassword = passwordEncoder.encodePassword(otp.getPassword(), null);

      transManager.insertValidUser(user, hashedPassword, principal.getName());
      enManager.sendPassword(user, password);
      mav.addObject("message", message);
      mav.addObject("username", principal.getName());
      return mav;
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      if (e instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException) {
        message = "Username already Exists.Choose a different username";
        mav.addObject("message", message);
        mav.setViewName("signup/saveData");
        mav.addObject("username", principal.getName());
        return mav;
      } else if (e instanceof BankDeactivatedException) {
        throw new BankDeactivatedException(e.getMessage());
      } else {
        message = "Error in saving your data.Please try again";
        mav.addObject("message", message);
        mav.setViewName("signup/saveData");
        mav.addObject("username", principal.getName());
        return mav;
      }
    }
  }
 /**
  * Get organization info
  *
  * @param principal
  * @return organization object
  */
 @RequestMapping(value = "/orginfo", method = RequestMethod.GET)
 public Organization getOrganization(Principal principal) {
   if (!Account.findRole(principal.getName()).equals("1")) {
     logger.error("[getOrganization] org: " + principal.getName() + " permission denied");
     throw new PermissionErrorException();
   }
   return accountService.getOrganization(Account.findMobile(principal.getName()));
 }
  private void createUserPrincipal() throws IOException {
    File testFile = createPasswordFile(0, 0);
    loadPasswordFile(testFile);

    _database.createPrincipal(_principal, TEST_PASSWORD_CHARS);
    Principal newPrincipal = _database.getUser(TEST_USERNAME);
    assertNotNull(newPrincipal);
    assertEquals(_principal.getName(), newPrincipal.getName());
  }
  /**
   * Updates the user's Shibboleth session with authentication information. If no session exists a
   * new one will be created.
   *
   * @param loginContext current login context
   * @param authenticationSubject subject created from the authentication method
   * @param authenticationMethod the method used to authenticate the subject
   * @param authenticationInstant the time of authentication
   * @param httpRequest current HTTP request
   * @param httpResponse current HTTP response
   */
  protected void updateUserSession(
      LoginContext loginContext,
      Subject authenticationSubject,
      String authenticationMethod,
      DateTime authenticationInstant,
      HttpServletRequest httpRequest,
      HttpServletResponse httpResponse) {
    Principal authenticationPrincipal = authenticationSubject.getPrincipals().iterator().next();
    LOG.debug("Updating session information for principal {}", authenticationPrincipal.getName());

    Session idpSession = (Session) httpRequest.getAttribute(Session.HTTP_SESSION_BINDING_ATTRIBUTE);
    if (idpSession == null) {
      LOG.debug("Creating shibboleth session for principal {}", authenticationPrincipal.getName());
      idpSession = (Session) sessionManager.createSession();
      loginContext.setSessionID(idpSession.getSessionID());
      addSessionCookie(httpRequest, httpResponse, idpSession);
    }

    // Merge the information in the current session subject with the information from the
    // login handler subject
    idpSession.setSubject(mergeSubjects(idpSession.getSubject(), authenticationSubject));

    // Check if an existing authentication method with no updated timestamp was used (i.e. SSO
    // occurred);
    // if not record the new information
    AuthenticationMethodInformation authnMethodInfo =
        idpSession.getAuthenticationMethods().get(authenticationMethod);
    if (authnMethodInfo == null || authenticationInstant != null) {
      LOG.debug(
          "Recording authentication and service information in Shibboleth session for principal: {}",
          authenticationPrincipal.getName());
      LoginHandler loginHandler =
          handlerManager.getLoginHandlers().get(loginContext.getAttemptedAuthnMethod());
      DateTime authnInstant = authenticationInstant;
      if (authnInstant == null) {
        authnInstant = new DateTime();
      }
      authnMethodInfo =
          new AuthenticationMethodInformationImpl(
              idpSession.getSubject(),
              authenticationPrincipal,
              authenticationMethod,
              authnInstant,
              loginHandler.getAuthenticationDuration());
    }

    loginContext.setAuthenticationMethodInformation(authnMethodInfo);
    idpSession
        .getAuthenticationMethods()
        .put(authnMethodInfo.getAuthenticationMethod(), authnMethodInfo);
    sessionManager.indexSession(idpSession, idpSession.getPrincipalName());

    ServiceInformation serviceInfo =
        new ServiceInformationImpl(
            loginContext.getRelyingPartyId(), new DateTime(), authnMethodInfo);
    idpSession.getServicesInformation().put(serviceInfo.getEntityID(), serviceInfo);
  }
 private void checkResourceOwner(String user, Principal principal) {
   if (principal instanceof OAuth2Authentication) {
     OAuth2Authentication authentication = (OAuth2Authentication) principal;
     if (!authentication.isClientOnly() && !user.equals(principal.getName())) {
       throw new AccessDeniedException(
           String.format(
               "User '%s' cannot obtain tokens for user '%s'", principal.getName(), user));
     }
   }
 }
 /**
  * Update organization
  *
  * @param principal
  * @param postclass
  * @return Boolean f
  */
 @RequestMapping(value = "/orginfo", method = RequestMethod.PUT)
 public ResponseResult updateOrganization(
     Principal principal, @RequestBody Organization postclass) {
   if (!Account.findRole(principal.getName()).equals("1")) {
     logger.error("[updateOrganization] org: " + principal.getName() + " permission denied");
     throw new PermissionErrorException();
   }
   return accountService.updateOrganizationInfo(
       Account.findMobile(principal.getName()), postclass);
 }
Esempio n. 12
0
 /**
  * This Sample PrivilegedAction performs the following operations:
  *
  * <ul>
  *   <li>Access the System property, <i>java.home</i>
  *   <li>Access the System property, <i>user.home</i>
  *   <li>Access the file, <i>foo.txt</i>
  * </ul>
  *
  * @return <code>null</code> in all cases.
  * @exception SecurityException if the caller does not have permission to perform the operations
  *     listed above.
  */
 public Object run() {
   Subject currentSubject = Subject.getSubject(AccessController.getContext());
   Iterator iter = currentSubject.getPrincipals().iterator();
   String dir = "";
   Principal p = null;
   while (iter.hasNext()) {
     p = (Principal) iter.next();
     dir = dir + p.getName() + " ";
   }
   if ((p.getName()).equals("Admin")) {
     String choice;
     while (!(choice = System.console().readLine("choice : ")).equals("exit")) {
       if (choice.equals("add")) {
         String directory = System.console().readLine("directory : ");
         String filename = System.console().readLine("name : ");
         String content = System.console().readLine("content : ");
         try {
           BufferedWriter bw =
               new BufferedWriter(
                   new FileWriter("sample/db/" + directory + "/" + filename + ".txt"));
           bw.write(content);
           bw.close();
           System.out.println(filename + ".txt generated.");
         } catch (Exception e) {
           System.out.println(e.toString());
           continue;
         }
       } else if (choice.equals("rm")) {
         try {
           String filename = System.console().readLine("name : ");
           File f = new File(searchMovie(dir, filename));
           if (f.exists()) {
             f.delete();
             System.out.println(filename + ".txt deleted.");
           }
         } catch (Exception e) {
           System.out.println(e.toString());
           continue;
         }
       } else if (choice.equals("read")) {
         String filename = System.console().readLine("Movie to watch : ");
         promptUser(dir, filename, p);
       } else {
         System.out.println("Invalid selection ( add, rm, read, exit )");
       }
     }
   } else {
     String filename;
     while (!(filename = System.console().readLine("Movie to watch : ")).equals("exit")) {
       promptUser(dir, filename, p);
     }
   }
   return null;
 }
Esempio n. 13
0
 @RequestMapping(value = "/events/{id}/prices/update", method = POST)
 public ValidationResult updatePrices(
     @PathVariable("id") int id,
     @RequestBody EventModification eventModification,
     Errors errors,
     Principal principal) {
   Event event = eventManager.getSingleEventById(id, principal.getName());
   return validateEventPrices(Optional.of(event), eventModification, errors)
       .ifSuccess(
           () -> eventManager.updateEventPrices(event, eventModification, principal.getName()));
 }
Esempio n. 14
0
 @Override
 @RolesAllowed({"AppTwo", "Intern"})
 public String invokeSecured(String text) {
   Principal caller = context.getCallerPrincipal();
   LOGGER.info("Secured invocation [" + caller.getName() + "] " + text);
   LOGGER.info(
       "Is in Role AppTwo="
           + context.isCallerInRole("AppTwo")
           + " Intern="
           + context.isCallerInRole("Intern"));
   return "app2[" + caller.getName() + "]@" + getJBossNodeName();
 }
  /**
   * @see
   *     org.apache.portals.bridges.velocity.GenericVelocityPortlet#processAction(javax.portlet.ActionRequest,
   *     javax.portlet.ActionResponse)
   */
  public void processAction(ActionRequest request, ActionResponse actionResponse)
      throws PortletException, IOException {

    String action = request.getParameter(Settings.PARAM_ACTION);
    if (action == null) {
      action = "";
    }

    PortletSession session = request.getPortletSession();

    if (action.equalsIgnoreCase("doOpenPartner")) {
      DisplayTreeNode partnerRoot = (DisplayTreeNode) session.getAttribute("partnerRoot");
      if (partnerRoot != null) {
        DisplayTreeNode node = partnerRoot.getChild(request.getParameter("id"));
        node.setOpen(true);
        if (node.get("checked") != null) {
          Iterator it = node.getChildren().iterator();
          while (it.hasNext()) {
            DisplayTreeNode child = (DisplayTreeNode) it.next();
            child.put("checked", "true");
          }
        }
      }
    } else if (action.equalsIgnoreCase("doClosePartner")) {
      DisplayTreeNode partnerRoot = (DisplayTreeNode) session.getAttribute("partnerRoot");
      if (partnerRoot != null) {
        DisplayTreeNode node = partnerRoot.getChild(request.getParameter("id"));
        node.setOpen(false);
      }
    } else if (action.equalsIgnoreCase("doOriginalSettings")) {
      Principal principal = request.getUserPrincipal();
      IngridPersistencePrefs.setPref(
          principal.getName(), IngridPersistencePrefs.SEARCH_PARTNER, "");
      DisplayTreeNode partnerRoot = (DisplayTreeNode) session.getAttribute("partnerRoot");
      Iterator it = partnerRoot.getChildren().iterator();
      while (it.hasNext()) {
        DisplayTreeNode partnerNode = (DisplayTreeNode) it.next();
        partnerNode.setOpen(false);
        Iterator it2 = partnerNode.getChildren().iterator();
        while (it2.hasNext()) {
          DisplayTreeNode providerNode = (DisplayTreeNode) it2.next();
          providerNode.remove("checked");
        }
      }
    } else {
      // Zur Suchanfrage hinzufuegen
      DisplayTreeNode partnerRoot = (DisplayTreeNode) session.getAttribute("partnerRoot");
      String resultQuery = UtilsSearch.processSearchPartner("", partnerRoot, request);
      Principal principal = request.getUserPrincipal();
      IngridPersistencePrefs.setPref(
          principal.getName(), IngridPersistencePrefs.SEARCH_PARTNER, resultQuery);
    }
  }
 public String isValidUserJSON(
     String username,
     String password,
     String memberOfGroup,
     List<String> returnGroups,
     XWikiContext context) {
   String resultJSON = getResultJSON(null, false, "access_denied", null, context);
   if (validationAllowed(context)) {
     Principal principal = null;
     try {
       String login =
           getCelementsweb(context)
               .getUsernameForUserData(
                   username,
                   context
                       .getWiki()
                       .getXWikiPreference(
                           OldCoreClasses.XWIKI_PREFERENCES_CELLOGIN_PROPERTY,
                           "loginname",
                           context),
                   context);
       principal = context.getWiki().getAuthService().authenticate(login, password, context);
     } catch (XWikiException e) {
       mLogger.error("DENYING access: Exception while authenticating.", e);
     }
     if (principal != null) {
       mLogger.debug("Authentication successful, now checking group");
       if (context.getWiki().getUser(principal.getName(), context).isUserInGroup(memberOfGroup)) {
         mLogger.debug("Group matched requirement, now checking if account is active.");
         try {
           if (checkActive(principal.getName(), context) == 1) {
             mLogger.debug("GRANTING access to " + principal.getName() + "!");
             resultJSON = getResultJSON(username, true, null, returnGroups, context);
           } else {
             mLogger.warn("DENYING access: account '" + username + "' is inactive.");
             resultJSON = getResultJSON(null, false, "useraccount_inactive", null, context);
           }
         } catch (XWikiException e) {
           mLogger.error("DENYING access: exception while checking if account is " + "active");
           resultJSON = getResultJSON(null, false, "useraccount_inactive", null, context);
         }
       } else {
         mLogger.warn("DENYING access: user is not in group '" + memberOfGroup + "'.");
         resultJSON = getResultJSON(null, false, "user_not_in_group", null, context);
       }
     } else {
       mLogger.warn("DENYING access: authentication failed");
       resultJSON = getResultJSON(null, false, "wrong_username_password", null, context);
     }
   }
   return resultJSON;
 }
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    Principal principal = request.getUserPrincipal();
    System.out.println("in prehandle");
    if (principal != null) {
      System.out.println("name is " + principal.getName());
      HttpSession session = request.getSession();
      session.setAttribute("user", principal.getName());
    }

    return true;
  }
 private Backend getBackend(CoreSession session) {
   if (session == null) {
     return null;
   }
   Principal principal = session.getPrincipal();
   if (principal == null || StringUtils.isEmpty(principal.getName())) {
     return null;
   }
   String principalName = principal.getName();
   WISession wiSession = SessionCacheHolder.getInstance().getCache().get(principalName);
   wiSession.setAttribute(WISession.CORESESSION_KEY, session);
   return new PluggableBackendFactory().getBackend(wiSession);
 }
Esempio n. 19
0
 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
     throws IOException, ServletException {
   // cast to the types I want to use
   HttpServletRequest request = (HttpServletRequest) req;
   HttpServletResponse response = (HttpServletResponse) resp;
   HttpSession session = request.getSession(true);
   Principal principal = request.getUserPrincipal();
   if (principal != null) {
     log.debug("username set:  " + principal.getName());
     HistoryInterceptor.setUserName(principal.getName());
     session.setAttribute("username", principal.getName());
     session.setAttribute("isPowerUser", checkIfPowerGroup(request));
   }
   chain.doFilter(request, response);
 }
  public void generate() throws SAXException, ProcessingException {
    if (log.isDebugEnabled()) log.debug("begin generate");
    contentHandler.startDocument();
    Document doc = XercesHelper.getNewDocument();
    Element root = doc.createElement("authentication");
    doc.appendChild(root);
    try {
      LoginContext lc = new LoginContext(jaasRealm, new InternalCallbackHandler());
      lc.login();
      Subject s = lc.getSubject();
      if (log.isDebugEnabled()) log.debug("Subject is: " + s.getPrincipals().toString());
      Element idElement = doc.createElement("ID");
      root.appendChild(idElement);

      Iterator it = s.getPrincipals(java.security.Principal.class).iterator();
      while (it.hasNext()) {
        Principal prp = (Principal) it.next();
        if (prp.getName().equalsIgnoreCase("Roles")) {
          Element roles = doc.createElement("roles");
          root.appendChild(roles);
          Group grp = (Group) prp;
          Enumeration member = grp.members();
          while (member.hasMoreElements()) {
            Principal sg = (Principal) member.nextElement();
            Element role = doc.createElement("role");
            roles.appendChild(role);
            Text txt = doc.createTextNode(sg.getName());
            role.appendChild(txt);
          }
        } else {
          Node nde = doc.createTextNode(prp.getName());
          idElement.appendChild(nde);
        }
      }
      lc.logout();
    } catch (Exception exe) {
      log.warn("Could not login user \"" + userid + "\"");
    } finally {
      try {
        DOMStreamer ds = new DOMStreamer(contentHandler);
        ds.stream(doc.getDocumentElement());
        contentHandler.endDocument();
      } catch (Exception exe) {
        log.error("Error streaming to dom", exe);
      }
      if (log.isDebugEnabled()) log.debug("end generate");
    }
  }
  @Override
  public int verify(String identifier, char[] secret) throws IllegalArgumentException {
    XWikiContext xwikiContext = Utils.getXWikiContext(this.componentManager);
    XWiki xwiki = Utils.getXWiki(this.componentManager);

    try {
      Principal principal =
          (secret == null)
              ? null
              : xwiki.getAuthService().authenticate(identifier, new String(secret), xwikiContext);
      if (principal != null) {
        String xwikiUser = principal.getName();

        xwikiContext.setUser(xwikiUser);

        this.context
            .getLogger()
            .log(Level.FINE, String.format("Authenticated as '%s'.", identifier));

        return RESULT_VALID;
      }
    } catch (XWikiException e) {
      this.context.getLogger().log(Level.WARNING, "Exception occurred while authenticating.", e);
    }

    this.context
        .getLogger()
        .log(Level.WARNING, String.format("Cannot authenticate '%s'.", identifier));

    return RESULT_INVALID;
  }
Esempio n. 22
0
 public String getUsername() {
   Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
   if (principal == null) {
     return null;
   }
   return principal.getName();
 }
 public boolean isAuthenticatedUser() {
   Principal p = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
   if (p != null) {
     return StringUtil.equals(getId(), p.getName());
   }
   return false;
 }
Esempio n. 24
0
  protected boolean matchGroupPrincipal(List<Principal> groupPrincipals, String userRole) {
    boolean res = false;

    {
      if (groupPrincipals != null) {
        if (userRole != null) {
          for (Principal groupPrincipal : groupPrincipals) {
            if (groupPrincipal instanceof DistinguishedNamePrincipal) {
              DistinguishedNamePrincipal p = (DistinguishedNamePrincipal) groupPrincipal;

              res = matchGroupPrincipal(p, userRole);
            } else {
              if (groupPrincipal instanceof CommonNamePrincipal) {
                CommonNamePrincipal p = (CommonNamePrincipal) groupPrincipal;

                res = matchGroupPrincipal(p, userRole);
              } else {
                String name = groupPrincipal.getName();
                if (name.equals(userRole)) {
                  res = true;
                }
              }
            }

            if (res) // if a match has been found...
            {
              break; // stop loop
            }
          }
        }
      }
    }

    return res;
  }
Esempio n. 25
0
  // posting edited comment
  @RequestMapping(
      value = "/posts/{postId:\\d+}/comments/{commentId:\\d+}/edit",
      method = RequestMethod.POST)
  public String onPostCommentEdit(
      @PathVariable long postId,
      @PathVariable long commentId,
      Model model,
      Principal principal,
      @Valid Comment editedComment,
      BindingResult result) {

    Comment oldComment = commentService.findById(commentId);
    Post post = postService.findById(postId);
    if (oldComment != null
        && post != null
        && post.getPostId() == oldComment.getPost().getPostId()) {
      if (result.hasErrors()) {
        model.addAttribute("logged_user", principal.getName());
        model.addAttribute("post", post);
        model.addAttribute("comments", commentService.findAllCommentsOfPost(postId));
        return "comment_edit";
      } else {
        commentService.merge(oldComment, editedComment);
        return "redirect:/posts/" + postId + "/comments";
      }
    } else return "404";
  }
  @Factory(value = "isInsidePersonalWorkspace", scope = ScopeType.EVENT)
  public boolean isShowingPersonalWorkspace() {
    if (!initialized) {
      initialize();
    }

    // NXP-9813 : navigating to a tab different than Documents should not change
    // the value for showingPersonalWorkspace
    if (mainTabsActions.isOnMainTab(DOCUMENT_MANAGEMENT_ACTION)) {
      DocumentModel currentDoc = navigationContext.getCurrentDocument();

      if (currentDoc == null || currentDoc.getPath().segmentCount() < 2) {
        return false;
      }

      String rootChild = currentDoc.getPath().segment(1);
      String wsName = currentDoc.getPath().segment(2);
      showingPersonalWorkspace =
          rootChild != null
              && rootChild.startsWith(UserWorkspaceConstants.USERS_PERSONAL_WORKSPACES_ROOT)
              && wsName != null
              && wsName.equals(currentUser.getName());
    }
    return showingPersonalWorkspace;
  }
Esempio n. 27
0
 @RequestMapping(value = "account/current", method = RequestMethod.GET)
 @ResponseStatus(value = HttpStatus.OK)
 @ResponseBody
 public Account accounts(Principal principal) {
   Assert.notNull(principal);
   return accountRepository.findByEmail(principal.getName());
 }
Esempio n. 28
0
 @Secured(value = {"ROLE_USER", "ROLE_ADMIN", "ROLE_MANAGER"})
 @RequestMapping(method = RequestMethod.GET, value = "profile-pic")
 public @ResponseBody FileSystemResource getFile(
     @RequestParam(required = false, value = "user") String userid,
     Principal principal,
     HttpSession session)
     throws IOException {
   if (documentFolder.exists()) {
     String uuid;
     if (userid != null) uuid = userid;
     else {
       PipUser user = PipUser.findPipUsersByEmailEquals(principal.getName()).getSingleResult();
       uuid = user.getUuid();
     }
     File folder = new File(documentFolder.getFile(), "user-data/" + uuid);
     File file;
     if (!uuid.isEmpty() && folder.exists() && folder.listFiles().length > 0)
       file = folder.listFiles()[0];
     else {
       file =
           new ServletContextResource(session.getServletContext(), "/images/profile.jpg")
               .getFile();
     }
     return new FileSystemResource(file);
   }
   return null;
 }
Esempio n. 29
0
  @Secured(value = {"ROLE_ADMIN", "ROLE_MANAGER"})
  @RequestMapping(method = RequestMethod.POST)
  public @ResponseBody void createUser(@RequestBody UserDto dto, Principal principal) {
    PipUser user = new PipUser();
    user.setEmail(dto.getEmail());
    Set<OrganisazionDto> organizations = dto.getOrganizations();
    if (organizations.isEmpty()) {
      PipUser currentUser =
          PipUser.findPipUsersByEmailEquals(principal.getName()).getSingleResult();
      List<Organisazion> organisazions = currentUser.getOrganisazions();
      if (!organisazions.isEmpty()) {
        user.getOrganisazions().add(organisazions.get(0));
      }
    } else {
      Organisazion organisazion =
          Organisazion.findOrganisazionsByName(
                  new ArrayList<OrganisazionDto>(organizations).get(0).getName())
              .getSingleResult();
      user.getOrganisazions().add(organisazion);
    }

    String randomPassword = RandomStringUtils.randomAlphanumeric(6);
    user.setPassword(encoder.encode(randomPassword));
    user.setRole(PipRole.USER.getName());
    user.persist();
    mailingUtil.sendCreationMail(user, randomPassword);
  }
  @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public void exportData(HttpServletResponse resp, Principal prin) throws IOException {

    resp.setContentType(MediaType.APPLICATION_JSON_VALUE);

    // this writer puts things out onto the wire
    JsonWriter writer = new JsonWriter(resp.getWriter());
    writer.setIndent("  ");

    try {

      writer.beginObject();

      writer.name("exported-at");
      writer.value(dateFormat.format(new Date()));

      writer.name("exported-from");
      writer.value(config.getIssuer());

      writer.name("exported-by");
      writer.value(prin.getName());

      // delegate to the service to do the actual export
      dataService_1_3.exportData(writer);

      writer.endObject(); // end root
      writer.close();

    } catch (IOException e) {
      logger.error("Unable to export data", e);
    }
  }