In Uncategorized

Source Code:

Steps Overview

  1. Configure authtoken
  2. Create Tokens + Connect to users
  3. Retrieve Token
  4. Restrict page access Configure authtoken
  5. Get Users Data
1 – Configure authtoken

Run “python migrate” to create add token to database and create a user if you have not yet.

2 – Create Tokens + Connect to users

No when you login to your admin page the “Token” object will be available. We will need to create a token and attach it to a user. The token automaticly generates a key when created so we dont have to.

We will normally have a token generated every time a user is created using “Signals” but for now we will manually create one by selecting a user and saving.

3 – Retrieve Token

Django provides a built in view for us that when given a valid username or email and password will return us a token. We will use this view in our url paths to send POST data from our login form.

Now that we have our url set up to retrive our users password we need a form to send data to that URL and retrieve the users assigned token. For now we will do nothing beyond just showing the token in the response.

Here is what our login page looks like:

If we type in our user name and password we should see the following in our console.

4 – Restrict page access Configure authtoken

No lets set some restrictions and logic for users with and without authentication. Lets first start by accessing our browsers localStorage property and add our token to it.

Add in you conditionals to you form again and submit it. You should now be able to see your token in local storage.

Before we add logic to our form lets restrict our home page for anyone without a token. Here is what our “logged in” page will look like

The login we added checks if we have a token BEFORE the page loads. if we do not, we are redirect to the login page. we can add this logic on every page we want to restrict.

Finally on our login page we add the opposite to the top and as if we are logged in. If yes then redirect us to the home page. In our success function after the token is added we redrect the user to the home page if they are authorized.

5  – Get Users Data

In most cases we will most likley need to render the logged in users personal information.

First lets serialize the user by create a UserSerializer in a file.

Next we need to create a view that handles the request for the user and serializers his/her information.

lets make sure we have the URL path to handle this view

And last but not least lests request the users information in our template. We wont render anymore HTML but instead will show it in our console.

Here is our response:

Source Code:

Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.