# Path: oauth_provider/models.py
# class Token(models.Model):
#     REQUEST = 1
#     ACCESS = 2
#     TOKEN_TYPES = ((REQUEST, 'Request'), (ACCESS, 'Access'))
# 
#     key = models.CharField(max_length=KEY_SIZE, null=True, blank=True)
#     secret = models.CharField(
#         max_length=RSA_SECRET_SIZE, null=True, blank=True)
#     token_type = models.SmallIntegerField(choices=TOKEN_TYPES)
#     timestamp = models.IntegerField(default=int(time()))
#     is_approved = models.BooleanField(default=False)
# 
#     user = models.ForeignKey(AUTH_USER_MODEL, null=True,
#                              blank=True, related_name='tokens', on_delete=models.CASCADE)
#     consumer = models.ForeignKey(Consumer, on_delete=models.CASCADE)
#     # LRS CHANGE - LRS SCOPES AREN'T RESOURCES
#     # scope = models.ForeignKey(Scope, null=True, blank=True)
#     scope = models.CharField(
#         max_length=100, default="statements/write statements/read/mine")
# 
#     @property
#     def resource(self):
#         return self.scope
# 
#     @resource.setter
#     def resource(self, value):
#         self.scope = value
# 
#     # OAuth 1.0a stuff
#     verifier = models.CharField(max_length=VERIFIER_SIZE)
#     callback = models.CharField(
#         max_length=MAX_URL_LENGTH, null=True, blank=True)
#     callback_confirmed = models.BooleanField(default=False)
# 
#     objects = TokenManager()
# 
#     def __unicode__(self):
#         return "%s Token %s for %s" % (self.get_token_type_display(), self.key, self.consumer)
# 
#     def to_string(self, only_key=False):
#         token_dict = {
#             'oauth_token': self.key,
#             'oauth_token_secret': self.secret,
#             'oauth_callback_confirmed': self.callback_confirmed and 'true' or 'error'
#         }
#         if self.verifier:
#             token_dict['oauth_verifier'] = self.verifier
# 
#         if only_key:
#             del token_dict['oauth_token_secret']
#             del token_dict['oauth_callback_confirmed']
# 
#         return urllib.parse.urlencode(token_dict)
# 
#     def generate_random_codes(self):
#         """
#         Used to generate random key/secret pairings.
#         Use this after you've added the other data in place of save().
#         """
#         self.key = uuid.uuid4().hex
#         if not self.consumer.rsa_signature:
#             self.secret = get_random_string(length=REGULAR_SECRET_SIZE)
#         self.save()
# 
#     def get_callback_url(self, args=None):
#         """
#         OAuth 1.0a, append the oauth_verifier.
#         """
#         if self.callback and self.verifier:
#             parts = urllib.parse.urlparse(self.callback)
#             scheme, netloc, path, params, query, fragment = parts[:6]
#             if query:
#                 query = '%s&oauth_verifier=%s' % (query, self.verifier)
#             else:
#                 query = 'oauth_verifier=%s' % self.verifier
# 
#             # workaround for non-http scheme urlparse problem in py2.6 (issue
#             # #2)
#             if "?" in path:
#                 query = "%s&%s" % (path.split("?")[-1], query)
#                 path = "?".join(path[:-1])
# 
#             if args is not None:
#                 query += "&%s" % urllib.parse.urlencode(args)
#             return urllib.parse.urlunparse((scheme, netloc, path, params,
#                                         query, fragment))
#         args = args is not None and "?%s" % urllib.parse.urlencode(args) or ""
#         return self.callback and self.callback + args
# 
#     def set_callback(self, callback):
#         if callback != OUT_OF_BAND:  # out of band, says "we can't do this!"
#             if check_valid_callback(callback):
#                 self.callback = callback
#                 self.callback_confirmed = True
#                 self.save()
#             else:
#                 raise oauth.Error('Invalid callback URL.')
# 
#     # LRS CHANGE - ADDED HELPER FUNCTIONS
#     def scope_to_list(self):
#         return self.scope.split(" ")
# 
#     def timestamp_asdatetime(self):
#         return datetime.fromtimestamp(self.timestamp)
# 
#     def key_partial(self):
#         return self.key[:10]


from itertools import chain
from django import forms
from django.conf import settings
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .models import Token
        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = ' for="%s"' % final_attrs['id']
            else:
                label_for = ''

            cb = forms.CheckboxInput(
                final_attrs, check_test=lambda value: value in str_values)
            option_value = force_unicode(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_unicode(option_label))
            output.append('<label%s>%s %s</label><br />' %
                          (label_for, rendered_cb, option_label))
        output.append('</p>')
        return mark_safe('\n'.join(output))


class AuthorizeRequestTokenForm(forms.Form):
    scopes = forms.MultipleChoiceField(required=False, initial=FORM_SCOPES[0],
                                       widget=MyCheckboxSelectMultiple(), choices=FORM_SCOPES)
    authorize_access = forms.IntegerField(widget=forms.HiddenInput, initial=1)
    obj_id = forms.IntegerField(widget=forms.HiddenInput, initial=0)
    oauth_token = forms.CharField(widget=forms.HiddenInput)

    def clean(self):
        cleaned = super(AuthorizeRequestTokenForm, self).clean()

