1# Copyright (c) 2012-2016 Seafile Ltd. 2from rest_framework.authentication import SessionAuthentication 3from rest_framework.permissions import IsAuthenticated 4from rest_framework.response import Response 5from rest_framework.views import APIView 6from rest_framework import status 7 8from seahub.api2.throttling import UserRateThrottle 9from seahub.api2.utils import api_error 10from seahub.api2.models import Token 11 12from seahub.settings import ENABLE_GET_AUTH_TOKEN_BY_SESSION 13 14 15class AuthTokenBySession(APIView): 16 """ Get user's auth token. 17 """ 18 19 authentication_classes = (SessionAuthentication,) 20 permission_classes = (IsAuthenticated,) 21 throttle_classes = (UserRateThrottle,) 22 23 def get(self, request): 24 25 if not ENABLE_GET_AUTH_TOKEN_BY_SESSION: 26 error_msg = 'Feature is not enabled.' 27 return api_error(status.HTTP_403_FORBIDDEN, error_msg) 28 29 username = request.user.username 30 try: 31 token_obj = Token.objects.get(user=username) 32 token = token_obj.key 33 except Token.DoesNotExist: 34 token = '' 35 36 return Response({'token': token}) 37 38 def post(self, request): 39 40 if not ENABLE_GET_AUTH_TOKEN_BY_SESSION: 41 error_msg = 'Feature is not enabled.' 42 return api_error(status.HTTP_403_FORBIDDEN, error_msg) 43 44 username = request.user.username 45 if len(Token.objects.filter(user=username)) > 0: 46 return api_error(status.HTTP_409_CONFLICT, 'Token already exists.') 47 48 token_obj = Token.objects.add_or_update(username) 49 return Response({'token': token_obj.key}) 50 51 def delete(self, request): 52 53 if not ENABLE_GET_AUTH_TOKEN_BY_SESSION: 54 error_msg = 'Feature is not enabled.' 55 return api_error(status.HTTP_403_FORBIDDEN, error_msg) 56 57 username = request.user.username 58 Token.objects.filter(user=username).delete() 59 60 return Response({'success': True}) 61