Example usage for org.apache.shiro SecurityUtils getSubject

List of usage examples for org.apache.shiro SecurityUtils getSubject

Introduction

In this page you can find the example usage for org.apache.shiro SecurityUtils getSubject.

Prototype

public static Subject getSubject() 

Source Link

Document

Returns the currently accessible Subject available to the calling code depending on runtime environment.

Usage

From source file:annis.service.internal.QueryServiceImpl.java

License:Apache License

/**
 * Fetches the example queries for a specific corpus.
 *
 * @param rawCorpusNames specifies the corpora the examples are fetched from.
 *
 *//*from  w ww . j av a2  s .c  o  m*/
@GET
@Path("corpora/example-queries/")
@Produces(MediaType.APPLICATION_XML)
public List<ExampleQuery> getExampleQueries(@QueryParam("corpora") String rawCorpusNames)
        throws WebApplicationException {

    Subject user = SecurityUtils.getSubject();

    try {
        String[] corpusNames;
        if (rawCorpusNames != null) {
            corpusNames = rawCorpusNames.split(",");
        } else {
            List<AnnisCorpus> allCorpora = queryDao.listCorpora();
            corpusNames = new String[allCorpora.size()];
            for (int i = 0; i < corpusNames.length; i++) {
                corpusNames[i] = allCorpora.get(i).getName();
            }
        }

        List<String> allowedCorpora = new ArrayList<>();

        // filter by which corpora the user is allowed to access
        for (String c : corpusNames) {
            if (user.isPermitted("query:*:" + c)) {
                allowedCorpora.add(c);
            }
        }

        List<Long> corpusIDs = queryDao.mapCorpusNamesToIds(allowedCorpora);
        return queryDao.getExampleQueries(corpusIDs);
    } catch (Exception ex) {
        log.error("Problem accessing example queries", ex);
        throw new WebApplicationException(ex, 500);
    }
}

From source file:annis.service.internal.QueryServiceImpl.java

License:Apache License

/**
 * Fetches the raw text from the text.tab file.
 *
 * @param top the name of the top level corpus.
 * @param docname the name of the document.
 *
 * @return Can be empty, if the corpus only contains media data or
 * segmentations.//from   w  w w.  j a  v a  2  s .  co  m
 */
@GET
@Path("rawtext/{top}/{docname}")
@Produces(MediaType.APPLICATION_XML)
public RawTextWrapper getRawText(@PathParam("top") String top, @PathParam("docname") String docname) {
    Subject user = SecurityUtils.getSubject();
    user.checkPermission("query:raw_text:" + top);

    RawTextWrapper result = new RawTextWrapper();
    result.setTexts(queryDao.getRawText(top, docname));
    return result;
}

From source file:annis.service.internal.URLShortenerImpl.java

License:Apache License

/**
 * Takes a URI and returns an ID.//from  www .j  a  v a  2  s. co m
 * 
 * In order to access this function the
 * {@code 
 * shortener:create:<ip>
 * }
 * right is needed. "&lt;ip&gt;" is replaced by the IP of the client which makes this request.
 * Either IPv4 or IPv6 can be used. The dots (IPv4) or colons (IPv6) 
 * must be replaced with underscores since they conflict with the Apache
 * Shiro {@link WildcardPermission} format.
 * 
 * @param str The string to shorten.
 * @return 
 */
@POST
@Produces(value = "text/plain")
public String addNewID(String str) {
    Subject user = SecurityUtils.getSubject();

    String remoteIP = request.getRemoteAddr().replaceAll("[.:]", "_");
    user.checkPermission("shortener:create:" + remoteIP);

    return shortenerDao.shorten(str, "" + user.getPrincipal()).toString();
}

From source file:ApacheShiro.ShiroMVC.java

public boolean AutentificarRol(String Rol) {
    currentUser = SecurityUtils.getSubject();
    boolean autentificarRol;
    if (currentUser.hasRole(Rol)) {
        log.info("eres " + Rol);
        autentificarRol = true;/*  w w w  .  jav a2  s.  co  m*/
    } else {
        log.info("no eres " + Rol);
        autentificarRol = false;
    }
    return autentificarRol;

}

