org.gaixie.jibu.security.service.AuthorityServiceTest.java Source code

Java tutorial

Introduction

Here is the source code for org.gaixie.jibu.security.service.AuthorityServiceTest.java

Source

/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.gaixie.jibu.security.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.gaixie.jibu.CoreTestSupport;
import org.gaixie.jibu.JibuException;
import org.gaixie.jibu.cache.Cache;
import org.gaixie.jibu.utils.CacheUtils;
import org.gaixie.jibu.utils.ConnectionUtils;
import org.gaixie.jibu.security.model.Authority;
import org.gaixie.jibu.security.model.Role;
import org.gaixie.jibu.security.model.User;
import org.gaixie.jibu.security.service.AuthorityService;
import org.gaixie.jibu.security.service.RoleService;
import org.gaixie.jibu.security.service.UserService;

public class AuthorityServiceTest extends CoreTestSupport {
    private AuthorityService authService;
    private RoleService roleService;
    private UserService userService;

    @Before
    public void setup() throws Exception {
        authService = getInjector().getInstance(AuthorityService.class);
        roleService = getInjector().getInstance(RoleService.class);
        userService = getInjector().getInstance(UserService.class);

        userService.add(new User("Administrator", "admin", "123456", "jibu.gaixie@gmail.com", true));

        authService.add(new Authority("sec.ast-v-auth1", "/ast-v-auth1.z"));
        authService.add(new Authority("sec.ast-v-auth2", "/ast-v-auth2.z"));
        authService.add(new Authority("sec.ast-v-auth3", "/ast-v-auth3.z"));
        // ??(value.length <5)??????
        authService.add(new Authority("ci", "/ast-v-auth1.z?ci=addUser"));
        userService.add(new User("ast-v-user1", "ast-v-user1", "123456", "ast-v-user1@x.xxx", true));

        /*
         * 
         * ROLE_BASE
         *     |-----ROLE_ADMIN
         *     |
         *     |-----ast-v-role1
         *     |          |------ast-v-role2
         *     |-----ast-v-role3
         */
        // ? Role 
        Connection conn = ConnectionUtils.getConnection();
        QueryRunner run = new QueryRunner();
        run.update(conn, "INSERT INTO roles (name,description,lft,rgt) values ('ROLE_BASE','ROLE_BASE',1,2)");
        DbUtils.commitAndClose(conn);

        Role parent = roleService.get("ROLE_BASE");
        roleService.add(new Role("ROLE_ADMIN", "ROLE_ADMIN"), parent);
        roleService.add(new Role("ast-v-role1", "ast-v-role1"), parent);
        roleService.add(new Role("ast-v-role3", "ast-v-role3"), parent);
        parent = roleService.get("ast-v-role1");
        roleService.add(new Role("ast-v-role2", "ast-v-role2"), parent);

        /* ????
         * ROLE_BASE 
         *     |-----ROLE_ADMIN
         *     |
         *     |-----ast-v-role1 <==> (/ast-v-auth1.z ) (/ast-v-auth1.z?ci=addUser)
         *     |          |------ast-v-role2 
         *     |-----ast-v-role3 <==> (/ast-v-auth2.z )
         */
        Authority auth = authService.get("/ast-v-auth1.z");
        Role role = roleService.get("ast-v-role1");
        roleService.bind(role, auth);
        auth = authService.get("/ast-v-auth1.z?ci=addUser");
        roleService.bind(role, auth);
        auth = authService.get("/ast-v-auth2.z");
        role = roleService.get("ast-v-role3");
        roleService.bind(role, auth);

        /* ast-v-role2, admin  ROLE_ADMIN
         * ROLE_BASE
         *     |-----ROLE_ADMIN <==> (admin)
         *     |
         *     |-----ast-v-role1
         *     |          |------ast-v-role2 <==> (ast-v-user1)
         *     |-----ast-v-role3 
         */
        role = roleService.get("ast-v-role2");
        User user = userService.get("ast-v-user1");
        roleService.bind(role, user);
        role = roleService.get("ROLE_ADMIN");
        user = userService.get("admin");
        roleService.bind(role, user);
    }

