# Path: src/accounts/models.py
# class OAuth(models.Model):
#     user = models.OneToOneField(User)   
# 
#     # account = models.CharField(max_length=50)
#     token = models.CharField(max_length=128)
#     uid = models.CharField(max_length=128)
#     expired = models.DateTimeField()


from .models import OAuth
from django.utils import timezone
from datetime import timedelta
from django.contrib.auth.models import User

class OAuthAuthenticationBackend(object):
    def authenticate(self, token=None, uid=None, expire_in=None):
        """
        check if uid aleady exists, create user if not exist
        """
        if token and uid:
            expired = self._get_expired_time(expire_in)
            try:
                user = User.objects.get(oauth__uid=uid)
                user.oauth.token = token
                user.oauth.expired = expired
                user.oauth.save()
            except User.DoesNotExist:
                user = User()
                user.username = "weibo_%s" % uid
                user.save()


# Path: src/accounts/models.py
# class OAuth(models.Model):
#     user = models.OneToOneField(User)   
# 
#     # account = models.CharField(max_length=50)
#     token = models.CharField(max_length=128)
#     uid = models.CharField(max_length=128)
#     expired = models.DateTimeField()


# Path: src/accounts/backends.py
from .models import OAuth
from django.utils import timezone
from datetime import timedelta
from django.contrib.auth.models import User


class OAuthAuthenticationBackend(object):
    def authenticate(self, token=None, uid=None, expire_in=None):
        """
        check if uid aleady exists, create user if not exist
        """
        if token and uid:
            expired = self._get_expired_time(expire_in)
            try:
                user = User.objects.get(oauth__uid=uid)
                user.oauth.token = token
                user.oauth.expired = expired
                user.oauth.save()
            except User.DoesNotExist:
                user = User()
                user.username = "weibo_%s" % uid
                user.save()


                user.oauth = OAuth(user=user, token=token, uid=uid, expired=expired)