Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User logout by session in Django Rest Framework

I have a application, where frontend written by Angular 6 and backend - by Django Rest Framework.

User logging out implemented on the frond with following code:

@Component({
  selector: 'app-logout-modal',
  templateUrl: './logout-modal.component.html',
  styleUrls: ['./logout-modal.component.scss']
})
export class LogoutModalComponent implements OnInit {

  constructor(public thisDialogRef: MatDialogRef<LogoutModalComponent>,
              private router: Router,
              @Inject(MAT_DIALOG_DATA) public data: any) {
  }

  ngOnInit() {
  }
  logoutAndClose(): void {
    localStorage.clear();
    this.thisDialogRef.close();
    this.router.navigateByUrl(RouteUrls.Login);
  }
}
class ProfileSettingsViewset(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet):
    @action(detail=False, methods=['post'])
    def logout(self, request):
        #???
        return Response(status=status.HTTP_200_OK)

That is, the user is not actually logging out.

How can I implement user logout by session on the DRF?


1 Answers

to logout user you must implement a viewset.

if you use token base authentication simply delete token

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

class Logout(APIView):
    def get(self, request, format=None):
        # simply delete the token to force a login
        request.user.auth_token.delete()
        return Response(status=status.HTTP_200_OK)

if you use session authentication backend you must logout user with Django backends like this:

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth import logout

class Logout(APIView):
    def get(self, request, format=None):
        # using Django logout
        logout(request)
        return Response(status=status.HTTP_200_OK)

then in urls:

urlpatterns = [
    ...
    url(r'^logout/', Logout.as_view()),
]

in your angular component must call Ajax request to this view before deleting clearing local storage content

like image 118
vorujack Avatar answered Oct 18 '25 22:10

vorujack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!