def get_user(request): """Get session and profile.""" # Check if the user is authenticated if not request.user.is_authenticated: return Response({"message": "not logged in"}, status=401) # Check if the user has a profile try: queryset = UserProfileFullSerializer.setup_eager_loading( UserProfile.objects) user_profile = queryset.get(user=request.user) profile_serialized = UserProfileFullSerializer( user_profile, context={'request': request}) except UserProfile.DoesNotExist: return Response({'message': "UserProfile doesn't exist"}, status=500) # Count this as a ping user_profile.last_ping = timezone.now() user_profile.save(update_fields=['last_ping']) # Return the details and nested profile return Response({ 'sessionid': request.session.session_key, 'user': request.user.username, 'profile_id': user_profile.id, 'profile': profile_serialized.data })
def perform_login(request): """ Perform login and retain session. """ username = request.GET.get('username') password = request.GET.get('password') user = authenticate(username=username, password=password) if user: # load user profile queryset = UserProfileFullSerializer.setup_eager_loading( UserProfile.objects) user_profile = queryset.get(user=user) login(request, user) # Return the session id return Response( { 'sessionid': request.session.session_key, 'user': user.username, 'profile_id': user_profile.id, 'profile': UserProfileFullSerializer(user_profile, context={ 'request': request }).data }, status=200) return HttpResponse("Invalid login credentials given!")
def update_me(self, request): """Update current user.""" serializer = UserProfileFullSerializer( request.user.profile, data=request.data, context=self.get_serializer_context()) if not serializer.is_valid(): return Response({'error': 'validation failed'}, status=400) serializer.save() return Response(serializer.data)
def retrieve(self, request, pk): try: UUID(pk, version=4) return super().retrieve(self, request, pk) except ValueError: queryset = UserProfileFullSerializer.setup_eager_loading( UserProfile.objects) profile = get_object_or_404(queryset, ldap_id=pk) return Response( UserProfileFullSerializer(profile, context={ 'request': request }).data)
def retrieve_me(self, request): """Get current user.""" queryset = UserProfileFullSerializer.setup_eager_loading( UserProfile.objects) user_profile = queryset.get(user=request.user) # Update fcm id if present if 'fcm_id' in request.GET: user_profile.fcm_id = request.GET['fcm_id'] user_profile.save() return Response( UserProfileFullSerializer( user_profile, context=self.get_serializer_context()).data)
def update_me(self, request): """Update current user.""" # Create device instead of updating profile if 'fcm_id' in request.data: update_fcm_device(request, request.data.pop('fcm_id', None)) serializer = UserProfileFullSerializer( request.user.profile, data=request.data, context=self.get_serializer_context()) if not serializer.is_valid(): return Response(serializer.errors, status=400) serializer.save() return Response(serializer.data)
def retrieve_me(self, request): """Get current user.""" queryset = UserProfileFullSerializer.setup_eager_loading( UserProfile.objects) user_profile = queryset.get(user=request.user) # WARNING: DEPREACATED # Update fcm id if present if 'fcm_id' in request.GET: update_fcm_device(request, request.GET['fcm_id']) return Response( UserProfileFullSerializer( user_profile, context=self.get_serializer_context()).data)
def update_me(self, request): """Update current user.""" # Create device instead of updating profile if 'fcm_id' in request.data: update_fcm_device(request, request.data.pop('fcm_id', None)) # Check if all fields are exposed ones if any(f not in UserProfile.ExMeta.user_editable for f in request.data): return forbidden_no_privileges() # Count as a ping profile = request.user.profile profile.last_ping = timezone.now() profile.active = True serializer = UserProfileFullSerializer( profile, data=request.data, context=self.get_serializer_context()) if not serializer.is_valid(): return Response(serializer.errors, status=400) serializer.save() return Response(serializer.data)
def get_user(request): """Get session and profile.""" # Check if the user is authenticated if not request.user.is_authenticated: return Response({"message":"not logged in"}, status=401) # Check if the user has a profile try: user_profile = UserProfile.objects.get(user=request.user) profile_serialized = UserProfileFullSerializer( user_profile, context={'request': request}) except UserProfile.DoesNotExist: return Response({'message': "UserProfile doesn't exist"}, status=500) # Return the details and nested profile return Response({ 'sessionid': request.session.session_key, 'user': request.user.username, 'profile_id': user_profile.id, 'profile': profile_serialized.data })
def perform_login(auth_code, redir, request): """Perform login with code and redir.""" post_data = 'code=' + auth_code + '&redirect_uri=' + redir + '&grant_type=authorization_code' # Get our access token response = requests.post( settings.SSO_TOKEN_URL, data=post_data, headers={ "Authorization": "Basic " + settings.SSO_CLIENT_ID_SECRET_BASE64, "Content-Type": "application/x-www-form-urlencoded" }, verify=not settings.SSO_BAD_CERT) response_json = response.json() # Check that we have the access token if 'access_token' not in response_json: return Response(response_json, status=400) # Get the user's profile profile_response = requests.get( settings.SSO_PROFILE_URL, headers={ "Authorization": "Bearer " + response_json['access_token'], }, verify=not settings.SSO_BAD_CERT) profile_json = profile_response.json() # Check if we got at least the user's SSO id if 'id' not in profile_json: return Response(profile_response, status=400) # Check that we have basic details like name and roll no. required_fields = ['first_name', 'roll_number'] if not all([(field in profile_json) for field in required_fields]): return Response({'message': 'Name and roll_number not present'}, status=403) username = str(profile_json['id']) roll_no = str(profile_json['roll_number']) # Check if a user exists with same username or roll number query = Q(username=username) if roll_no: query = query | Q(profile__roll_no=roll_no) user = User.objects.filter(query).first() # Create a new user if not found if not user: user = User.objects.create_user(username) # Set username again in case LDAP ID changed user.username = username # Check if User has a profile and create if not try: queryset = UserProfileFullSerializer.setup_eager_loading(UserProfile.objects) user_profile = queryset.get(user=user) except UserProfile.DoesNotExist: user_profile = UserProfile.objects.create(user=user, name='iitbuser') # Fill models with new data fill_models_from_sso(user_profile, user, profile_json) # Log in the user login(request, user) request.session.save() # Deprecated: update fcm id fcm_id = request.GET.get('fcm_id') if fcm_id is not None: update_fcm_device(request, fcm_id) # Return the session id return Response({ 'sessionid': request.session.session_key, 'user': user.username, 'profile_id': user_profile.id, 'profile': UserProfileFullSerializer( user_profile, context={'request': request}).data })
def login(request): """Log in. Uses the `code` and `redir` query parameters.""" # Check if we have the auth code auth_code = request.GET.get('code') if auth_code is None: return Response({"message" : "{?code} is required"}, status=400) # Construt post data to get token redir = request.GET.get('redir') if redir is None: return Response({"message" : "{?redir} is required"}, status=400) post_data = 'code=' + auth_code + '&redirect_uri=' + redir + '&grant_type=authorization_code' # Get our access token response = requests.post( settings.SSO_TOKEN_URL, data=post_data, headers={ "Authorization": "Basic " + settings.SSO_CLIENT_ID_SECRET_BASE64, "Content-Type": "application/x-www-form-urlencoded" }, verify=False) response_json = response.json() # Check that we have the access token if not 'access_token' in response_json: print(response.content) return Response(response_json, status=400) # Get the user's profile profile_response = requests.get( settings.SSO_PROFILE_URL, headers={ "Authorization": "Bearer " + response_json['access_token'], }, verify=False) profile_json = profile_response.json() # Print the profile for debugging print(profile_response.content) # Check if we got at least the user's SSO id if not 'id' in profile_json: return Response(profile_response, status=400) # Check that we have basic details like name and roll no. required_fields = ['first_name', 'roll_number'] if not all([(field in profile_json) for field in required_fields]): return Response({'message': 'Name and roll_number not present'}, status=403) username = str(profile_json['id']) # Check if the User exists, otherwise create a new object try: user = User.objects.get(username=username) except User.DoesNotExist: user = User.objects.create_user(username) # Check if User has a profile and create if not try: user_profile = UserProfile.objects.get(user=user) except UserProfile.DoesNotExist: user_profile = UserProfile.objects.create(user=user, name='iitbuser') # Fill models with new data fill_models_from_sso(user_profile, user, profile_json) fcm_id = request.GET.get('fcm_id') if fcm_id is not None: user_profile.fcm_id = fcm_id user_profile.save() # Log in the user login(request, user) request.session.save() # Return the session id return Response({ 'sessionid': request.session.session_key, 'user': user.username, 'profile_id': user_profile.id, 'profile': UserProfileFullSerializer( user_profile, context={'request': request}).data })