# Path: oauth_provider/models.py
# class Token(models.Model):
#     REQUEST = 1
#     ACCESS = 2
#     TOKEN_TYPES = ((REQUEST, 'Request'), (ACCESS, 'Access'))
# 
#     key = models.CharField(max_length=KEY_SIZE, null=True, blank=True)
#     secret = models.CharField(
#         max_length=RSA_SECRET_SIZE, null=True, blank=True)
#     token_type = models.SmallIntegerField(choices=TOKEN_TYPES)
#     timestamp = models.IntegerField(default=int(time()))
#     is_approved = models.BooleanField(default=False)
# 
#     user = models.ForeignKey(AUTH_USER_MODEL, null=True,
#                              blank=True, related_name='tokens', on_delete=models.CASCADE)
#     consumer = models.ForeignKey(Consumer, on_delete=models.CASCADE)
#     # LRS CHANGE - LRS SCOPES AREN'T RESOURCES
#     # scope = models.ForeignKey(Scope, null=True, blank=True)
#     scope = models.CharField(
#         max_length=100, default="statements/write statements/read/mine")
# 
#     @property
#     def resource(self):
#         return self.scope
# 
#     @resource.setter
#     def resource(self, value):
#         self.scope = value
# 
#     # OAuth 1.0a stuff
#     verifier = models.CharField(max_length=VERIFIER_SIZE)
#     callback = models.CharField(
#         max_length=MAX_URL_LENGTH, null=True, blank=True)
#     callback_confirmed = models.BooleanField(default=False)
# 
#     objects = TokenManager()
# 
#     def __unicode__(self):
#         return "%s Token %s for %s" % (self.get_token_type_display(), self.key, self.consumer)
# 
#     def to_string(self, only_key=False):
#         token_dict = {
#             'oauth_token': self.key,
#             'oauth_token_secret': self.secret,
#             'oauth_callback_confirmed': self.callback_confirmed and 'true' or 'error'
#         }
#         if self.verifier:
#             token_dict['oauth_verifier'] = self.verifier
# 
#         if only_key:
#             del token_dict['oauth_token_secret']
#             del token_dict['oauth_callback_confirmed']
# 
#         return urllib.parse.urlencode(token_dict)
# 
#     def generate_random_codes(self):
#         """
#         Used to generate random key/secret pairings.
#         Use this after you've added the other data in place of save().
#         """
#         self.key = uuid.uuid4().hex
#         if not self.consumer.rsa_signature:
#             self.secret = get_random_string(length=REGULAR_SECRET_SIZE)
#         self.save()
# 
#     def get_callback_url(self, args=None):
#         """
#         OAuth 1.0a, append the oauth_verifier.
#         """
#         if self.callback and self.verifier:
#             parts = urllib.parse.urlparse(self.callback)
#             scheme, netloc, path, params, query, fragment = parts[:6]
#             if query:
#                 query = '%s&oauth_verifier=%s' % (query, self.verifier)
#             else:
#                 query = 'oauth_verifier=%s' % self.verifier
# 
#             # workaround for non-http scheme urlparse problem in py2.6 (issue
#             # #2)
#             if "?" in path:
#                 query = "%s&%s" % (path.split("?")[-1], query)
#                 path = "?".join(path[:-1])
# 
#             if args is not None:
#                 query += "&%s" % urllib.parse.urlencode(args)
#             return urllib.parse.urlunparse((scheme, netloc, path, params,
#                                         query, fragment))
#         args = args is not None and "?%s" % urllib.parse.urlencode(args) or ""
#         return self.callback and self.callback + args
# 
#     def set_callback(self, callback):
#         if callback != OUT_OF_BAND:  # out of band, says "we can't do this!"
#             if check_valid_callback(callback):
#                 self.callback = callback
#                 self.callback_confirmed = True
#                 self.save()
#             else:
#                 raise oauth.Error('Invalid callback URL.')
# 
#     # LRS CHANGE - ADDED HELPER FUNCTIONS
#     def scope_to_list(self):
#         return self.scope.split(" ")
# 
#     def timestamp_asdatetime(self):
#         return datetime.fromtimestamp(self.timestamp)
# 
#     def key_partial(self):
#         return self.key[:10]


# Path: oauth_provider/forms.py
from itertools import chain
from django import forms
from django.conf import settings
from django.utils.encoding import force_text
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from .models import Token

        str_values = set([force_unicode(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = ' for="%s"' % final_attrs['id']
            else:
                label_for = ''

            cb = forms.CheckboxInput(
                final_attrs, check_test=lambda value: value in str_values)
            option_value = force_unicode(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_unicode(option_label))
            output.append('<label%s>%s %s</label><br />' %
                          (label_for, rendered_cb, option_label))
        output.append('</p>')
        return mark_safe('\n'.join(output))


class AuthorizeRequestTokenForm(forms.Form):
    scopes = forms.MultipleChoiceField(required=False, initial=FORM_SCOPES[0],
                                       widget=MyCheckboxSelectMultiple(), choices=FORM_SCOPES)
    authorize_access = forms.IntegerField(widget=forms.HiddenInput, initial=1)
    obj_id = forms.IntegerField(widget=forms.HiddenInput, initial=0)
    oauth_token = forms.CharField(widget=forms.HiddenInput)

    def clean(self):
        cleaned = super(AuthorizeRequestTokenForm, self).clean()

        t = Token.objects.get(id=cleaned.get('obj_id'))