Integration of Django Tastypie with Angular for secure user authentication

I'm currently facing an issue where I cannot establish a connection to the Django server. Upon checking the browser console, I noticed the following error message:

[![console error][1]][1]

My setup involves using Tastypie along with a UserResource class:

class UserResource(ModelResource):

class Meta:
    queryset = User.objects.all()
    fields = ['first_name', 'last_name', 'email']
    allowed_methods = ['get', 'post']
    resource_name = 'user'

def override_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/login%s$" %
            (self._meta.resource_name, trailing_slash()),
            self.wrap_view('login'), name="api_login"),
        url(r'^(?P<resource_name>%s)/logout%s$' %
            (self._meta.resource_name, trailing_slash()),
            self.wrap_view('logout'), name='api_logout'),
    ]

def login(self, request, **kwargs):
    self.method_check(request, allowed=['post'])

    data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))

    username = data.get('username', '')
    password = data.get('password', '')

    user = authenticate(username=username, password=password)
    if user:
        if user.is_active:
            login(request, user)
            return self.create_response(request, {
                'success': True
            })
        else:
            return self.create_response(request, {
                'success': False,
                'reason': 'disabled',
                }, HttpForbidden )
    else:
        return self.create_response(request, {
            'success': False,
            'reason': 'incorrect',
            }, HttpUnauthorized )

def logout(self, request, **kwargs):
    self.method_check(request, allowed=['get'])
    if request.user and request.user.is_authenticated():
        logout(request)
        return self.create_response(request, { 'success': True })
    else:
        return self.create_response(request, { 'success': False }, HttpUnauthorized)

Additionally, I've implemented a loginController in my client-side code to send a POST request with a username and password:

    module.controller('LoginController', ['$scope','$http',
      function($scope, $http) {
        $http({
              method: 'POST',
              data: {'username' : 'test', 'password' : 'test123' },
              url: 'http://localhost:8000/api/v1/user/login/'
            }).then(function successCallback(response) {
                console.log("OK Response");
                console.log(response.data);
                $scope.orders = response.data.objects;
              }, function errorCallback(response) {
                console.log("NO Response");
        });
 }]);

Answer №1

In order to handle requests effectively, it is essential to provide the backend with a list of permitted hosts. You can refer to this gist for a code snippet, or explore the django-cors-headers package which addresses the Cross-Domain requests issue.

By using django-cors-headers, you have the ability to specify which domains can make requests, either individually or through regular expressions. This feature is particularly handy for managing multiple subdomains accessing the same API, among other customizable options.

Best of luck with your implementation!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a Karma/Selenium issue while attempting to connect to: http://:9876/?id=77115711

After executing the command karma start, I encountered the following error: INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/ INFO [launcher]: Launching browser selenium_chrome with concurrency 5 INFO [launcher]: Starting browser chrome vi ...

Using the Django template tags template, you can merge the method call within the {{ }} with the context variable in the template

In attempting to make the output of one template tag rely on another template tag, my use case is as follows: I have a list of headers that includes all the columns I want displayed in a table, along with the corresponding model column and visibility statu ...

Controller binding is not possible without the directive 'tabset' and its controller

I'm brand new to angular, and I've hit a roadblock with directive communication. Specifically, I'm getting the error message Cannot bind to controller without directive 'tabset's controller. Here is my Code HTML code <tabset ...

I am encountering issues with my JavaScript files that appear to be following the correct path, however they are not functioning properly. Error messages such as SyntaxError: expected expression

I am currently working on a Yii2 application. My goal is to utilize the JavaScript and CSS files from the common folder in my backend. The paths for these files are within the common/web/js and common/web/css directories respectively. To achieve this, I ...

Encountered a Gulp error: unable to spawn process due to E

gulpfile.js 'use strict'; var gulp = require('gulp'); gulp.paths = { src: 'src', dist: 'dist', tmp: '.tmp', e2e: 'e2e' }; require('require-dir')('./gulp'); gulp.ta ...

Issues with the proper functionality of the .ajax() method in Django

I'm currently facing an issue with my Ajax code while trying to interact with the database in order to edit model instances. I noticed that the first alert statement is functioning correctly, however, the subsequent alert statements are not working as ...

"An endless redirect loop error is occurring on this webpage, attributed to the combination of angularjs, rails, and devise

I have encountered a unique redirect issue while using AngularJS with Rails as my API server and Devise for authentication. When I log in successfully via ajax/json, everything works fine until I try to refresh the page or navigate to a different authentic ...

How can a TypeScript Angular directive utilize a function?

Recently, I have been following a unique Angular directive TypeScript pattern that I find really effective. The approach involves giving the directive its own isolated scope by creating a new controller. I encountered a scenario where I needed to invoke a ...

Is it possible to efficiently transfer a Tensorflow.js Tensor between Node.js processes?

Currently, I am in the process of building an AI model using Tensorflow.js and Node.js. One of the challenges I am facing is handling a large dataset in a streaming manner due to its size being too massive to be stored in memory all at once. This task invo ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

Tips for displaying two dynamic variables that are interdependent

For instance: Controller: AllBooks[{ book1:{ hardcover{price:25.99},e-book{price:1.99} } }, book2:{ hardcover{price:60.00},e-book{price:2.99} }]; $scope.bookchoice = function(selectedBook) { $rootScope.choice = selectedBook;} $scope.booktype = functio ...

Using Django, Django Rest Framework, React, and the integration with active directory

Background As part of a project for a client, I developed a React application (app.client.com) that interacts with a Django backend server utilizing the django-rest-framework (DRF) hosted on a separate domain (api.client.com). Currently, users log in usin ...

Wrap the text in Alphine using PHP

Currently, I am dealing with a situation where I have a string that needs to be wrapped using the Yii tag like Yii::t('app' , 'what_string'). The reason for this is because I require it to be translated per string on another page. Howev ...

Achieve video lazy loading in JavaScript or jQuery without relying on any external plugins

I've been experimenting with lazy loading videos using jQuery. While I've had success with lazy loading images and background-images using the same technique, I ran into issues when trying to apply it to videos. Here's what I've tried s ...

Discover the ultimate solution to disable JSHint error in the amazing Webstorm

I am encountering an error with my test files. The error message states: I see an expression instead of an assignment or function call. This error is being generated by the Chai library asserts. Is there a way to disable this warning in Webstorm? It high ...

Transferring information between components within AngularJS

export class AppComponent { title = 'shopping-cart'; ngOnInit() { } images = [ { title: 'At the beach', url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA ...

Gather data on webview requests and their corresponding responses

In my app, I am developing a feature that allows users to browse the web using a webview element. <webview src='user-generated'></webview> I am trying to find a way to capture all requests and responses generated during this process ...

I've come across this ajax url that seems promising, but I keep getting a GET 404 (Not Found)

I am attempting to validate using ajax and php. This is the code I have for my ajax: function PrintRecibopapel() { recibo = document.getElementById("txtCod").value; if(recibo == "") { alert("You must save the receipt before pr ...

An error was encountered: ReferenceError - Unable to locate google within the google.maps.Marker() function

<script src="https://maps.googleapis.com/maps/api/js?key=[KEY]&callback=initMap" async defer></script> <script> var user_lat,user_lng; var map; function initMap() { map = ...

Implementing jQuery functionality on elements that are generated dynamically

I'm facing a challenge when working with dynamic elements in jQuery and I really could use some help. Let me provide an example from my current project: main.js $(function () { renderPlaceList(places); setupVoting(); } The two functions are ...