[Django] 포스트 작성 접근 권한 설정

haremeat·2021년 12월 30일
0

Django

목록 보기
7/15
post-thumbnail

모든 회원이 글을 쓰게 하는 것이 아닌 admin 또는 스태프에 해당하는 사람만 글을 작성할 수 있게 만들어보자

관리자 페이지에서 [User] 메뉴로 들어가면 사용자의 등급을 부여할 수 있다.

이 권한 여부에 따라 글을 작성할 수 있도록 기능을 만들어보ja

테스트 코드 작성

def setUp(self):
  self.user_main = User.objects.create_user(username='staff_user', password='somepassword')

  # 권한 부여
  self.user_main.is_staff = True
  self.user_main.save()
  
def test_create_post(self):
  # staff가 아닌 유저가 로그인을 한다
  self.client.login(username='normal', password='somepassword')
  response = self.client.get('/blog/create_post/')
  self.assertNotEqual(response.status_code, 301)

  # staff인 staff_user로 로그인한다.
  self.client.login(username='staff_user', password='somepassword')
  response = self.client.get('/blog/create_post/')
  self.assertEqual(response.status_code, 301)
  

일단 staff_user라는 아이디를 가진 유저를 staff로 설정하고 is_staff를 True로 설정한다.
포스트 작성시 테스트가 필요하므로 test_create_post 함수 안에 staff가 아닌 일반 유저가 로그인할 시 작성 페이지에 접근할 수 없게 작성한다. (assertNotEqual)
반면 staff_user가 접근할 때는 정상적으로 페이지가 뜨도록 테스트 코드를 작성한다.

여기까지만 하고 test를 돌리면 당연히 Fail이 뜬다. 아직 일반 회원도 포스트를 작성할 수 있기 때문이다.

views.py에 UserPassesTestMixin 추가하기

이제 /blog/views.py에서 PostCreate 클래스를 수정한다.
UserPassesTestMixin을 사용하면 된다.

class PostCreate(LoginRequiredMixin, UserPassesTestMixin, CreateView):
    model = Post
    fields = ['title', 'hook_text', 'content', 'head_image', 'file_upload', 'category']

    def test_func(self):
        return self.request.user.is_superuser or self.request.user.is_staff

    def form_valid(self, form):
        current_user = self.request.user
        if current_user.is_authenticated and (current_user.is_staff or current_user.is_superuser):
            form.instance.author = current_user
            return super(PostCreate, self).form_valid(form)
        else:
            return redirect('/blog/')

새로운 함수 test_func를 추가하고 form_valid 함수 안에 다음과 같은 조건을 추가한다.
if current_user.is_authenticated and (current_user.is_staff or current_user.is_superuser)
로그인 중이면서 + is_staff이거나 is_superuser일 때만 포스트를 작성할 수 있다는 조건이다.

python manage.py test

이후 테스트를 돌려보면 OK가 뜬다.

포스트 작성 버튼 만들기

{% if user.is_authenticated %}
    {% if user.is_superuser or user.is_staff %}
        <a href="/blog/create_post/" class="btn btn-info btn-sm float-right" role="button">New Post</a>
    {% endif %}
{% endif %}

포스트 목록이 있는 파일로 접근해서 해당 버튼이 최고관리자이거나 스태프일 때만 보이도록 설정한다.

끝!

profile
버그와 함께하는 삶

0개의 댓글