    @Test
    public void testGet() throws Exception {
        Authority auth = authService.get("/ast-v-auth1.z");
        String name = authService.get(auth.getId()).getName();
        Assert.assertTrue(auth.getName().equals(name));
    }

    @Test
    public void testUpdateAndDelete() throws Exception {
        authService.add(new Authority("sec.test.ast-v-auth4", "/ast-v-auth4.z"));
        Authority auth = authService.get("/ast-v-auth4.z");
        Role role = roleService.get("ROLE_BASE");
        roleService.bind(role, auth);

        List<Authority> auths = authService.getAll();
        Cache cache = CacheUtils.getAuthCache();
        List<Authority> authsc = (List<Authority>) cache.get("authorities");
        Assert.assertNotNull(authsc);

        auth.setValue("/ast-v-auth4-none.z");
        authService.update(auth);
        Assert.assertNull(authService.get("/ast-v-auth4.z"));
        // ? cache
        authsc = (List<Authority>) cache.get("authorities");
        Assert.assertNull(authsc);
        auth = authService.get("/ast-v-auth4-none.z");
        Assert.assertNotNull(auth);
        roleService.unbind(role, auth);
        authService.delete(auth);
        Assert.assertNull(authService.get(auth.getId()));
    }

    @Test
    public void testFindByName() throws Exception {
        List<Authority> auths = authService.findByName("sec.ast-v-auth");
        Assert.assertTrue(auths.size() == 3);
        auths = authService.findByName("sec.ast-v-auth1");
        Assert.assertTrue(auths.size() == 1);
    }

    //  RoleService.find(user) 
    @Test
    public void testFindByUser() throws Exception {
        // ?
        User user = userService.get("ast-v-user1");
        List<Authority> auths = authService.find(user);
        Assert.assertTrue(auths.size() == 2);
        // ??
        List<Role> roles = roleService.find(user);
        Assert.assertTrue(roles.size() == 1);
    }

    // ???
    //  UserService.find(Role) 
    @Test
    public void testFindByRole() throws Exception {
        Role role = roleService.get("ast-v-role2");
        List<Authority> auths = authService.find(role);
        Assert.assertTrue(auths.size() == 0);
        List<User> users = userService.find(role);
        Assert.assertTrue(users.size() == 1);
    }

    //  UserService.find(Authority)  RoleService.find(Authority) 
    @Test
    public void testFindByAuth() throws Exception {
        // ??
        Authority auth = authService.get("/ast-v-auth1.z");
        List<Role> roles = roleService.find(auth);
        Assert.assertTrue(roles.size() == 1);
        // ?
        List<User> users = userService.find(auth);
        Assert.assertTrue(users.size() == 1);
    }

    @Test
    public void testVerify() throws Exception {
        // ?
        // ast-v-user1  /ast-v-auth1.z ??
        boolean bl = authService.verify("/ast-v-auth1.z", "ast-v-user1");
        Assert.assertTrue(bl);
        // ast-v-user1 ast-v-auth2.z??
        bl = authService.verify("/ast-v-auth2.z", "ast-v-user1");
        Assert.assertTrue(!bl);
        // ???auth??
        bl = authService.verify("/ast-v-auth3.z", "ast-v-user1");
        Assert.assertTrue(bl);
        // ?auth?
        bl = authService.verify("/ast-v-auth4.z", "ast-v-user1");
        Assert.assertTrue(!bl);

        // ast-v-user1  ?? /ast-v-auth1.z?ci=addUser
        bl = authService.verify("/ast-v-auth1.z?ci=addUser", "ast-v-user1");
        Assert.assertTrue(bl);

        // ROLE_ADMIN admin???
        bl = authService.verify("/ast-v-auth1.z", "admin");
        Assert.assertTrue(bl);
        bl = authService.verify("/ast-v-auth3.z", "admin");
        Assert.assertTrue(bl);
        bl = authService.verify("/ast-v-auth3.z", "admin");
        Assert.assertTrue(bl);
        // ROLE_ADMIN ???
        bl = authService.verify("/ast-v-auth4.z", "admin");
        Assert.assertTrue(bl);
    }

