Example usage for org.apache.shiro.authz AuthorizationException AuthorizationException

List of usage examples for org.apache.shiro.authz AuthorizationException AuthorizationException

Introduction

In this page you can find the example usage for org.apache.shiro.authz AuthorizationException AuthorizationException.

Prototype

public AuthorizationException(Throwable cause) 

Source Link

Document

Constructs a new AuthorizationException.

Usage

From source file:aaa.realms.MySQLRealm.java

License:Apache License

/**
 * This implementation of the interface expects the principals collection to return a String username keyed off of
 * this realm's {@link #getName() name}//from   ww  w  . j  a  va 2 s  . c  o m
 *
 * @see #getAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    //null usernames are invalid
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }

    String username = (String) getAvailablePrincipal(principals);

    Connection conn = null;
    Set<String> roleNames = null;
    Set<String> permissions = null;
    try {
        conn = dataSource.getConnection();

        // Retrieve roles and permissions from database
        roleNames = getRoleNamesForUser(conn, username);
        if (permissionsLookupEnabled) {
            permissions = getPermissions(conn, username);
        }

    } catch (SQLException e) {
        final String message = "There was a SQL error while authorizing user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authorization exception
        throw new AuthorizationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissions);
    return info;

}

From source file:br.com.betsportclub.controller.security.SecurityRealm.java

License:Apache License

/**
 * This implementation of the interface expects the principals collection to return a String username keyed off of
 * this realm's {@link #getName() name}/*from  w ww .  j  av  a2 s  . c om*/
 *
 * @see #getAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    //null usernames are invalid
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }

    String username = (String) getAvailablePrincipal(principals);

    Connection conn = null;
    Set<String> roleNames = null;
    Set<String> permissions = null;
    try {
        conn = dataSource.getConnection();

        // Retrieve roles and permissions from database
        roleNames = getRoleNamesForUser(conn, username);
        if (permissionsLookupEnabled) {
            permissions = getPermissions(conn, username, roleNames);
        }

    } catch (SQLException e) {
        final String message = "There was a SQL error while authorizing user [" + username + "]";
        if (log.isErrorEnabled()) {
            log.error(message, e);
        }

        // Rethrow any SQL errors as an authorization exception
        throw new AuthorizationException(message, e);
    } finally {
        JdbcUtils.closeConnection(conn);
    }

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
    info.setStringPermissions(permissions);
    return info;

}

From source file:br.com.criativasoft.opendevice.restapi.auth.AbstractAuthorizingRealm.java

License:Open Source License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    if (principals.isEmpty())
        throw new AuthorizationException("Empty principals list!");

    AccountPrincipal principal = (AccountPrincipal) principals.getPrimaryPrincipal();

    Set<String> roles = new HashSet(Arrays.asList(principal.getType().name()));

    if (principal.getType() == AccountType.CLOUD_MANAGER)
        roles.add(AccountType.ROLES.ACCOUNT_MANAGER);

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
    return info;//from   w  ww  . j  av  a2s  . com
}

From source file:br.com.criativasoft.opendevice.restapi.resources.AccountRest.java

License:Open Source License

@POST
@Path("users")
@RequiresRoles(AccountType.ROLES.ACCOUNT_MANAGER)
public User addUser(User user) {

    AccountPrincipal principal = (AccountPrincipal) getSubject().getPrincipal();

    Account account = dao.getAccountByUID(principal.getAccountUUID());

    HashingPasswordService service = new DefaultPasswordService();
    user.setPassword(service.encryptPassword(user.getPassword()));

    // Editing/*from  w  w  w.jav a  2  s .  c o  m*/
    if (user.getId() > 0) {

        boolean contains = dao.existUser(account, user);

        if (!contains)
            throw new AuthorizationException("This user does not belong to your account");

        userDao.update(user);
    } else {

        UserAccount userAccount = new UserAccount();
        userAccount.setType(AccountType.USER);
        userAccount.setOwner(account);
        userAccount.setUser(user);
        user.getAccounts().add(userAccount);
        userDao.persist(user);
    }

    return user;
}

From source file:br.com.criativasoft.opendevice.restapi.resources.AccountRest.java

License:Open Source License

@DELETE
@Path("users/{id}")
@RequiresRoles(AccountType.ROLES.ACCOUNT_MANAGER)
public Response deleteUser(@PathParam("id") long id) {

    AccountPrincipal principal = (AccountPrincipal) getSubject().getPrincipal();

    Account account = dao.getAccountByUID(principal.getAccountUUID());

    User user = userDao.getById(id);/*  ww w. j a  va 2  s . c o m*/

    boolean exist = dao.existUser(account, user);

    if (!exist)
        throw new AuthorizationException("This user does not belong to your account");

    List<User> users = dao.listUsers(account);

    if (users.size() == 1) {
        return ErrorResponse.BAD_REQUEST("You can not remove all users");
    }

    Set<UserAccount> userAccounts = account.getUserAccounts();

    UserAccount userAccount = null;

    // Find Account
    for (UserAccount ua : userAccounts) {
        if (ua.getUser().getId() == user.getId()) {
            userAccount = ua;
        }
    }

    boolean deleteUser = (user.getAccounts().size() == 1);
    account.getUserAccounts().remove(userAccount);
    userDao.delete(userAccount);
    if (deleteUser)
        userDao.delete(user);

    return Response.ok().build();

}

