Issue
Currently I've been using the generic login/register links (.../account/login, .../account/register etc) which lets all users (staff and non-staff) to login. I'm creating a separate app for only staff members and I'd like to have a separate endpoint link (.../acccount/staff-login) that would only allow staff members to get tokens. This seems pretty basic but I haven't been able to find anything for this.
Edit: MY SOLUTION : I simply reused the existing ObtainAuthToken view, and added a simple check for is_staff, if the user isn't staff I send an error status.
class StaffAuthToken(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
if coreapi_schema.is_enabled():
schema = ManualSchema(
fields=[
coreapi.Field(
name="username",
required=True,
location='form',
schema=coreschema.String(
title="Username",
description="Valid username for authentication",
),
),
coreapi.Field(
name="password",
required=True,
location='form',
schema=coreschema.String(
title="Password",
description="Valid password for authentication",
),
),
],
encoding="application/json",
)
def get_serializer_context(self):
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}
def get_serializer(self, *args, **kwargs):
kwargs['context'] = self.get_serializer_context()
return self.serializer_class(*args, **kwargs)
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
if (not user.is_staff): ## this is what I added
return Response(status = status.HTTP_403_FORBIDDEN)
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
Solution
You can do this using two different link... 1.link_for_non-staf 2.link_for_staf Now listen that request in two different function in views.py.
def link_for_staff(request):
if request.method=="POST":
staff_form=AuthenticationForm(request,data=request.POST)
if form.is_valid():
username=staff_form.cleaned_data.get('username')
passowrd=staff_form.cleaned_data.get('password')
user=authenticate(username=username,passowrd=password)
if user is not None:
login(request,user)
return redirect('home')
Similarly you can create a another function to listen non-staff login request. In your staff link no any other can login. Don't forgot to import all import modules and variable names may be differ according to your choice.
Answered By - Vishal Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.