Django: Track and save to db user login/logout activities

62 Views Asked by At

I want to log users into the database with their time when they log in or log out. I can do this if these operations are done using the login and logout functions, but I need to detect and record the logout operation when they log out by closing the browser. I used websocket for this, but websocket disconnects and reconnects when users switch pages in the project, so it is detected as logout. Is there a way to do this?

I added this websocket codes to my base.html

let wsProtocol = window.location.protocol === "https:" ? "wss" : "ws";
let url = `${wsProtocol}://${window.location.host}/ws/socket-server/`
const markSocket = new WebSocket(url)
markSocket.onopen = function(e){
    markSocket.send(JSON.stringify({
        'message':'CONNECTED'
    }))
}
markSocket.onclose = function(event) {
    console.error("WebSocket closed:", event);
};

and here is my consumer.py that connected to websocket

class OnlineStatusConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()
        user = self.scope['user']
        status = True
        print("CONNECTED",user)
        await self.change_online_status(user, status)

    async def disconnect(self, close_code):
        user = self.scope['user']
        status = False
        print("DISCONNECTED", user,close_code)
        await self.change_online_status(user, status)

    @database_sync_to_async
    def change_online_status(self, user, status):
        if status:
            active_user = ActiveUsers.objects.get_or_create()[0]
            if not active_user.active_users.filter(id=user.id).exists():
                active_user.active_users.add(user)
                active_user.active_user_count += 1
                active_user.save()
                # Kullanıcının en son oturum açma girişimini al
                last_login_attempt = SpecificUserLoginDiary.objects.filter(user=user).last()
                # Eğer kullanıcı daha önce oturum açma girişimi yapmışsa ve son giriş denemesi 10 dakika içindeyse yeni bir obje oluştur
                if last_login_attempt and (timezone.now() - last_login_attempt.login_date) < timedelta(minutes=2):
                    print("Son oturum açma girişimi 30 dakika içinde yapılmış.")
                else:
                    specific_user_active_log = SpecificUserLoginDiary.objects.create(
                        user=user,
                        login_date=timezone.now()
                    )
            else:
                print("User already connected")
        else:
            active_user = ActiveUsers.objects.get_or_create()[0]
            if active_user.active_users.filter(id=user.id).exists():
                active_user.active_users.remove(user)
                active_user.active_user_count -= 1
                active_user.save()
                specific_user_active_log = SpecificUserLoginDiary.objects.filter().last()
                if specific_user_active_log:
                    specific_user_active_log.logout_date = datetime.now()
                    specific_user_active_log.save()
            else:
                print("User already disconnected")

Thank you in advance

0

There are 0 best solutions below