@PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, USER}) public User modify(@NotNull User user) { User existingUser = null; if (sessionContext.isCallerInRole(USER) && !sessionContext.isCallerInRole(ADMIN)) { existingUser = userFinder.findByLogin(sessionContext.getCallerPrincipal().getName()); if (!existingUser.getId().equals(user.getId()) || !existingUser.getLogin().equals(user.getLogin())) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } user.setActivated(existingUser.getActivated()); user.setDisabled(existingUser.getDisabled()); user.setActionToken(existingUser.getActionToken()); } if (existingUser == null) { existingUser = entityManager.find(User.class, user.getId()); } checkNotNull(existingUser); user.setPassword(existingUser.getPassword()); user.setCreationDate(existingUser.getCreationDate()); user.setRoles(existingUser.getRoles()); return entityManager.merge(user); }
@Override public String addForm(Form form) throws AddFormException { logger.info("------------> Adding a new Form 848"); try { logger.info("Finding principal user"); User user = null; try { user = userManager.findUserByName(sc.getCallerPrincipal().getName()); } catch (Exception e1) { logger.error("Imposible to retrieve principal user.", e1); throw new AddFormException(e1.getClass() + " --> " + e1.getMessage()); } Form848 form848 = new Form848(user); form848.fillForm(form); em.persist(form848); form848.setPrePrintedNumber(form848.getId().toString()); return form848.getId().toString(); } catch (FillFormException e) { logger.error(e); throw new AddFormException(e.getClass() + " --> " + e.getMessage()); } }
private boolean checkModificationAccessBySlot(String productID) throws OntologyErrorException { return DefaultSecurityManager.getInstance() .checkPersonCanModifyEntity( DefaultSecurityManager.getInstance().getParentProcess(productID), DefaultSecurityManager.getInstance() .getUserID(sessionCoontext.getCallerPrincipal().getName())); }
/** * Gets the caller authorization. * * @param methodname not null methodname. * @param classname not null classname. * @return {@link Authorization}. * @throws OntologyErrorException if an error occurs in ontology back end */ private Authorization getCallerAuthorization(String methodname, String classname) throws OntologyErrorException { return DefaultSecurityManager.getInstance() .createAuthorization( organizationEntity.getUser(sessionCoontext.getCallerPrincipal().getName()).getID(), methodname, classname); }
/** * This checks every not administrator caller if he can change the process model. <br> * this returns true if the process (in this context call) can be changed from the caller. * * @param parameters the method parameter. * @return true if the caller can change the process. * @throws OntologyErrorException if an error occurs in ontology back end */ private boolean checkNotAdminUser(Object[] parameters) throws OntologyErrorException { String modelID = (String) parameters[0]; LOG.debug("checkNotAdminUser PARAM[0] " + modelID); return DefaultSecurityManager.getInstance() .checkPersonCanModifyEntity( modelID, organizationEntity.getUser(sessionCoontext.getCallerPrincipal().getName()).getID()); }
@SuppressWarnings("unchecked") @RolesAllowed({"BANKADMIN", "BANKUSER"}) public List<Transaction> getAllTransactionsForUser(int start, int size) { Query q = em.createNamedQuery("getAllTransactionForUser"); q.setMaxResults(size); q.setFirstResult(start); q.setParameter("userId", sctx.getCallerPrincipal().getName()); return q.getResultList(); }
@RolesAllowed({"BANKADMIN", "BANKUSER"}) public Transaction getTransaction(int tranId) throws InvalidTranException, NotAuthorizedException, NotFoundException { String user = sctx.getCallerPrincipal().getName(); Transaction tran = em.find(Transaction.class, tranId); if (tran == null) throw new NotFoundException(); if (user.equals(tran.getAccount().getUserId()) || sctx.isCallerInRole("BANKADMIN")) return tran; else throw new NotAuthorizedException(); }
@Override public void beforeCompletion() throws EJBException, RemoteException { loger.log( Level.INFO, simpleDateHere.format(new Date()).toString() + " || Transakcja o ID: " + IDTransakcji + " przed zakonczeniem przez użytownka " + sessionContext.getCallerPrincipal().getName()); }
@RolesAllowed({"BANKADMIN", "BANKUSER"}) public int createTransaction(Transaction tran, int id) throws InvalidTranException, NotAuthorizedException, NotFoundException { String user = sctx.getCallerPrincipal().getName(); Account account = accountDao.getAccount(id); tran.setAccount(account); if (user.equals(tran.getAccount().getUserId()) || sctx.isCallerInRole("BANKADMIN")) em.persist(tran); return tran.getId(); }
public void kaufen(String produkt, int anzahl) { System.out.println(sessionContext.getCallerPrincipal().getName()); System.out.println(timeService.getTime()); if (map.containsKey(produkt)) { int alt = map.get(produkt); int neu = alt + anzahl; map.put(produkt, neu); } else { map.put(produkt, anzahl); } }
@Override public void afterBegin() throws EJBException, RemoteException { IDTransakcji = System.currentTimeMillis(); loger.log( Level.INFO, simpleDateHere.format(new Date()).toString() + " || Transakcja o ID: " + IDTransakcji + " zostala rozpoczeta ,przez użytkownika " + sessionContext.getCallerPrincipal().getName()); }
@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(); }
@Override public void afterCompletion(boolean committed) throws EJBException, RemoteException { loger.log( Level.INFO, simpleDateHere.format(new Date()).toString() + " || Transakcja o ID: " + IDTransakcji + " zostala zakonczona przez: " + (committed ? "zatwierdzenie" : "wycofanie") + " przez użytkownia" + sessionContext.getCallerPrincipal().getName()); }
/** * {@inheritDoc} * * @see * org.prowim.services.interceptors.SecurityInterceptor#onMethodCall(javax.interceptor.InvocationContext) */ @AroundInvoke public Object onMethodCall(InvocationContext context) throws Exception { Object[] params = context.getParameters(); for (int i = 0; i < params.length; i++) { LOG.debug("PARAM : " + i + " " + params[i]); } LOG.debug("Invoking class: " + context.getMethod().getDeclaringClass().getSimpleName()); LOG.debug("Invoking method: " + context.getMethod().getName()); System.out.println("CALLER PRINCIPAL " + sessionCoontext.getCallerPrincipal()); if (!intercept( context.getMethod().getName(), context.getMethod().getDeclaringClass().getSimpleName(), params)) { LOG.debug( "BeansSecurityInterceptor: allow call method < " + context.getMethod().getDeclaringClass().getSimpleName() + "#" + context.getMethod().getName() + " >"); if (context.getMethod().getName().equals("createObject")) { Object returnedObject = context.proceed(); if (returnedObject != null) { if (params[0].equals("model")) { DefaultSecurityManager.getInstance() .setUserCanModifyEntity( (String) returnedObject, DefaultSecurityManager.getInstance() .getUserID(sessionCoontext.getCallerPrincipal().getName())); } } return returnedObject; } else { return context.proceed(); } } else { throw new IllegalStateException( "No Permission to call this method for user. " + sessionCoontext.getCallerPrincipal()); } }
@GET @Path("/current") @Produces(MediaType.APPLICATION_JSON) @RolesAllowed({ADMIN, ADMIN_READONLY, USER}) public User findCurrentUser() { User user = userFinder.findByLogin(sessionContext.getCallerPrincipal().getName()); if (user == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return user; }
public String echo(String arg) { System.out.println("PublicSessionBean.echo, arg=" + arg); Principal p = sessionContext.getCallerPrincipal(); System.out.println("PublicSessionBean.echo, callerPrincipal=" + p); System.out.println( "PublicSessionBean.echo, isCallerInRole('EchoUser')=" + sessionContext.isCallerInRole("EchoUser")); try { InitialContext ctx = new InitialContext(); SessionHome home = (SessionHome) ctx.lookup("java:comp/env/ejb/PrivateSession"); Session bean = home.create(); System.out.println("PublicSessionBean.echo, created PrivateSession"); arg = bean.echo(arg); } catch (Exception e) { } return arg; }
@AroundInvoke public Object log(InvocationContext context) throws Exception { System.out.println("---" + context.getMethod()); QueueConnection conn = qcf.createQueueConnection(); conn.start(); QueueSession session = conn.createQueueSession(true, Session.SESSION_TRANSACTED); TextMessage msg = session.createTextMessage(); msg.setText( context.getMethod().getDeclaringClass().getSimpleName() + ";" + context.getMethod().getName() + ";" + sessionContext.getCallerPrincipal().getName()); QueueSender queueSender = session.createSender(queue); queueSender.send(msg); return context.proceed(); }
@Override public String invokeAll(String text) { Principal caller = context.getCallerPrincipal(); LOGGER.info("[" + caller.getName() + "] " + text); final StringBuilder result = new StringBuilder("MainEjbClient34App[" + caller.getName() + "]@" + getJBossNodeName()); // Call AppOne with the direct ejb: naming try { result.append(" > [ " + invokeAppOne(text)); } catch (Exception e) { LOGGER.error("Could not invoke AppOne", e); } result.append(" > " + invokeAppTwo(text)); result.append(" ]"); return result.toString(); }
protected Form848 findByPrePrintedNumber(String prePrintedNumber) throws FormNotFoundException { try { logger.info("Find Form whit PPN : " + prePrintedNumber); User user = userManager.findUserByName(sc.getCallerPrincipal().getName()); Form848 form848 = (Form848) em.createQuery( "from Form848 where prePrintedNumber like :ppn and businessCompany = :bc") .setParameter("ppn", prePrintedNumber.trim().toUpperCase()) .setParameter("bc", user.getBusinessCompany()) .getSingleResult(); return form848; } catch (Exception e) { logger.error(e); throw new FormNotFoundException(e.getClass().getName()); } }
@Override public void addBook(EntityBook book, EntityRelease release, EntityAuthor author) { // Autor se umisti do databaze. if (author.getId() != null) { author = em.merge(author); em.refresh(author); } else { em.persist(author); } // Propoji se autor s knihou. book.getAuthorCollection().add(author); author.getBookCollection().add(book); em.persist(book); em.persist(author); // Vytvori se nove vydani knihy. release.setBook(book); book.getReleasesCollection().add(release); em.persist(book); em.persist(release); // Ziska se uzivatel. Principal principal = sessionContext.getCallerPrincipal(); EntityUser user = beanSessionUser.getUserByEmail(principal.getName()); // Vytvori se novy vytisk knihy. EntityPrint print = new EntityPrint(); print.setRelease(release); release.getPrintsCollection().add(print); print.setOwnershipType(EntityPrint.EnumOwnershipType.PHYSICAL); print.setReadStatus(EntityPrint.EnumReadStatus.UNREAD); print.setUser(user); user.getPrintsCollection().add(print); em.persist(print); em.persist(release); em.persist(user); em.flush(); }
@Override public String invokeAll(String text) { Principal caller = context.getCallerPrincipal(); LOGGER.info("[" + caller.getName() + "] " + text); final StringBuilder result = new StringBuilder( "MainApp[" + caller.getName() + "]@" + System.getProperty("jboss.node.name")); // Call AppOne with the direct ejb: naming try { result.append(" > [ " + invokeAppOne(text)); } catch (Exception exception) { LOGGER.error("Could not invoke AppOne", exception); } String lookup = ""; // Call AppTwo with the direct ejb: naming try { lookup = "ejb:jboss-ejb-multi-server-app-two/ejb//AppTwoBean!" + AppTwo.class.getName(); result.append(" > " + invokeAppTwo(lookup, text)); LOGGER.info("Invoke '" + lookup + " OK"); } catch (Exception exception) { LOGGER.error("Could not invoke apptwo '" + lookup + "'", exception); } // Call AppTwo by using the local alias configured in // META-INF/ejb-jar.xml try { lookup = "java:comp/env/AppTwoAlias"; result.append(" ; " + invokeAppTwo(lookup, text)); LOGGER.info("Invoke '" + lookup + " OK"); } catch (Exception exception) { LOGGER.error("Could not invoke apptwo '" + lookup + "'", exception); } result.append(" ]"); return result.toString(); }
@PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("/{userLogin}/password") @PermitAll public void resetPassword( @NotNull @PathParam("userLogin") String userLogin, @QueryParam("token") String token, @NotNull String newPassword) { User user; if (sessionContext.isCallerInRole(ADMIN)) { user = userFinder.findByLogin(userLogin); } else if (sessionContext.isCallerInRole(USER)) { user = userFinder.findByLogin(sessionContext.getCallerPrincipal().getName()); if (!userLogin.equals(user.getLogin())) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); } } else { user = userFinder.findByLogin(userLogin); if (user == null || !user.getActionToken().equals(UUID.fromString(token))) { throw new WebApplicationException(Response.Status.NOT_FOUND); } user.setActionToken(null); } user.setPassword(hashSha256Base64(newPassword)); user.setActivated(true); sendMail(user, Mails.userChangePassword); }
public void restricted() { System.out.println("PublicSessionBean.restricted"); Principal p = sessionContext.getCallerPrincipal(); System.out.println("PublicSessionBean.restricted, callerPrincipal=" + p); }
private String getLoggedUser() { return ejbContext.getCallerPrincipal().getName(); }
/** * {@inheritDoc} * * @see org.prowim.services.interceptors.SecurityInterceptor#intercept(java.lang.String, * java.lang.String, java.lang.Object[]) */ public boolean intercept(String methodname, String classname, Object[] parameters) throws OntologyErrorException { Authorization authorization = getCallerAuthorization(methodname, classname); LOG.debug("INTERCEPT : " + methodname + " authorization " + authorization); if (authorization != null) { LOG.debug("AUTHORIZATIONS: " + authorization); if (authorization.getRolename().equals("Administrator")) { return !authorization.isAuthorized(); } // other user have to make this step but not the admin else { if (checkCreateModelForModeler(methodname, parameters, authorization.getRolename())) { LOG.debug("NO INTERCEPT for createObject Modeler Role :"); return false; } if (methodname.equals("setProduct")) { /** * TODO: param[2]= productID -> get the process ID where this product is defined and check * if <br> * the caller can modify this process */ return !(checkModificationAccessBySlot((String) parameters[2]) && authorization.isAuthorized()); } if (methodname.equals("removeRelationValue") || methodname.equals("setCombinationRule") || methodname.equals("setActivationRule")) { return !(checkModificationAccessBySlot((String) parameters[0]) && authorization.isAuthorized()); } if (methodname.equals("setProcessType")) { return !(checkModificationAccessBySlot((String) parameters[1]) && authorization.isAuthorized()); } if (methodname.equals("setRelationValue") || methodname.equals("setProcessStarter")) { return !(checkModificationAccessBySlot((String) parameters[0]) && authorization.isAuthorized()); } if (methodname.equals("deleteObject") || methodname.equals("setPersonCanModifyEntity")) { return !(checkModificationAccessBySlot((String) parameters[0]) && authorization.isAuthorized()); } if (methodname.equals("connectActivityControlFlow") || methodname.equals("connectActivityMittel") || methodname.equals("connectActivityRole")) { return !(checkModificationAccessBySlot((String) parameters[0]) && authorization.isAuthorized()); } /** for all other methods use this check. */ boolean check1 = authorization.isAuthorized(); boolean check2 = this.checkNotAdminUser(parameters); LOG.debug("Caller is not Administrator: " + sessionCoontext.getCallerPrincipal()); LOG.debug("Caller authorization: " + check1); LOG.debug("Caller checkNotAdmin " + check2); return !(check1 && check2); } } return true; }
public void noop() { System.out.println("PublicSessionBean.noop"); Principal p = sessionContext.getCallerPrincipal(); System.out.println("PublicSessionBean.noop, callerPrincipal=" + p); }
@Override public String invoke(String text) { Principal caller = context.getCallerPrincipal(); LOGGER.info("[" + caller.getName() + "] " + text); return "app2[" + caller.getName() + "]@" + getJBossNodeName(); }