카테고리 없음

220119_개발일지

VIPeveloper 2022. 1. 19. 13:50
728x90
반응형

1. 권한 관리 로직 개선

- 어드민으로 접속 시, 어드민 권한이 없다면 접속할 수 없도록 조치하는 로직을 만들었다.

- 근데 이걸 다 controller에 적용하려면 페이지 넘길때마다 권한 조회하는 sql이 생길텐데,, 이거 security로 빼는 방법 공부해야할 것 같다.

@GetMapping("admin-dashboard")
public String adminDashBoard(@CurrentUser Account account){
    Role role = roleService.findByName("Admin");
    if(account == null || !account.isAdmin(role)){
        return "redirect:/";
    }

    return "pages/dashboard/admin-dashboard";
}

2. 체크박스 + ajax 로직

- 체크박스를 클릭 및 해제할 때마다 ajax 로 권한을 줬다 제거했다 하는 로직을 만들었다.

- onclick으로 적용될 수 있도록 만들었다.

<th:block th:with="an=|${account.nickname}-${role.id}|">
    <input type="checkbox" th:checked="${#lists.contains(tl, role)}"
           th:id="${an}"
           data-onstyle="primary"
           data-style="slow"
           th:onclick="dataSend([[${an}]])"
           data-width="80" data-height="50"
           class="m-2"
           th:value="r"/>
</th:block>
<script th:inline="javascript">
    function dataSend(an){
        var isCheck = $('#'+ an);
        if(isCheck.is(':checked')){
            $.ajax({
                url: '/pages/dashboard/role-add',
                data: {param: an},
                type:"POST",
            }).done(function (data) {
                alert('권한을 추가했습니다.');
            });
        }else{
            $.ajax({
                url: '/pages/dashboard/role-delete',
                data: {param: an},
                type:"POST",
            }).done(function (data) {
                alert('권한을 삭제했습니다.');
            });
        }
    }
</script>

3. 어드민 접근 권한 로직 개선

- 어드민인지 확인한 후 들여보내주는 로직 개발

/**
 * 어드민 권한 확인
 * @param account 현재 접속한 유저
 * @return boolean
 */
public boolean adminRoleCheck(Account account) {
    Role role = this.findByName("Admin");
    return account == null || !account.isAdmin(role);
}

4. 권한에 따라 버튼 보이도록 개선

- 객체 뒤에 ? 로 null 체크 해준다.

- 타임리프에서 함수도 사용 가능하다.

<th:block th:if="${account?.hasInstructor()}">
    <a th:href="@{/pages/dashboard-instructor}" class="btn btn-white">Are You Instructor?</a>
</th:block>
<th:block th:if="${account?.hasAdmin()}">
    <a th:href="@{/pages/dashboard/admin-dashboard}" class="btn btn-white">Are You Admin?</a>
</th:block>
728x90
반응형