How to check that a user is logged in from chrome extension when using django in backend

I’m developing a web site using django framework and I need to develop a chrome extension for this website. I want when the user click the icon of the extension check if the user is logged in my site to show a specific popup or show a logging popup (if the user is not logged yet).
Thank you in advance.

Django CSRF token failure risk

On our production server, periodically we suffer from many CSRF token failures. The site does work fine for the rest, and I am aware CSRF failures may be user-side errors. However, for example this morning we received a flood of new failures, so we want to exclude any other possibilities.

An example failure mail today:

{
   "GET": {},
   "COOKIES": {},
   "ERROR": "Referer checking failed - no Referer.",
   "USER": "AnonymousUser",
   "META": {
       "REMOTE_ADDR": "127.0.0.1",
       "mod_wsgi.version": "(4, 5, 20)",
       "DOCUMENT_ROOT": "/usr/local/apache2/htdocs",
       "SERVER_ADDR": "127.0.0.1",
       "HTTP_ACCEPT_ENCODING": "gzip, deflate, br",
       "wsgi.multithread": "True",
       "HTTP_FORWARDED_REQUEST_URI": "/",
       "CONTEXT_DOCUMENT_ROOT": "/usr/local/apache2/htdocs",
       "wsgi.file_wrapper": "",
       "mod_wsgi.path_info": "/",
       "HTTP_ORIGIN": "chrome-extension://aegnopegbbhjeeiganiajffnalhlkkjb",
       (...)
   },
   "POST": {}
}

Especially the HTTP_ORIGIN looks “interesting”: why is this Chrome extension scraping/bullying us?

So essentially: Do we need to be worried about this?

Thanks!

Django-Allauth: How to authenticate users via Chrome extension?

I’m building a Django web app with django-allauth handling user authentication.

As title, how do you expose a RESTful API to authenticate users from a Chrome extension? Taking into account of both:

  1. locally stored username & password hash string pairs and
  2. third party social log-in providers?

What is the best or simplest way to do this?

ConnectionAborted Error: [WinError 10053] in Django Service

I am working on Login,Registration of users through my Chrome extension. While registration in the extension, Django service is stopping abruptly and throughing some exceptions and errors.
The error Message is as follows:

C:UsersAnushaDesktopDjangoServices>python manage.py runserver
Performing system checks…

System check identified no issues (0 silenced).
March 08, 2018 - 11:15:04
Django version 2.0.1, using settings 'hello.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[08/Mar/2018 11:15:44] "POST /polls/? HTTP/1.1" 200 21
Traceback (most recent call last):
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 138, in run
    self.finish_response()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 180, in finish_response
    self.write(data)
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 274, in write
    self.send_headers()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 332, in send_headers
    self.send_preamble()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 255, in send_preamble
    ('Date: %srn' % format_date_time(time.time())).encode('iso-8859-1')
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 453, in _write
    result = self.stdout.write(data)
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libsocketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
[08/Mar/2018 11:15:44] "POST /polls/? HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 52297)
Traceback (most recent call last):
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 138, in run
    self.finish_response()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 180, in finish_response
    self.write(data)
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 274, in write
    self.send_headers()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 332, in send_headers
    self.send_preamble()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 255, in send_preamble
    ('Date: %srn' % format_date_time(time.time())).encode('iso-8859-1')
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 453, in _write
    result = self.stdout.write(data)
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libsocketserver.py", line 775, in write
    self._sock.sendall(b)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 141, in run
    self.handle_error()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libsite-packagesdjangocoreserversbasehttp.py", line 86, in handle_error
    super().handle_error()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 368, in handle_error
    self.finish_response()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 180, in finish_response
    self.write(data)
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 274, in write
    self.send_headers()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libsocketserver.py", line 639, in process_request_thread
    self.finish_request(request, client_address)
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libsocketserver.py", line 361, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libsocketserver.py", line 696, in __init__
    self.handle()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libsite-packagesdjangocoreserversbasehttp.py", line 154, in handle
    handler.run(self.server.get_app())
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefhandlers.py", line 144, in run
    self.close()
  File "C:UsersAnushaAppDataLocalProgramsPythonPython36-32libwsgirefsimple_server.py", line 35, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------