From source file:ApacheShiro.ShiroMVC.java

public boolean AutentificarPermisos(String permiso) {
    currentUser = SecurityUtils.getSubject();
    boolean autentificarPermiso;
    if (currentUser.isPermitted(permiso)) {
        log.info("Tienes permsiso para: " + permiso);
        autentificarPermiso = true;/*  w w w . j a v a 2  s .  c o  m*/
    } else {
        log.info("Sorry, no tienes permiso para: " + permiso);
        autentificarPermiso = false;
    }
    return autentificarPermiso;
}

From source file:apm.modules.sys.security.SystemAuthorizingRealm.java

License:Open Source License

/**
 * ?, /*w  w  w  . j av  a 2 s. com*/
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
        throws AuthenticationException {
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

    if (LoginController.isValidateCodeLogin(token.getUsername(), false, false)) {
        // ??
        Session session = SecurityUtils.getSubject().getSession();
        String code = (String) session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
        if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)) {
            throw new CaptchaException("??.");
        }
    }

    User user = getUserService().findByLoginName(token.getUsername());
    if (user != null) {
        byte[] salt = Encodes.decodeHex(user.getPassword().substring(0, 16));
        return new SimpleAuthenticationInfo(new Principal(user), user.getPassword().substring(16),
                ByteSource.Util.bytes(salt), getName());
    } else {
        return null;
    }
}

From source file:apm.modules.sys.service.UserService.java

License:Open Source License

@Transactional(readOnly = false)
public void updateUserLoginInfo(String id) {
    dao.updateLoginInfo(SecurityUtils.getSubject().getSession().getHost(), new Date(), id);
}

From source file:at.pollux.thymeleaf.shiro.dialect.ShiroDialectTest.java

License:Apache License

@Test
public void testPrincipalWithType() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    setSubject(subjectUnderTest);// w  ww .j a v  a  2  s .  c om

    Context context = new Context();
    String result;

    // Guest user
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("TYPEPRINCIPAL1"));
    assertFalse(result.contains("TYPEPRINCIPAL2"));

    // Logged in user
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertEquals(Integer.valueOf(0), SecurityUtils.getSubject().getPrincipals().oneByType(Integer.class)); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("TYPEPRINCIPAL1<span>0</span>TYPEPRINCIPAL1"));
    assertTrue(result.contains("TYPEPRINCIPAL20TYPEPRINCIPAL2"));
    subjectUnderTest.logout();
}

From source file:at.pollux.thymeleaf.shiro.dialect.ShiroDialectTest.java

License:Apache License

@Test
public void testPrincipalWithProperty() {
    Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
    setSubject(subjectUnderTest);/*from w  w  w  .j a  va 2  s . c o  m*/

    Context context = new Context();
    String result;

    // Guest user
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertFalse(result.contains("PROPPRINCIPAL1"));
    assertFalse(result.contains("PROPPRINCIPAL2"));

    // Logged in user
    subjectUnderTest.login(new UsernamePasswordToken(USER1, PASS1));
    assertEquals(Integer.valueOf(0), SecurityUtils.getSubject().getPrincipals().oneByType(Integer.class)); // sanity
    result = templateEngine.process(TEST_TEMPLATE_PATH, context);
    assertFalse(result.contains("shiro:"));
    assertTrue(result.contains("PROPPRINCIPAL1<span>" + USER1.toUpperCase() + " " + USER1.toUpperCase()
            + "</span>PROPPRINCIPAL1"));
    assertTrue(result
            .contains("PROPPRINCIPAL2" + USER1.toUpperCase() + " " + USER1.toUpperCase() + "PROPPRINCIPAL2"));
    subjectUnderTest.logout();
}

From source file:at.pollux.thymeleaf.shiro.dialect.ShiroFacade.java

License:Apache License

public static boolean isAuthenticated() {
    return SecurityUtils.getSubject() != null && SecurityUtils.getSubject().isAuthenticated();
}