0
0

More than 3 years have passed since last update.

[Django] クラス継承によるアクセス制限を実装してみた。

Posted at

前書き

メモがてら初心者が書いているので、間違いはご容赦ください。
チャットアプリを作っているのですが、チャットルームを部屋の参加者以外覗けないようにしたくなりました。
クラスビューのメソッドのオーバーライドで実装しようとして、かなり時間を費やしましたが、
めちゃくちゃ簡単な方法がありましたのでご紹介します。

本題

※中間テーブルで参加者を管理しています。(該当のレコードがあれば参加済)

models.py

class Room(models.Model):
     ()

class User(AbstractBaseUser, PermissionsMixin):
     ()

class JoinRoom(models.Model):#中間テーブル
    room = models.ForeignKey(Room,on_delete=models.CASCADE)
    user = models.ForeignKey(User,on_delete=models.PROTECT)

本当はここに書かないほうがいいのかもしれませんが、見やすくするためこちらにまとめます。
filterを使うより、getのほうが早くていいらしいのでこうしてます。

views.py

from django.contrib.auth.mixins import UserPassesTestMixin

class OnlyParticipantMixin(UserPassesTestMixin):
    raise_exception = True

    def test_func(self):
        try:
            exist_or_not = MyRoom.objects.get(room=self.kwargs['pk'],user=self.request.user)#代入する必要があるのかはまだ試してません。
            return True
        except MyRoom.DoesNotExist:
            return False

class CommentCreateView(OnlyParticipantMixin,generic.CreateView):#この順番じゃないと機能しないっぽい?
     template_name = 'hogehoge/hogehoge'

これで完了。参加者以外が覗こうとしたらエラーが出るようになります。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0