[08/Mar/2018 11:26:19] "GET /polls HTTP/1.1" 301 0
[08/Mar/2018 11:26:19] "GET /polls/ HTTP/1.1" 200 21
Not Found: /favicon.ico
[08/Mar/2018 11:26:20] "GET /favicon.ico HTTP/1.1" 404 2079"

How to make common authentication between 2 server – Rails & Django

the service I’m developing consists of chrome extension & web application.
For it I’m trying to create 2 server:

  • web application server (build by Rails)
  • API server(build by Django) to receive requests from chrome extension and process user data.

Those application use same database, same user information.

My question is how to authenticate users — in Rails app, users can sign-up and sign-in via form. But in API server, how to authenticate users?

One solution might be JWT authentication, user get JWT token from Rails server and send token to Django server, and Django server authenticate by JWT authorization.

Is that best practice — or simply sending username & password is better then this?

Thanks

Ajax POST request from Chrome extension to django fails with 400

I have a Django REST API running on Nginx + Gunicorn on my server (an AWS instance) and I’m trying to call this API from a Chrome extension using Ajax. I can’t make it work. The API itself seems to work fine – I can make a similar request with cURL and it works fine. However, when I try to do it from the extension, I’m getting 400 error. There is no authentication at the moment, both the website from which I’m calling and the Django app run on https (at first I thought this might be a problem), I added both of them to permissions in manifest.json. My call (from background.js) looks like this:

$.ajax({
    type: "POST",
    crossDomain: true,
    cache: false,
    url: 'https://**************/',
    data: JSON.stringify(collectedData),
    success: function(data, textStatus, xhr) {
        collectedData = [];
        server_response = xhr.status;
    },
    error: function(xhr, textStatus, error) {
        server_response = xhr.status;
    },
    dataType: "json"
}).always(function(){
    sendResponse({ status: server_response });
});

I’m running out of ideas. What am I doing wrong?

Send request from chrome extension to django

I am developing a chrome extension having three links login,registration,Sign out.
This is my html page in chrome extension

Login!

Registration!

SignOut!

Manifest file:

"background": {
        "scripts": ["popup.js"],
        "persistent": false
    },
  "browser_action": {

     "default_icon": "icon.png",
     "default_popup": "popup.html"
  },
  "externally_connectable": {
    "matches": ["*://localhost:*/"]
  },

  "permissions": [
     "http://localhost:8000/",
    "tabs", "contextMenus", "", "storage"
  ]
Popup.js:

function login() {
  chrome.tabs.executeScript({
    file: 'contentscript.js'    
  }); 
}
document.getElementById('login').addEventListener('click', login);

where i have developed login and registration pages in Django frame work and i have successfully registered and login in local host Django .But when I click a registration button in chrome extension i have to open Django registration page which is in local server. For this how to send request from chrome extension to Django and how to get request from chrome extension in Django.

Chrome Application Cache deleted when going Offline

I intend using a Service Worker to make a Web App available offline. The cache Storage shows the files when I have Internet Connection. However if I go Offline the cache seems to disappear. I do not have enabled the checkbox of Update on Reload in the Service Workers tab.

The fetch event of my service worker is:

self.addEventListener('fetch', function(e) {
  console.log('[ServiceWorker] Fetch', e.request.url);
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    })
  );
});

When I am Online the print for the console is:

An unknown error occurred when fetching the script.
Failed to load resource: net::ERR_INTERNET_DISCONNECTED service-worker.js

However when I am offline the console ouptut is the following:

[ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/bootstrap/CSS/bootstrap.css
service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/logo.png
cocoa.pythonanywhere.com/:1 Adding master entry to Application Cache with manifest https://cocoa.pythonanywhere.com/static/login/Offline/HTML/manifesto
service-worker.js:113 [ServiceWorker] Fetch https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css
service-worker.js:113 [ServiceWorker] Fetch https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js
service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/js/app.js
service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/bootstrap/js/jquery-3.1.1.min.js
service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/bootstrap/js/bootstrap.min.js
service-worker.js:113 [ServiceWorker] Fetch https://cocoa.pythonanywhere.com/static/login/js/diem.js
cocoa.pythonanywhere.com/:1 Slow network is detected. Fallback font will be used while loading: https://cocoa.pythonanywhere.com/static/login/bootstrap/fonts/glyphicons-halflings-regular.woff2
app.js:2 CLIENT: service worker registration in progress.
app.js:4 CLIENT: service worker registration complete.

When I am Online the application tab looks:

The Application Cache is poblated

The Application Cache is poblated and the Service Worker registered.

When I am Offline it appears like this:

The Cache is not poblated and the service worker not active

The Cache is not poblated and the service worker not active.

Why the javascript fetch API changes the request from POST to OPTIONS?

I just want to post the data to the API whenever the User clicks on the link or opens a link.

Below is the JSON format of the data i’m trying to post,

{
    "username": "somename",
    "email": "[email protected]",
    "mobile": "xxxxxxxxxx",
    "url": "https://www.atatus.com/blog/fetch-api/"
}

The manifest.json file is below,

{
    "manifest_version": 2,

    "name": "UserData save to Chrome",
    "description": "Save the data to the API",
    "version": "1.0",

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "login.html",
        "defult_title": "UserData save to Chrome"
    },
    "background": {
        "scripts": ["url.js", "popup.js"]
    },
    "permissions": [
        "activeTab",
        "storage",
        "history"
    ]
}

Below is the HTML file that’s used to pop up the form,




The popup.js is the javascript file which i’m using to store the data locally to the chrome storage,

function saveChanges() {

    var user = document.getElementById("id_username").value;
    var email_id = document.getElementById("id_email").value;
    var mobile_no = document.getElementById("id_mobile").value;

    chrome.storage.local.set({
        'username': user,
        'email': email_id,
        'mobile': mobile_no
    }, function() {
        alert("Data Saved Successfully " + user + " - " + email_id + " - " + mobile_no);
        window.close();
    });
}

document.getElementById("save").onclick=saveChanges;

And finally url.js file which runs in the background is below,

chrome.storage.local.get({"username": [], "email": [], "mobile": []}, 
function(user) {
    if (!user) {
        alert("You're not logged in.");
    }

    chrome.history.onVisited.addListener(function (data) {
        save_api(user, data);
    });
})


function save_api(user, data) {
    alert("Saving data....");
    var user_data = {
        "username": user.username,
        "email": user.email,
        "mobile": user.mobile,
        "url": data.url
    }

    alert(JSON.stringify(user_data));

    fetch("http://127.0.0.1:8000/api/extension/", {
        method: "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(user_data)
    });
}

The url for the request is,

url(r'^api/extension/$', extension_view.ExtensionAPI.as_view()),

Below code is the django views which holds the post method,

class ExtensionAPI(APIView):

    def get(self, request):
        acc = Account.objects.all()
        return Response(ExtensionSerializer(acc, many=True).data)

    def post(self, request):
        cust_user_name = request.data.get('username', None)
        cust_email = request.data.get('email', None)
        cust_mobile = request.data.get('mobile', None)
        cust_url = request.data.get('url', None)

        account_details = Account.objects.create(
            username=cust_user_name,
            email=cust_email,
            mobile=cust_mobile,
            url=cust_url
        )
        account_details.save()

        return Response({'status': 'success'})

Right now the probelm i’m facing is, everything works as per the expectations, except that fetch api. When i try to post the data it changes the type of request from post to options. And the data is also not saving to the database! Please someone help me fix this issue.