    @Test
    public void testFindMapByUsername() throws Exception {
        // user ??/ast-v-auth1.z
        //  /ast-v-auth3.z ???user??
        // map  sec, sec.ast-v-auth1,sec.ast-v-auth3
        // ? map ? 0004 ??
        Map<String, String> map = authService.findMapByUsername("ast-v-user1");
        Assert.assertTrue(3 == map.size());
        Assert.assertTrue("#".equals(map.get("sec")));
        Assert.assertTrue("/ast-v-auth1.z".equals(map.get("sec.ast-v-auth1")));
        Assert.assertNull(map.get("sec.ast-v-auth2"));
        // ROLE_ADMIN??distinct?/ast-v-auth1.z /ast-v-auth2.z
        map = authService.findMapByUsername("admin");
        Assert.assertTrue(map.size() >= 4);
        Assert.assertNotNull(map.get("sec.ast-v-auth2"));
    }

    // ????
    // @Test 
    public void testPerformance() throws Exception {
        //  10 
        Role parent = roleService.get("ROLE_BASE");
        for (int i = 0; i < 10; i++) {
            Role role = new Role("ast-pf-role" + i, "ast-pf-role" + 1);
            roleService.add(role, parent);
            parent = roleService.get(role.getName());
        }
        parent = roleService.get("ROLE_BASE");
        // 500auth??1500
        // ROLE_BASE
        // ?160k cache
        for (int i = 0; i < 500; i++) {
            Authority auth = new Authority("lev1.lev" + i + ".lev3.ast-pf-auth" + i, "/ast-pf-auth" + i + ".z");
            authService.add(auth);
            auth = authService.get(auth.getValue());
            roleService.bind(parent, auth);
        }

        // 500userrole
        Role role = roleService.get("ast-pf-role9");
        for (int i = 0; i < 500; i++) {
            User user = new User("ast-pf-user" + i, "ast-pf-user" + i, "123456");
            user.setEnabled(true);
            userService.add(user);
            user = userService.get(user.getUsername());
            roleService.bind(role, user);
        }

        // ???Cache
        long start = System.currentTimeMillis();
        Map<String, String> map = authService.findMapByUsername("ast-pf-user100");
        System.out
                .println("no cache:" + (System.currentTimeMillis() - start) + " ms, get " + map.size() + " menus.");
        start = System.currentTimeMillis();
        map = authService.findMapByUsername("ast-pf-user100");
        System.out
                .println("in cache:" + (System.currentTimeMillis() - start) + " ms, get " + map.size() + " menus.");

        // ?usercache?0.4k
        start = System.nanoTime();
        boolean bl = authService.verify("/ast-pf-auth100.z", "ast-pf-user101");
        System.out.println("no cache:" + (System.nanoTime() - start) + " ns, verify: " + bl);
        start = System.nanoTime();
        bl = authService.verify("/ast-pf-auth100.z", "ast-pf-user101");
        System.out.println("in cache:" + (System.nanoTime() - start) + " ns, verify: " + bl);
    }

    @After
    public void tearDown() {
        Connection conn = null;
        try {
            conn = ConnectionUtils.getConnection();
            QueryRunner run = new QueryRunner();
            run.update(conn, "DELETE from role_authority_map ");
            run.update(conn, "DELETE from user_role_map");
            run.update(conn, "DELETE from roles");
            run.update(conn, "DELETE from authorities ");
            run.update(conn, "DELETE from userbase");
            DbUtils.commitAndClose(conn);
        } catch (SQLException e) {
            DbUtils.rollbackAndCloseQuietly(conn);
            System.out.println(e.getMessage());
        }
    }
}