From source file:cn.powerdash.libsystem.common.security.SecurityContext.java

License:Open Source License

/**
 * ???/*w w  w .ja v a2  s  .  c om*/
 * 
 * @see org.apache.shiro.subject.Subject#checkPermission(String permission)
 * @param permission
 * @throws AuthorizationException
 */
public static void checkPermission(String permission) throws AuthorizationException {
    Subject subject = getSubject();
    if (subject == null) {
        throw new AuthorizationException("No permission as there is no subject bound.");
    }
    subject.checkPermission(permission);
}

From source file:com.autumnframework.common.shiroconfig.realm.ShiroDbRealm.java

License:Open Source License

/**
 * ???//  ww w.  ja v a2s.co m
 *
 * @param principals
 * @return
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    //        if (!super.isAuthenticationCachingEnabled()) {
    //            super.setCachingEnabled(authenticationCachingEnabled);
    //        }
    if (principals == null) {
        throw new AuthorizationException("Principal?");
    }

    User user = (User) getAvailablePrincipal(principals);
    log.info("??????:" + user.getUser_login_name());
    log.info("load user information:" + user.getUser_login_name());
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    List<Resource> resUserList = resourceService.selectResListByUserId(user.getId());
    for (Resource resUser : resUserList) {
        info.addStringPermission(String.valueOf(resUser.getId()));
    }

    List<Plugin> pluginList = pluginMapper.selectPluginByUserId(user.getId());
    for (Plugin plugin : pluginList) {
        info.addStringPermission(String.valueOf(plugin.getId()));
    }
    return info;
}

From source file:com.axelor.meta.service.MetaFilterService.java

License:Open Source License

@Transactional
public MetaFilter removeFilter(MetaFilter ctx) {
    User user = AuthUtils.getUser();//from   w  w w  . j a  v a  2 s.c  o m
    String query = "self.name = ?1 AND self.filterView = ?2 AND (self.user.code = ?3 OR self.shared = true)";
    MetaFilter filter = filters.all().filter(query, ctx.getName(), ctx.getFilterView(), user.getCode())
            .fetchOne();

    if (!Objects.equal(filter.getUser(), user)) {
        throw new AuthorizationException(I18n.get("You are not allowed to remove this filter"));
    }

    filters.remove(filter);

    return ctx;
}

From source file:com.baguaz.module.user.realm.AdminAuthorizingRealm.java

License:Apache License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //????/*www  .  j a  v  a2 s.  c  o m*/
    UserPrincipal principal = (UserPrincipal) super.getAvailablePrincipal(principals);
    String adminName = principal.getUserName();
    try {
        if (!principal.isAuthorized()) {
            //??????
            List<Record> roleRList = Role.dao.getRolesByUserid(principal.getUser().getInt("id"));
            Set<Role> roleMSet = roleRList.stream().map(r -> new Role().put(r)).collect(Collectors.toSet());
            principal.setRoles(roleMSet);

            List<String> authorities = null;
            if (principal.isAdmin()) {
                authorities = Permission.dao.getAllPermsName();
            } else {
                authorities = Permission.dao.getPermsNameByRoleids(principal.getRoleIds());
            }

            principal.setAuthorities(new LinkedHashSet<>(authorities));

            /*
             * ????
             */
            if (!principal.isAdmin()) {
                List<Integer> catpriv = CategoryPriv.dao.select("catid",
                        "roleid in(" + principal.getRoleIds() + ")", "catid asc", "", "");
                principal.setCatpriv(new LinkedHashSet<>(catpriv));
            }

            principal.setAuthorized(true);
            log.debug("?" + adminName + "???......");
            log.debug("?" + adminName + " " + principal.getRoleNameStrSet());

            Map<String, List<String>> aulistGroups = principal.getAuthorities().stream()
                    .sorted((a, b) -> a.compareTo(b)).collect(Collectors.groupingBy(a -> a.split(":")[0]));
            TreeMap<String, List<String>> map = new TreeMap<>();
            map.putAll(aulistGroups);
            log.debug("?" + adminName + " ??\n"
                    + map.values().stream().map(
                            ss -> ss.stream().collect(Collectors.joining(", ", "  " + ss.size() + " [", "]")))
                            .collect(Collectors.joining("\n", "{\n", "\n}")));
            log.debug("?" + adminName + " ???" + principal.getCatpriv());
        }
    } catch (RuntimeException e) {
        throw new AuthorizationException("?" + adminName + "?");
    }
    //???
    log.debug("???...");
    info.addStringPermissions(principal.getAuthorities());
    info.addRoles(principal.getRoleNameStrSet());
    return info;
}

From source file:com.baomidou.kisso.common.shiro.SSOAuthRealm.java

License:Apache License

/**
 * ????/*from   ww w  . j  av  a 2s.  c om*/
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }
    Token token = (Token) getAvailablePrincipal(principals);
    SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    List<String> permissions = shiroPermission.getPermissions(token);
    if (permissions != null) {
        authorizationInfo.addStringPermissions(permissions);
    }
    return authorizationInfo;
}