4

i'm using rest_framework.authtoken.models Token. i can see 3 fields which is key, created_at and user_id.

Background of App:

I use chrome app as client for app, i want to use token authentication to connect with my APIs in django rest framework. and i want to store user_id and company_id in authtoken_token table. so i could store just the token key in chrome app localstorage,

enter image description here

  1. My question is how can i add an extra field like company_id to that model? i couldn't find any docs or articles about this.

  2. I've also Jamie's answer in this article to subclass the model but i don't know how.

Thanks!

Community
  • 1
  • 1
Binsoi
  • 383
  • 5
  • 13
  • Check [multi-table inheritance](https://docs.djangoproject.com/en/1.9/topics/db/models/#multi-table-inheritance) – Rahul Gupta Jun 08 '16 at 18:30

1 Answers1

5

Define you own authentication method: settings.py

    'DEFAULT_AUTHENTICATION_CLASSES': (
    'my_project.my_app.authentication.myOwnTokenAuthentication',
     ),

authentication.py

from rest_framework.authentication import TokenAuthentication
from my_project.my_app.models.token import MyOwnToken

class MyOwnTokenAuthentication(TokenAuthentication):
    model = MyOwnToken

model.py

import binascii
import os

from django.db import models
from django.utils.translation import ugettext_lazy as _
from my_project.companies.models import Company


class MyOwnToken(models.Model):
    """
    The default authorization token model.
    """
    key = models.CharField(_("Key"), max_length=40, primary_key=True)

    company = models.OneToOneField(
        Company, related_name='auth_token',
        on_delete=models.CASCADE, verbose_name="Company"
    )
    created = models.DateTimeField(_("Created"), auto_now_add=True)

    class Meta:
        verbose_name = _("Token")
        verbose_name_plural = _("Tokens")

    def save(self, *args, **kwargs):
        if not self.key:
            self.key = self.generate_key()
        return super(MyOwnToken, self).save(*args, **kwargs)

    def generate_key(self):
        return binascii.hexlify(os.urandom(20)).decode()

    def __str__(self):
        return self.keyDefine you own authentication method:
Machavity
  • 30,841
  • 27
  • 92
  • 100
mullerivan
  • 1,833
  • 1
  • 14
  • 15