├── djxero ├── migrations │ ├── __init__.py │ ├── 0003_xeroprojectsuser.py │ ├── 0002_xero_secrets_defaults.py │ └── 0001_xero_initial.py ├── tests.py ├── templates │ └── xero │ │ └── interstitial.html ├── __init__.py ├── apps.py ├── signals.py ├── decorators.py ├── urls.py ├── admin.py ├── middleware.py ├── views.py └── models.py ├── setup.cfg ├── CHANGELOG.md ├── requirements.txt ├── MANIFEST.in ├── NOTICE ├── setup.py ├── .gitignore ├── README.md └── LICENSE /djxero/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | 2 | [bdist_wheel] 3 | universal=1 -------------------------------------------------------------------------------- /djxero/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 0.0.3 2 | - added basic support for guessing user details 3 | 4 | # 0.0.2 5 | - first public release 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django>=2.2.3,<3.0 2 | cryptography>=2.7,<3.0 3 | django-encrypted-model-fields>=0.5.8,<0.6 4 | pyxero>=0.9.1,<1.0 5 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include NOTICE 3 | include README.md 4 | include CHANGELOG.md 5 | include requirements.txt 6 | recursive-include djxero/templates/xero * 7 | recursive-include docs * 8 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Giacomo Lacava 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"). 4 | You may obtain a copy of the License at 5 | http://www.apache.org/licenses/LICENSE-2.0 6 | -------------------------------------------------------------------------------- /djxero/templates/xero/interstitial.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Authorize Xero 4 | 5 | 6 |
7 | Please click the button below to enable Xero. 8 | You will be redirected to Xero for authorization. 9 |
10 | 11 | 12 | -------------------------------------------------------------------------------- /djxero/__init__.py: -------------------------------------------------------------------------------- 1 | VERSION = (0, 0, 4) 2 | 3 | __title__ = 'django-xero' 4 | __version_info__ = VERSION 5 | __version__ = '.'.join(map(str, VERSION)) 6 | __author__ = 'Giacomo Lacava' 7 | __license__ = 'Apache Software License v.2' 8 | __copyright__ = 'Copyright (c) 2019 Giacomo Lacava ' 9 | 10 | __doc__ = """Xero integration for Django""" 11 | 12 | default_app_config = 'djxero.apps.DjxeroConfig' 13 | -------------------------------------------------------------------------------- /djxero/migrations/0003_xeroprojectsuser.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.3 on 2019-08-05 07:48 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ('djxero', '0002_xero_secrets_defaults'), 11 | ] 12 | 13 | operations = [ 14 | migrations.CreateModel( 15 | name='XeroProjectsUser', 16 | fields=[ 17 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 18 | ('prj_user_id', models.UUIDField(help_text='Xero user ID in the Projects API')), 19 | ('xerouser', models.ForeignKey(help_text='Regular Xero user ID', on_delete=django.db.models.deletion.CASCADE, related_name='prjuser', to='djxero.XeroUser')), 20 | ], 21 | ), 22 | ] 23 | -------------------------------------------------------------------------------- /djxero/apps.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from django.apps import AppConfig 14 | 15 | 16 | # noinspection PyUnresolvedReferences 17 | class DjxeroConfig(AppConfig): 18 | name = 'djxero' 19 | 20 | def ready(self): 21 | import djxero.signals 22 | return super().ready() 23 | -------------------------------------------------------------------------------- /djxero/signals.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from django.contrib.auth.signals import user_logged_out 14 | from django.dispatch import receiver 15 | 16 | 17 | @receiver(user_logged_out) 18 | def djxero_logout(sender, request, user, **kwargs): 19 | if user.xerouser: 20 | user.xerouser.last_token = None 21 | user.xerouser.save() 22 | -------------------------------------------------------------------------------- /djxero/decorators.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from django.utils.decorators import decorator_from_middleware 14 | 15 | from djxero.middleware import XeroMiddleware 16 | 17 | xero_required = decorator_from_middleware(XeroMiddleware) 18 | xero_required.__name__ = 'xero_required' 19 | xero_required.__doc__ = """ 20 | Decorator to require a valid Xero session in a view. 21 | On failure it redirects to view xero-interstitial. 22 | """ 23 | -------------------------------------------------------------------------------- /djxero/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from django.urls import path 14 | 15 | from .views import xero_auth_start, xero_auth_accept, xero_logout, \ 16 | xero_interstitial 17 | 18 | urlpatterns = [ 19 | path('start', xero_auth_start, name='xero-auth-start'), 20 | path('accepted', xero_auth_accept, name='xero-auth-accept'), 21 | path('logout', xero_logout, name='xero-logout'), 22 | path('please', xero_interstitial, name='xero-interstitial') 23 | ] 24 | -------------------------------------------------------------------------------- /djxero/admin.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from django.contrib import admin 14 | 15 | from djxero.models import XeroAuthFlowState, XeroUser, XeroSecret 16 | 17 | 18 | @admin.register(XeroAuthFlowState) 19 | class XeroAuthFlowAdmin(admin.ModelAdmin): 20 | date_hierarchy = "created_on" 21 | list_display = ('oauth_token', 'created_on', 'next_page') 22 | 23 | 24 | @admin.register(XeroUser) 25 | class XeroUserAdmin(admin.ModelAdmin): 26 | list_display = ('user', 'updated_on') 27 | search_fields = ['user__username', 28 | 'user__last_name', 'user__first_name', 29 | 'org'] 30 | 31 | 32 | @admin.register(XeroSecret) 33 | class XeroSecretAdmin(admin.ModelAdmin): 34 | list_display = ('name', 'label') 35 | -------------------------------------------------------------------------------- /djxero/migrations/0002_xero_secrets_defaults.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from django.db import migrations 14 | 15 | _DEFAULT_SECRETS = [('xero_consumer_key', 'Consumer Key'), 16 | ('xero_consumer_secret', 'Consumer Secret')] 17 | 18 | 19 | def load_defaults(apps, schema_editor): 20 | XeroSecret = apps.get_model('djxero', 'XeroSecret') 21 | db_alias = schema_editor.connection.alias 22 | defaults = [XeroSecret(name=name, label=label, value='') 23 | for name, label in _DEFAULT_SECRETS] 24 | XeroSecret.objects.using(db_alias).bulk_create(defaults) 25 | 26 | 27 | def purge_defaults(apps, schema_editor): 28 | XeroSecret = apps.get_model('djxero', 'XeroSecret') 29 | db_alias = schema_editor.connection.alias 30 | XeroSecret.objects.using(db_alias).filter( 31 | name__in=[key for key, label in _DEFAULT_SECRETS] 32 | ).delete() 33 | 34 | 35 | class Migration(migrations.Migration): 36 | dependencies = [ 37 | ('djxero', '0001_xero_initial') 38 | ] 39 | 40 | operations = [ 41 | migrations.RunPython(load_defaults, purge_defaults, elidable=True), 42 | ] 43 | -------------------------------------------------------------------------------- /djxero/middleware.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from datetime import datetime 14 | 15 | from django.contrib.auth import get_user_model 16 | from django.shortcuts import redirect 17 | from django.urls import reverse 18 | 19 | 20 | class XeroMiddleware: 21 | """ Middleware to require a valid Xero session """ 22 | 23 | def process_view(self, request, view_func, view_args, view_kwargs): 24 | """ 25 | Require a valid Xero session. 26 | On failure, redirect to view xero-interstitial. 27 | """ 28 | valid_auth = False 29 | try: 30 | xero_user = request.user.xerouser 31 | # note that all this is not TZ-aware, so all servers have to be on 32 | # same TZ 33 | if xero_user.token['oauth_expires_at'] >= datetime.now(): 34 | valid_auth = True 35 | except (get_user_model().xerouser.RelatedObjectDoesNotExist, 36 | AttributeError) as e: 37 | pass 38 | if not valid_auth: 39 | return redirect( 40 | '{url}?next={path}'.format(url=reverse('xero-interstitial'), 41 | path=request.path)) 42 | return None 43 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | from pathlib import Path 14 | 15 | from setuptools import setup 16 | 17 | import djxero 18 | 19 | BASEDIR = Path(__file__).parent 20 | 21 | # load readme contents 22 | README = open(BASEDIR / 'README.md').read() 23 | # read requirements from requirements.txt 24 | REQUIREMENTS = [] 25 | with open(BASEDIR / 'requirements.txt', 'r', encoding='utf-8') as reqtxt: 26 | for line in reqtxt: 27 | reqline = line.strip() 28 | if reqline and not reqline.startswith('#'): 29 | REQUIREMENTS.append(reqline) 30 | 31 | setup( 32 | name=djxero.__title__, 33 | version=djxero.__version__, 34 | packages=['djxero', ], 35 | include_package_data=True, 36 | license=djxero.__license__, 37 | description=djxero.__doc__, 38 | long_description=README, 39 | long_description_content_type='text/markdown', 40 | url='https://github.com/toyg/django-xero', 41 | author=djxero.__author__, 42 | author_email='giac@autoepm.com', 43 | install_requires=REQUIREMENTS, 44 | classifiers=[ 45 | 'Environment :: Web Environment', 46 | 'Framework :: Django', 47 | 'Framework :: Django :: 2.0', 48 | 'Framework :: Django :: 2.1', 49 | 'Framework :: Django :: 2.2', 50 | 'Intended Audience :: Developers', 51 | 'Intended Audience :: Financial and Insurance Industry', 52 | 'License :: OSI Approved :: Apache Software License', 53 | 'Development Status :: 4 - Beta', 54 | 'Operating System :: OS Independent', 55 | 'Programming Language :: Python', 56 | 'Programming Language :: Python :: 3 :: Only', 57 | 'Programming Language :: Python :: 3.7', 58 | 'Programming Language :: Python :: 3.6', 59 | 'Topic :: Internet :: WWW/HTTP', 60 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 61 | 'Topic :: Internet :: WWW/HTTP :: Session', 62 | 'Topic :: Office/Business :: Financial', 63 | 'Topic :: Office/Business :: Financial :: Accounting', 64 | ] 65 | ) 66 | -------------------------------------------------------------------------------- /djxero/migrations/0001_xero_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.3 on 2019-07-15 20:15 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.db.models.deletion 6 | import encrypted_model_fields.fields 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | initial = True 12 | 13 | dependencies = [ 14 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 15 | ] 16 | 17 | operations = [ 18 | migrations.CreateModel( 19 | name='XeroSecret', 20 | fields=[ 21 | ('name', models.CharField(help_text='Key to refer to this secret', max_length=255, primary_key=True, serialize=False)), 22 | ('value', encrypted_model_fields.fields.EncryptedTextField(blank=True, default='', help_text='Value to store (will be encrypted in database)')), 23 | ('label', models.CharField(blank=True, help_text='Human-readable label or description', max_length=255, null=True)), 24 | ], 25 | ), 26 | migrations.CreateModel( 27 | name='XeroUser', 28 | fields=[ 29 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 30 | ('last_token', encrypted_model_fields.fields.EncryptedTextField(blank=True, default='', help_text='JSON with last successful login details (so you can check if still logged on). ')), 31 | ('xero_id', models.CharField(blank=True, help_text="User ID in Xero. Note that this has to be manually retrieved with custom logic, because there is no way to find it from a token; so it's blank by default.", max_length=255, null=True)), 32 | ('org', models.CharField(blank=True, help_text='Identifier for the org the user belongs to, in theory', max_length=255, null=True)), 33 | ('created_on', models.DateTimeField(auto_now_add=True)), 34 | ('updated_on', models.DateTimeField(auto_now=True)), 35 | ('user', models.OneToOneField(help_text='Django user', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 36 | ('xero_email', models.EmailField(blank=True, help_text='Email registered with Xero. If present, it overrides User.email when dealing with Xero', max_length=255, null=True)), 37 | ], 38 | ), 39 | migrations.CreateModel( 40 | name='XeroAuthFlowState', 41 | fields=[ 42 | ('oauth_token', models.TextField(help_text='OAuth token to which this request belongs',primary_key=True, serialize=False)), 43 | ('state', encrypted_model_fields.fields.EncryptedTextField(help_text='JSON with all values to recreate a given PublicCredentials state')), 44 | ('next_page', models.CharField(help_text='Where to redirect once successful', max_length=255, null=True)), 45 | ('created_on', models.DateTimeField(auto_now_add=True)), 46 | ('auth_url', models.URLField(help_text='URL where the user was sent to authenticate', max_length=4096)), 47 | ], 48 | ), 49 | ] 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### JetBrains template 2 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 3 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 4 | 5 | # User-specific stuff 6 | .idea/**/workspace.xml 7 | .idea/**/tasks.xml 8 | .idea/**/usage.statistics.xml 9 | .idea/**/dictionaries 10 | .idea/**/shelf 11 | 12 | # Generated files 13 | .idea/**/contentModel.xml 14 | 15 | # Sensitive or high-churn files 16 | .idea/**/dataSources/ 17 | .idea/**/dataSources.ids 18 | .idea/**/dataSources.local.xml 19 | .idea/**/sqlDataSources.xml 20 | .idea/**/dynamic.xml 21 | .idea/**/uiDesigner.xml 22 | .idea/**/dbnavigator.xml 23 | 24 | # Gradle 25 | .idea/**/gradle.xml 26 | .idea/**/libraries 27 | 28 | # Gradle and Maven with auto-import 29 | # When using Gradle or Maven with auto-import, you should exclude module files, 30 | # since they will be recreated, and may cause churn. Uncomment if using 31 | # auto-import. 32 | # .idea/modules.xml 33 | # .idea/*.iml 34 | # .idea/modules 35 | # *.iml 36 | # *.ipr 37 | 38 | # CMake 39 | cmake-build-*/ 40 | 41 | # Mongo Explorer plugin 42 | .idea/**/mongoSettings.xml 43 | 44 | # File-based project format 45 | *.iws 46 | 47 | # IntelliJ 48 | out/ 49 | 50 | # mpeltonen/sbt-idea plugin 51 | .idea_modules/ 52 | 53 | # JIRA plugin 54 | atlassian-ide-plugin.xml 55 | 56 | # Cursive Clojure plugin 57 | .idea/replstate.xml 58 | 59 | # Crashlytics plugin (for Android Studio and IntelliJ) 60 | com_crashlytics_export_strings.xml 61 | crashlytics.properties 62 | crashlytics-build.properties 63 | fabric.properties 64 | 65 | # Editor-based Rest Client 66 | .idea/httpRequests 67 | 68 | # Android studio 3.1+ serialized cache file 69 | .idea/caches/build_file_checksums.ser 70 | 71 | ### Python template 72 | # Byte-compiled / optimized / DLL files 73 | __pycache__/ 74 | *.py[cod] 75 | *$py.class 76 | 77 | # C extensions 78 | *.so 79 | 80 | # Distribution / packaging 81 | .Python 82 | build/ 83 | develop-eggs/ 84 | dist/ 85 | downloads/ 86 | eggs/ 87 | .eggs/ 88 | lib/ 89 | lib64/ 90 | parts/ 91 | sdist/ 92 | var/ 93 | wheels/ 94 | pip-wheel-metadata/ 95 | share/python-wheels/ 96 | *.egg-info/ 97 | .installed.cfg 98 | *.egg 99 | MANIFEST 100 | 101 | # PyInstaller 102 | # Usually these files are written by a python script from a template 103 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 104 | *.manifest 105 | *.spec 106 | 107 | # Installer logs 108 | pip-log.txt 109 | pip-delete-this-directory.txt 110 | 111 | # Unit test / coverage reports 112 | htmlcov/ 113 | .tox/ 114 | .nox/ 115 | .coverage 116 | .coverage.* 117 | .cache 118 | nosetests.xml 119 | coverage.xml 120 | *.cover 121 | .hypothesis/ 122 | .pytest_cache/ 123 | 124 | # Translations 125 | *.mo 126 | *.pot 127 | 128 | # Django stuff: 129 | *.log 130 | local_settings.py 131 | db.sqlite3 132 | 133 | # Flask stuff: 134 | instance/ 135 | .webassets-cache 136 | 137 | # Scrapy stuff: 138 | .scrapy 139 | 140 | # Sphinx documentation 141 | docs/_build/ 142 | 143 | # PyBuilder 144 | target/ 145 | 146 | # Jupyter Notebook 147 | .ipynb_checkpoints 148 | 149 | # IPython 150 | profile_default/ 151 | ipython_config.py 152 | 153 | # pyenv 154 | .python-version 155 | 156 | # pipenv 157 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 158 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 159 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 160 | # install all needed dependencies. 161 | #Pipfile.lock 162 | 163 | # celery beat schedule file 164 | celerybeat-schedule 165 | 166 | # SageMath parsed files 167 | *.sage.py 168 | 169 | # Environments 170 | .env 171 | .venv 172 | env/ 173 | venv/ 174 | ENV/ 175 | env.bak/ 176 | venv.bak/ 177 | 178 | # Spyder project settings 179 | .spyderproject 180 | .spyproject 181 | 182 | # Rope project settings 183 | .ropeproject 184 | 185 | # mkdocs documentation 186 | /site 187 | 188 | # mypy 189 | .mypy_cache/ 190 | .dmypy.json 191 | dmypy.json 192 | 193 | # Pyre type checker 194 | .pyre/ 195 | 196 | # PyPI 197 | .pypirc 198 | 199 | .DS_Store 200 | .idea 201 | **/.DS_Store -------------------------------------------------------------------------------- /djxero/views.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | """ 13 | Default views to manage Xero integration. 14 | All views are marked with login_required since there is no way to find out 15 | any user detail from a Xero session, so you must have a valid user already 16 | registered. 17 | """ 18 | 19 | import logging 20 | 21 | from django.contrib.auth.decorators import login_required 22 | from django.http import HttpResponseBadRequest 23 | from django.shortcuts import redirect, get_object_or_404, render 24 | from django.urls import reverse, Resolver404, resolve 25 | from django.views.decorators.cache import never_cache 26 | from django.views.decorators.http import require_GET, require_POST 27 | 28 | from djxero.models import XeroAuthFlowState 29 | 30 | logger = logging.getLogger(__name__) 31 | 32 | 33 | def _validate_next(path): 34 | """ 35 | Utility to validate a "next" parameter and move on. 36 | todo: add xss protections here 37 | :param path: path fragment (e.g. /home ) 38 | :return: safe path 39 | """ 40 | try: 41 | resolve(path) 42 | return path 43 | except Resolver404: 44 | return '/' 45 | 46 | 47 | class XeroFlowException(Exception): 48 | pass 49 | 50 | 51 | @require_GET 52 | @never_cache 53 | @login_required 54 | def xero_auth_accept(request): 55 | """ 56 | Completes Oauth 1 flow from Xero 57 | :param request: HttpRequest with parameters 58 | oauth_verifier, oauth_token, and org 59 | :return: HttpResponseRedirect 60 | """ 61 | try: 62 | # retrieve the details for this session 63 | verifier = request.GET.get('oauth_verifier') 64 | token = request.GET.get('oauth_token') 65 | 66 | if not verifier or not token: 67 | raise XeroFlowException(request.GET.get('error', "unknown"), 68 | request.GET.get('error_description', 69 | 'unknown')) 70 | state_obj = get_object_or_404(XeroAuthFlowState, pk=token) 71 | # complete the flow 72 | xerouser = state_obj.complete_flow(verifier, request.user) 73 | # org should be validated, maybe...? 74 | xerouser.org = request.GET.get('org') 75 | xerouser.save() 76 | # find out where user should go next 77 | next_page = state_obj.next_page 78 | # we are done, forget this state 79 | state_obj.delete() 80 | # send user on its way 81 | return redirect(_validate_next(next_page)) 82 | except XeroFlowException as xfe: 83 | logger.exception(xfe) 84 | return HttpResponseBadRequest() 85 | 86 | 87 | @require_GET 88 | @never_cache 89 | @login_required 90 | def xero_auth_start(request): 91 | """ 92 | Start OAuth 1 flow with xero 93 | :param request: HttpRequest 94 | :return: HttpResponseRedirect 95 | """ 96 | # calculate where MS will send user on success 97 | acceptance_url = request.build_absolute_uri( 98 | reverse('xero-auth-accept', 99 | current_app=request.resolver_match.namespace)) 100 | 101 | # validate the 'next' parameter, we don't want an open proxy... 102 | next_page = _validate_next(request.GET.get('next')) 103 | # save state for later 104 | xerostate = XeroAuthFlowState.start_flow(acceptance_url, next_page) 105 | # send user to MS 106 | return redirect(xerostate.auth_url) 107 | 108 | 109 | @require_POST 110 | @never_cache 111 | @login_required 112 | def xero_logout(request): 113 | """ 114 | Completely remove a Xero account linked to the logged-on user 115 | :param request: HttpRequest 116 | :return: redirect to next page 117 | """ 118 | xerouser = request.user.xerouser 119 | # unlike o365, there is no point in keeping this around, so delete 120 | xerouser.delete() 121 | return redirect(_validate_next(request.POST.get('next'))) 122 | 123 | 124 | @require_GET 125 | @login_required 126 | def xero_interstitial(request): 127 | """ Ask user to link Xero """ 128 | next_page = request.GET.get('next') 129 | return render(request, 'xero/interstitial.html', 130 | context={'next': _validate_next(next_page)}) 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django-Xero 2 | [Xero](https://xero.com) integration for Django. 3 | 4 | ## Features 5 | This package allows users to authenticate to Xero via a Public App that you have 6 | registered on the [Xero Developer Portal](https://developer.xero.com). 7 | 8 | Whenever you want to trigger authentication with Xero, just redirect to the view 9 | `xero_auth_start` (either directly or via `resolve('xero-auth-start')` and this package 10 | will do the rest. 11 | The view also accepts an optional `next`parameter to control where the user will land 12 | on successful authentication; otherwise it will redirect to `/`. 13 | 14 | Xero sessions last for 30 minutes, but if you want to end them earlier, POST to 15 | the view `xero_logout` (again with an optional `next`). 16 | 17 | There is also a `@xero_required` decorator for views, which will automatically 18 | check if an active Xero session is present. If not, it will redirect to an interstitial page 19 | asking the user to do the authentication dance. You can control that page by creating a 20 | custom template `xero/interstitial.html` (make sure it has a link to `xero-auth-start` somewhere). 21 | 22 | Once authorized, in your view you will get a `.xerouser` attribute which you can use to do stuff like: 23 | ```python 24 | 25 | from djxero.decorators import xero_required 26 | 27 | @login_required 28 | @xero_required 29 | def my_view(request): 30 | client = request.user.xerouser.client 31 | contacts = client.contacts.all() 32 | ... 33 | ``` 34 | That client is a preconfigured `xero.Xero` object from [pyxero](https://github.com/freakboy3742/pyxero). 35 | 36 | ***you must have some other registration mechanism to create a regular Django 37 | user first*** (e.g. regular login page with some other auth system); this package only extends 38 | that `User` instance to attach a temporary Xero session. 39 | 40 | Some details will be exposed in `User` instances under `.xerouser`, but the Xero OAuth1 mechanism 41 | makes it difficult to reflect on the authenticated user. If your User model has the same email or 42 | firstname/lastname as recorded in Xero, you can try to guess its details. 43 | The heuristic is very basic and may or may not work: 44 | ```python 45 | # try to guess user details 46 | details_dict = xerouser.guess_user_details() 47 | 48 | # the Projects API also has a separate ID, so there is an attached model 49 | from djxero.models import XeroProjectsUser 50 | xero_prj_user = XeroProjectsUser(xerouser=xerouser) 51 | xero_prj_user.prj_user_id = xero_prj_user.guess_projects_user_id() 52 | xero_prj_user.save() 53 | # now you can retrieve the Projects-related ID from the main user object: 54 | def myview(request): 55 | ... 56 | # note you can have multiple IDs if you have multiple Orgs, so it's a linked with a ForeignKey 57 | prj_user_id = request.user.xerouser.prjuser.first().prj_user_id 58 | ... 59 | ``` 60 | 61 | ## Supported Platforms 62 | * Python 3.7 (should work on 3.5/3.6 too, but is untested). 63 | * Django 2 64 | 65 | ## Requirements 66 | django-xero should automatically download all necessary prerequisites, but I like 67 | to give credit where credit is due. 68 | We stand on the shoulders of the following giants: 69 | 70 | * [django-encrypted-model-fields](https://gitlab.com/lansharkconsulting/django/django-encrypted-model-fields/) 71 | * [pyxero](https://github.com/freakboy3742/pyxero) 72 | 73 | ## Installation 74 | 1. Install the package 75 | ``` 76 | pip install django-xero 77 | ``` 78 | 2. Add `encrypted_model_fields` and `djxero` to `INSTALLED_APPS` in your settings. 79 | Note that the authentication system is required. 80 | ```python 81 | INSTALLED_APPS = [ 82 | 'django.contrib.auth', 83 | 'django.contrib.sessions', 84 | ... 85 | 'encrypted_model_fields', 86 | 'djxero', 87 | ... 88 | ] 89 | ``` 90 | 3. Generate an encryption key: 91 | ```bash 92 | python -c 'import base64; import os; print(base64.urlsafe_b64encode(os.urandom(32)))' 93 | ``` 94 | and add it to your settings. NOTE: in production, you want to store this safely. 95 | ```python 96 | FIELD_ENCRYPTION_KEY = b'A7c4T1Kx3XmttUjm2cX8ScYcUEdF7RzFziEzfoBO7x4=' 97 | ``` 98 | 4. Run migrations to create the necessary objects 99 | ```bash 100 | python manage.py migrate djxero 101 | ``` 102 | 5. Set the Xero secrets for your public app. You can do this from the admin site (easier), 103 | or directly via `manage.py shell`: 104 | ```python 105 | from djxero.models import XeroSecret 106 | consumer_key = XeroSecret.objects.get(pk='xero_consumer_key') 107 | consumer_key.value = 'your key' 108 | consumer_key.save() 109 | consumer_secret = XeroSecret.objects.get(pk='xero_consumer_secret') 110 | consumer_secret.value = 'your secret' 111 | consumer_secret.save() 112 | ``` 113 | 6. in your project `urls.py`, add the following: 114 | ```python 115 | urlpatterns = [ 116 | path('xero/', include('djxero.urls')), 117 | ... 118 | ] 119 | ``` 120 | 121 | 122 | ## Issues 123 | For problems, file an issue on [GitHub](https://github.com/toyg/django-xero). 124 | The author is available for hire (hint hint). 125 | 126 | ## Credits and License 127 | Copyright (c) 2019 [Giacomo Lacava](https://linkedin.com/in/glacava). 128 | 129 | Released under the terms of the Apache Software License, version 2. 130 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /djxero/models.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019 Giacomo Lacava 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # http://www.apache.org/licenses/LICENSE-2.0 7 | # Unless required by applicable law or agreed to in writing, software 8 | # distributed under the License is distributed on an "AS IS" BASIS, 9 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | # See the License for the specific language governing permissions and 11 | # limitations under the License. 12 | 13 | import json 14 | import logging 15 | from datetime import datetime 16 | 17 | import requests 18 | from django.conf import settings 19 | from django.core.serializers.json import DjangoJSONEncoder 20 | from django.db import models 21 | from django.db.models import CASCADE 22 | from encrypted_model_fields.fields import EncryptedTextField 23 | from xero import Xero 24 | from xero.auth import PublicCredentials 25 | 26 | logger = logging.getLogger(__name__) 27 | 28 | DATETIME_FIELDS = ['oauth_expires_at', 'oauth_authorization_expires_at'] 29 | 30 | 31 | def _datetime_parser_hook(adict): 32 | """ Utility for json deserialization of naive datetimes. """ 33 | for field in DATETIME_FIELDS: 34 | if field in adict: 35 | adict[field] = datetime.strptime(adict[field] + '000', 36 | "%Y-%m-%dT%H:%M:%S.%f") 37 | return adict 38 | 39 | 40 | # todo: make secret-handling more flexible 41 | def get_secret(param): 42 | try: 43 | secret = XeroSecret.objects.get(name=param) 44 | return secret.value 45 | except XeroSecret.DoesNotExist: 46 | return None 47 | 48 | 49 | def get_xero_consumer_key(): 50 | return get_secret('xero_consumer_key') 51 | 52 | 53 | def get_xero_consumer_secret(): 54 | return get_secret('xero_consumer_secret') 55 | 56 | 57 | # 2019-07-10T11:26:05.125 58 | class XeroSecret(models.Model): 59 | """ 60 | Configuration data that has to be protected. 61 | """ 62 | name = models.CharField(max_length=255, primary_key=True, 63 | help_text="Key to refer to this secret") 64 | value = EncryptedTextField(blank=True, default='', 65 | help_text="Value to store " 66 | "(will be encrypted in database)") 67 | label = models.CharField(max_length=255, blank=True, null=True, 68 | help_text='Human-readable label or description') 69 | 70 | def __str__(self): 71 | return self.name 72 | 73 | 74 | class XeroAuthFlowState(models.Model): 75 | """ Temporary storage for details of in-flow auth requests. 76 | Likely to be replaced with redis or something later on.""" 77 | oauth_token = models.TextField(primary_key=True, 78 | help_text="OAuth token to which " 79 | "this request belongs") 80 | state = EncryptedTextField(help_text="JSON with all values to " 81 | "recreate a given " 82 | "PublicCredentials state") 83 | auth_url = models.URLField(null=False, blank=False, 84 | max_length=4096, 85 | help_text="URL where the user was sent to " 86 | "authenticate") 87 | next_page = models.CharField(max_length=255, 88 | null=True, 89 | blank=False, 90 | help_text="Where to redirect once successful") 91 | 92 | created_on = models.DateTimeField(auto_now_add=True) 93 | 94 | def __str__(self): 95 | return self.created_on.isoformat() + ' ' + \ 96 | json.loads(self.state)['oauth_token'] 97 | 98 | @classmethod 99 | def start_flow(cls, acceptance_url, next_page=None): 100 | """ 101 | Start authorization flow 102 | """ 103 | # instantiating credentials automatically starts the flow 104 | creds = PublicCredentials(get_xero_consumer_key(), 105 | get_xero_consumer_secret(), 106 | acceptance_url) 107 | # save state for later 108 | af_state = cls(state=json.dumps(creds.state, 109 | cls=DjangoJSONEncoder), 110 | oauth_token=creds.oauth_token, 111 | next_page=next_page) 112 | af_state.auth_url = creds.url 113 | af_state.save() 114 | return af_state 115 | 116 | def complete_flow(self, verification_code, user): 117 | """ Complete Authorization flow 118 | Note that you must already have a Django user, since Xero won't tell you 119 | anything about the logged-on user. 120 | 121 | :param verification_code: code to verify the original request 122 | :param user: User instance 123 | :returns XeroUser instance 124 | """ 125 | # rebuild our connection 126 | state_dict = json.loads(self.state, object_hook=_datetime_parser_hook) 127 | creds = PublicCredentials(**state_dict) 128 | creds.verify(verification_code) 129 | xero_user = XeroUser.from_state(creds, user) 130 | return xero_user 131 | 132 | 133 | class XeroUser(models.Model): 134 | """ Xero account linked to a User """ 135 | user = models.OneToOneField(settings.AUTH_USER_MODEL, 136 | on_delete=CASCADE, 137 | null=False, blank=False, 138 | help_text="Django user") 139 | org = models.CharField(max_length=255, 140 | blank=True, null=True, 141 | help_text="Identifier for the org the user belongs " 142 | "to, in theory") 143 | last_token = EncryptedTextField(blank=True, default='', 144 | help_text="JSON with last successful login " 145 | "details (so you can check if " 146 | "still logged on). ") 147 | xero_id = models.CharField(max_length=255, blank=True, null=True, 148 | help_text="User ID in Xero. " 149 | "Note that this has to be manually " 150 | "retrieved with custom logic, because " 151 | "there is no way to find it from " 152 | "a token; so it's blank by default.") 153 | xero_email = models.EmailField(max_length=255, blank=True, null=True, 154 | help_text="Email registered with Xero. " 155 | "If present, it overrides " 156 | "User.email when dealing with Xero") 157 | created_on = models.DateTimeField(auto_now_add=True) 158 | updated_on = models.DateTimeField(auto_now=True) 159 | 160 | def __str__(self): 161 | return f"{self.user.first_name} {self.user.last_name}" 162 | 163 | @classmethod 164 | def from_state(cls, creds: PublicCredentials, user): 165 | """ given a token reference, retrieve or construct a XeroUser instance. 166 | Note that you must already have a Django user, since Xero won't tell you 167 | anything about the logged-on user. 168 | :param creds: PublicCredentials instance with a valid session 169 | :param user: User instance 170 | :returns: XeroUser instance 171 | """ 172 | if not creds.verified: 173 | raise Exception("Trying to create a XeroUser with " 174 | "an invalid session") 175 | 176 | xero_user, created = cls.objects.get_or_create( 177 | user=user 178 | ) 179 | xero_user.last_token = json.dumps(creds.state, cls=DjangoJSONEncoder) 180 | xero_user.save() 181 | return xero_user 182 | 183 | @property 184 | def token(self): 185 | """ 186 | Get a dict with the current token info 187 | :return: dict 188 | """ 189 | return json.loads(self.last_token, object_hook=_datetime_parser_hook) 190 | 191 | @property 192 | def client(self): 193 | """ 194 | Get a ready-made xero.Xero object 195 | :return: xero.Xero instance 196 | """ 197 | return Xero(credentials=PublicCredentials(**self.token), 198 | user_agent=get_xero_consumer_key()) 199 | 200 | def guess_user_details(self): 201 | """ 202 | Xero provides no way to find user details from a oauth1.0 token, but 203 | if we have a prepopulated user we can make an educated guess. 204 | This is not foolproof, of course, which is why we don't automatically 205 | set the xero_id field. 206 | Use at your own risk. 207 | :return: dict with user details that we *think* might be from the user 208 | who generated the token, or None if not found anything 209 | """ 210 | filters = [ 211 | # django_field_name, xero_field_name 212 | ('email', 'emailaddress'), 213 | ('first_name', 'firstname'), 214 | ('last_name', 'lastname') 215 | ] 216 | 217 | params = {xerokey: getattr(self.user, djkey) 218 | for djkey, xerokey in filters} 219 | 220 | if self.xero_email: 221 | params['emailaddress'] = self.xero_email 222 | 223 | while True: 224 | result = self.client.users.filter(**params) 225 | if len(result) > 0: 226 | return result[0] 227 | 228 | if params.get('emailaddress', None): 229 | # try again with just the email 230 | params.pop('firstname') 231 | params.pop('lastname') 232 | else: 233 | break 234 | 235 | return None 236 | 237 | def _request_data(self, verb, url, **kwargs): 238 | """ 239 | Utility for authenticated calls to Xero apis not yet supported by 240 | pyxero, getting json back. Note that pagination is NOT handled. 241 | 242 | :param verb: 'get','post',... 243 | :param url: url to call 244 | :param kwargs: extra parameters to pass to requests 245 | :return: list of returned json dicts 246 | """ 247 | result = self._request(verb, url, **kwargs) 248 | if result.status_code != 200: 249 | raise Exception(f"Unexpected response: " 250 | f"{result.status_code} {result.text}\n" 251 | f"Call was: {verb} {url}\n" 252 | f"Args: {kwargs}") 253 | data = result.json() 254 | if settings.DEBUG: 255 | from pprint import pprint 256 | pprint(data) 257 | return data 258 | 259 | def _request(self, verb, url, **kwargs): 260 | """ 261 | Utility for authenticated calls to Xero apis not yet supported by pyxero 262 | :param verb: 'get','post',... 263 | :param url: url to call 264 | :param kwargs: extra parameters to pass to requests 265 | :return: list of returned json dicts 266 | """ 267 | creds = self.client.accounts.credentials 268 | try: 269 | result = getattr( 270 | requests, verb.lower() 271 | )(url, auth=creds.oauth, 272 | headers={'User-Agent': creds.consumer_key}, 273 | **kwargs) 274 | return result 275 | except Exception as e: 276 | logger.exception(e) 277 | return None 278 | 279 | 280 | class XeroProjectsUser(models.Model): 281 | """ It turns out that the Projects API has different IDs...""" 282 | xerouser = models.ForeignKey(XeroUser, on_delete=CASCADE, 283 | related_name='prjuser', 284 | help_text="Regular Xero user ID") 285 | prj_user_id = models.UUIDField(help_text="Xero user ID in the Projects API") 286 | 287 | BASE_URI = "https://api.xero.com/projects.xro/2.0" 288 | 289 | def guess_projects_user_id(self): 290 | """ 291 | Xero provides no way to find user details from a oauth1.0 token, but 292 | if we have a prepopulated user we can make an educated guess. 293 | This is not foolproof, of course, which is why we don't automatically 294 | fill it up. Use at your own risk. 295 | 296 | :return: dict with user details that we *think* might be from the user 297 | who generated the token, or None if not found anything""" 298 | page = 1 299 | pagesize = 50 300 | end_page = 2 301 | email_lookup = self.xerouser.xero_email or self.xerouser.user.email 302 | if not email_lookup: 303 | raise Exception("You cannot guess a Projects user without an email " 304 | "set. Add a value to XeroUser.xero_email or " 305 | "User.email, and try again.") 306 | while page <= end_page: 307 | url = f'{self.BASE_URI}/projectsusers?page={page}&pagesize={pagesize}' 308 | result = self.xerouser._request_data('get', url) 309 | for user in result['items']: 310 | if user['email'] == email_lookup: 311 | return user['userId'] 312 | # not found? next page 313 | end_page = result['pageCount'] 314 | page += 1 315 | # still here ? Not found 316 | return None 317 | --------------------------------------------------------------------------------