Compare commits
No commits in common. "master" and "django17-deploy-step1" have entirely different histories.
master
...
django17-d
|
@ -1,18 +1,13 @@
|
|||
.*.sw*
|
||||
.#*
|
||||
*.log
|
||||
taiga/search
|
||||
settings/local.py
|
||||
settings/celery_local.py
|
||||
database.sqlite
|
||||
logs
|
||||
media
|
||||
static
|
||||
*.pyc
|
||||
*.mo
|
||||
.venv
|
||||
.coverage
|
||||
.cache
|
||||
.\#*
|
||||
.project
|
||||
.env
|
||||
|
|
34
.travis.yml
34
.travis.yml
|
@ -1,25 +1,25 @@
|
|||
language: python
|
||||
python:
|
||||
- "3.5"
|
||||
- "3.6"
|
||||
addons:
|
||||
postgresql: "9.4"
|
||||
- "3.3"
|
||||
services:
|
||||
- rabbitmq
|
||||
- postgresql
|
||||
cache:
|
||||
- apt
|
||||
- pip
|
||||
before_install:
|
||||
- sudo apt-get -qq update
|
||||
- sudo /etc/init.d/postgresql stop
|
||||
- sudo apt-get install -y postgresql-plpython-9.4
|
||||
- sudo /etc/init.d/postgresql start 9.4
|
||||
- rabbitmq # will start rabbitmq-server
|
||||
addons:
|
||||
postgresql: "9.3"
|
||||
before_script:
|
||||
- psql -c 'create database taiga;' -U postgres
|
||||
install:
|
||||
- travis_retry pip install pipenv
|
||||
- travis_retry pipenv sync --dev
|
||||
- sudo apt-get install postgresql-plpython-9.3
|
||||
- pip install -r requirements-devel.txt --use-mirrors
|
||||
script:
|
||||
- travis_retry pipenv run coverage run --source=taiga --omit='*tests*,*commands*,*migrations*,*admin*,*.jinja,*dashboard*,*settings*,*wsgi*,*questions*,*documents*' -m pytest -v --tb=native
|
||||
- coverage run --source=taiga --omit='*tests*,*commands*,*migrations*,*admin*,*.jinja,*dashboard*,*settings*,*wsgi*,*questions*,*documents*' -m py.test -v --tb=native
|
||||
notifications:
|
||||
email:
|
||||
recipients:
|
||||
- jespinog@gmail.com
|
||||
- andrei.antoukh@gmail.com
|
||||
- bameda@dbarragan.com
|
||||
- anler86@gmail.com
|
||||
on_success: change
|
||||
on_failure: change
|
||||
after_success:
|
||||
- coveralls
|
||||
|
|
|
@ -1,9 +0,0 @@
|
|||
[main]
|
||||
host = https://www.transifex.com
|
||||
lang_map = sr@latin:sr_Latn, zh_CN:zh_Hans, zh_TW:zh_Hant, fa_IR:fa
|
||||
|
||||
[taiga-back.taiga]
|
||||
file_filter = taiga/locale/<lang>/LC_MESSAGES/django.po
|
||||
source_file = taiga/locale/en/LC_MESSAGES/django.po
|
||||
source_lang = en
|
||||
type = PO
|
28
AUTHORS.rst
28
AUTHORS.rst
|
@ -1,38 +1,16 @@
|
|||
The PRIMARY AUTHORS are:
|
||||
|
||||
- Andrey Antukh <niwi@niwi.nz>
|
||||
- Andrey Antukh <niwi@niwi.be>
|
||||
- Jesus Espino Garcia <jespinog@gmail.com>
|
||||
- David Barragán Merino <dbarragan@dbarragan.com>
|
||||
- Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
- Xavi Julian <xavier.julian@kaleidos.net>
|
||||
- Anler Hernández <hello@anler.me>
|
||||
|
||||
Special thanks to Kaleidos Open Source S.L. for provice time for Taiga
|
||||
Special thanks to Kaleidos Open Source S.L. for provice time for taiga
|
||||
development.
|
||||
|
||||
And here is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS --
|
||||
people who have submitted patches, reported bugs, added translations, helped
|
||||
answer newbie questions, and generally made taiga that much better:
|
||||
|
||||
- Alejandro Gómez <alejandro.gomez@kaleidos.net>
|
||||
- Allister Antosik <me@allisterantosik.com>
|
||||
- Alonso Torres <alonso.torres@kaleidos.net>
|
||||
- Andrea Stagi <stagi.andrea@gmail.com>
|
||||
- Andrés Moya <andres.moya@kaleidos.net>
|
||||
- Andrey Alekseenko <al42and@gmail.com>
|
||||
- Brett Profitt <brett.profitt@gmail.com>
|
||||
- Bruno Clermont <bruno@robotinfra.com>
|
||||
- Chris Wilson <chris.wilson@aridhia.com>
|
||||
- David Burke <david@burkesoftware.com>
|
||||
- Everardo Medina <everblut@gmail.com>
|
||||
- Hector Colina <hcolina@gmail.com>
|
||||
- Joe Letts
|
||||
- Julien Palard
|
||||
- luyikei <luyikei.qmltu@gmail.com>
|
||||
- Michael Jurke <m.jurke@gmx.de>
|
||||
- Motius GmbH <mail@motius.de>
|
||||
- Riccardo Coccioli <riccardo.coccioli@immobiliare.it>
|
||||
- Ricky Posner <e@eposner.com>
|
||||
- Stefan Auditor <stefan.auditor@erdfisch.de>
|
||||
- Yamila Moreno <yamila.moreno@kaleidos.net>
|
||||
- Yaser Alraddadi <yaser@yr.sa>
|
||||
- ...
|
||||
|
|
510
CHANGELOG.md
510
CHANGELOG.md
|
@ -1,510 +0,0 @@
|
|||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 4.1.0 (2019-02-04)
|
||||
|
||||
### Misc
|
||||
|
||||
- Fix Close sprints
|
||||
|
||||
### Features:
|
||||
|
||||
- Negative filters
|
||||
- Activate the Ukrainian language
|
||||
|
||||
## 4.0.4 (2019-01-15)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fixes.
|
||||
|
||||
## 4.0.3 (2018-12-11)
|
||||
|
||||
### Misc
|
||||
|
||||
- Add extra requirements for oauthlib
|
||||
|
||||
## 4.0.2 (2018-12-04)
|
||||
|
||||
### Misc
|
||||
|
||||
- Update messages catalog.
|
||||
|
||||
## 4.0.1 (2018-11-28)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fix.
|
||||
|
||||
## 4.0.0 Larix cajanderi (2018-11-28)
|
||||
|
||||
### Features
|
||||
|
||||
- Custom home section (https://tree.taiga.io/project/taiga/issue/3059)
|
||||
- Custom fields (https://tree.taiga.io/project/taiga/issue/3725):
|
||||
- Dropdown
|
||||
- Checkbox
|
||||
- Number
|
||||
- Bulk move unfinished objects in sprint (https://tree.taiga.io/project/taiga/issue/5451)
|
||||
- Paginate history activity
|
||||
- Improve notifications area (https://tree.taiga.io/project/taiga/issue/2165 and
|
||||
https://tree.taiga.io/project/taiga/issue/3752)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor icon changes
|
||||
- Lots of small bugfixes
|
||||
|
||||
## 3.4.5 (2018-10-15)
|
||||
|
||||
### Features
|
||||
|
||||
- Prevent local Webhooks
|
||||
|
||||
## 3.4.4 (2018-09-19)
|
||||
|
||||
### Misc
|
||||
|
||||
- Small fixes
|
||||
|
||||
## 3.4.3 (2018-09-19)
|
||||
|
||||
### Misc
|
||||
|
||||
- Refactor attachment url's in timeline
|
||||
- Avoid receive feedkback in private projects from non-members
|
||||
- Allow delete reports uuid's
|
||||
- Small fixes
|
||||
|
||||
## 3.4.0 Pinus contorta (2018-08-13)
|
||||
|
||||
### Features
|
||||
|
||||
- Due dates configuration (https://tree.taiga.io/project/taiga/issue/3070):
|
||||
- Add due dates to admin attributes
|
||||
- Update project templates
|
||||
- Issues to Sprints (https://tree.taiga.io/project/taiga/issue/1181):
|
||||
- Add milestone filters
|
||||
|
||||
## 3.3.14 (2018-08-06)
|
||||
|
||||
### Misc
|
||||
|
||||
- Improve US reorder algorithm.
|
||||
- Drop python 3.4 and add python 3.6 to travis configuration.
|
||||
|
||||
## 3.3.13 (2018-07-05)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fixes.
|
||||
|
||||
## 3.3.11 (2018-06-27)
|
||||
|
||||
### Features
|
||||
|
||||
- Add assigned users kanban/taskboard filter.
|
||||
- Improve US reorder in kanban.
|
||||
- Upgrade psycopg2 library.
|
||||
|
||||
## 3.3.8 (2018-06-14)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fix.
|
||||
|
||||
## 3.3.7 (2018-05-31)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fix related with project import.
|
||||
|
||||
- Pin requirements to solve incompatible versions detected by pip 10.
|
||||
|
||||
## 3.3.4 (2018-05-24)
|
||||
|
||||
### Misc
|
||||
|
||||
- Add features to fulfill GDPR.
|
||||
|
||||
## 3.3.3 (2018-05-10)
|
||||
|
||||
### Misc
|
||||
|
||||
- Update locales.
|
||||
- Minor bug fixes.
|
||||
|
||||
## 3.3.1 (2018-04-30)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fixes.
|
||||
|
||||
## 3.3.1 (2018-04-30)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fixes.
|
||||
|
||||
## 3.3.0 Picea mariana (2018-04-26)
|
||||
|
||||
### Features
|
||||
|
||||
- Add "live notifications" to Taiga:
|
||||
- Migration for user configuration.
|
||||
- Add due date to US, tasks and issues (https://tree.taiga.io/project/taiga/issue/3070):
|
||||
- Add to csv export.
|
||||
- Add to projects import/export.
|
||||
- Add to webhooks.
|
||||
- Add to django admin.
|
||||
- Add multiple assignement only in US (https://tree.taiga.io/project/taiga/issue/1961):
|
||||
- The `assigned_to` field is still active.
|
||||
- Add to csv export.
|
||||
- Add to projects import/export.
|
||||
- Add to webhooks.
|
||||
- Add to django admin.
|
||||
- Delete cards in Kanban and sprint Taskboard (https://tree.taiga.io/project/taiga/issue/2683).
|
||||
|
||||
## 3.2.3 (2018-04-04)
|
||||
|
||||
### Misc
|
||||
|
||||
- Fix milestone burndown graph with empty US.
|
||||
- Upgrade markdown library to solve bug.
|
||||
- Update locales.
|
||||
|
||||
## 3.2.2 (2018-03-15)
|
||||
|
||||
### Misc
|
||||
|
||||
- Minor bug fixes.
|
||||
|
||||
|
||||
## 3.2.0 Betula nana (2018-03-07)
|
||||
|
||||
### Features
|
||||
- Add role filtering in US.
|
||||
|
||||
|
||||
## 3.1.3 (2018-02-28)
|
||||
|
||||
### Features
|
||||
- Increase token entropy.
|
||||
- Squash field changes on notification emails
|
||||
- Minor bug fixes.
|
||||
|
||||
|
||||
## 3.1.0 Perovskia Atriplicifolia (2017-03-10)
|
||||
|
||||
### Features
|
||||
- Contact with the project: if the projects have this module enabled Taiga users can contact them.
|
||||
- Ability to create rich text custom fields in Epics, User Stories, Tasks and Isues.
|
||||
- Full text search now use simple as tokenizer so search with non-english text are allowed.
|
||||
- Duplicate project: allows creating a new project based on the structure of another (status, tags, colors, default values...)
|
||||
- Add thumbnails and preview for PSD files.
|
||||
- Add thumbnails and preview for SVG files (Cario lib is needed).
|
||||
- i18n:
|
||||
- Add japanese (ja) translation.
|
||||
- Add korean (ko) translation.
|
||||
- Add chinese simplified (zh-Hans) translation.
|
||||
- Third party services project importers:
|
||||
- Trello
|
||||
- Jira 7
|
||||
- Github
|
||||
- Asana
|
||||
|
||||
### Misc
|
||||
- API:
|
||||
- Memberships API endpoints now allows using usernames and emails instead of using only emails.
|
||||
- Contacts API allow full text search (by the username, full name or email).
|
||||
- Filter milestones, user stories and tasks by estimated_start and estimated_finish dates.
|
||||
- Add project_extra_info to epics, tasks, milestones, issues and wiki pages endpoints.
|
||||
- Gogs integration: Adding new Gogs signature method.
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 3.0.0 Stellaria Borealis (2016-10-02)
|
||||
|
||||
### Features
|
||||
- Add Epics.
|
||||
- Include created, modified and finished dates for tasks in CSV reports.
|
||||
- Add gravatar url to Users API endpoint.
|
||||
- ProjectTemplates now are sorted by the attribute 'order'.
|
||||
- Create enpty wiki pages (if not exist) when a new link is created.
|
||||
- Diff messages in history entries now show only the relevant changes (with some context).
|
||||
- User stories and tasks listing API call support extra params to include more data (tasks and attachemnts and attachments, respectively)
|
||||
- Comments:
|
||||
- Now comment owners and project admins can edit existing comments with the history Entry endpoint.
|
||||
- Add a new permissions to allow add comments instead of use the existent modify permission for this purpose.
|
||||
- Tags:
|
||||
- New API endpoints over projects to create, rename, edit, delete and mix tags.
|
||||
- Tag color assignation is not automatic.
|
||||
- Select a color (or not) to a tag when add it to stories, issues and tasks.
|
||||
- Improve search system over stories, tasks and issues:
|
||||
- Search into tags too. (thanks to [Riccardo Cocciol](https://github.com/volans-))
|
||||
- Weights are applied: (subject = ref > tags > description).
|
||||
- Import/Export:
|
||||
- Gzip export/import support.
|
||||
- Export performance improvements.
|
||||
- Add filter by email domain registration and invitation by setting.
|
||||
- Third party integrations:
|
||||
- Included gogs as builtin integration.
|
||||
- Improve messages generated on webhooks input.
|
||||
- Add mentions support in commit messages.
|
||||
- Cleanup hooks code.
|
||||
- Rework webhook signature header to align with larger implementations and defined [standards](https://superfeedr-misc.s3.amazonaws.com/pubsubhubbub-core-0.4.html\#authednotify). (thanks to [Stefan Auditor](https://github.com/sanduhrs))
|
||||
- Add created-, modified-, finished- and finish_date queryset filters
|
||||
- Support exact match, gt, gte, lt, lte
|
||||
- added issues, tasks and userstories accordingly
|
||||
- i18n:
|
||||
- Add norwegian Bokmal (nb) translation.
|
||||
|
||||
### Misc
|
||||
- [API] Improve performance of some calls over list.
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 2.1.0 Ursus Americanus (2016-05-03)
|
||||
|
||||
### Features
|
||||
- Add sprint name and slug on search results for user stories (thanks to [@everblut](https://github.com/everblut))
|
||||
- [API] projects resource: Random order if `discover_mode=true` and `is_featured=true`.
|
||||
- Webhooks: Improve webhook data:
|
||||
- add permalinks
|
||||
- owner, assigned_to, status, type, priority, severity, user_story, milestone, project are objects
|
||||
- add role to 'points' object
|
||||
- add the owner to every notification ('by' field)
|
||||
- add the date of the notification ('date' field)
|
||||
- show human diffs in 'changes'
|
||||
- remove unnecessary data
|
||||
- CSV Reports:
|
||||
- Change field name: 'milestone' to 'sprint'
|
||||
- Add new fields: 'sprint_estimated_start' and 'sprint_estimated_end'
|
||||
- Importer:
|
||||
- Remove project after load a dump file fails
|
||||
- Add more info the the logger if load a dump file fails
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 2.0.0 Pulsatilla Patens (2016-04-04)
|
||||
|
||||
### Features
|
||||
- Ability to create url custom fields. (thanks to [@astagi](https://github.com/astagi)).
|
||||
- Blocked projects support
|
||||
- Transfer projects ownership support
|
||||
- Customizable max private and public projects per user
|
||||
- Customizable max of memberships per owned private and public projects
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.10.0 Dryas Octopetala (2016-01-30)
|
||||
|
||||
### Features
|
||||
- Add logo field to project model
|
||||
- Add is_featured field to project model
|
||||
- Add is_looking_for_people and looking_for_people_note fields to project model
|
||||
- Filter projects list by
|
||||
- is_looking_for_people
|
||||
- is_featured
|
||||
- is_backlog_activated
|
||||
- is_kanban_activated
|
||||
- Search projects by text query (order by ranking name > tags > description)
|
||||
- Order projects list:
|
||||
- alphabetically by default
|
||||
- by fans (last week/moth/year/all time)
|
||||
- by activity (last week/moth/year/all time)
|
||||
- Show stats for discover secction
|
||||
- i18n.
|
||||
- Add swedish (sv) translation.
|
||||
- Add turkish (tr) translation.
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.9.1 Taiga Tribe (2016-01-05)
|
||||
|
||||
### Features
|
||||
- [CSV Reports] Add fields "created_date", "modified_date", "finished_date" to issues CSV report.
|
||||
- [Attachment] Generate 'card-image' size (300x200) thumbnails for attached image files.
|
||||
|
||||
### Misc
|
||||
- Improve login and forgot password: allow username or email case-insensitive if the query only
|
||||
match with one user.
|
||||
- Improve the django admin panel, now it is more usable and all the selector fields works properly.
|
||||
- [API] Add tribe_gig field to user stories (improve integration between Taiga and Taiga Tribe).
|
||||
- [API] Performance improvements for project stats.
|
||||
- [Events] Add command to send an instant notifications to all the currently online users.
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.9.0 Abies Siberica (2015-11-02)
|
||||
|
||||
### Features
|
||||
- Project can be starred or unstarred and the fans list can be obtained.
|
||||
- US, tasks and Issues can be upvoted or downvoted and the voters list can be obtained.
|
||||
- Now users can watch public issues, tasks and user stories.
|
||||
- Add endpoints to show the watchers list for issues, tasks and user stories.
|
||||
- Add a "field type" property for custom fields: 'text', 'multiline text' and 'date' right nowi
|
||||
(thanks to [@artlepool](https://github.com/artlepool)).
|
||||
- Allow multiple actions in the commit messages.
|
||||
- Now every user that coments USs, Issues or Tasks will be involved in it (add author to the watchers list).
|
||||
- Now profile timelines only show content about the objects (US/Tasks/Issues/Wiki pages) you are involved.
|
||||
- Add custom videoconference system.
|
||||
- Fix the compatibility with BitBucket webhooks and add issues and issues comments integration.
|
||||
- Add support for comments in the Gitlab webhooks integration.
|
||||
- Add externall apps: now Taiga can integrate with hundreds of applications and service.
|
||||
- Improve searching system, now full text searchs are supported
|
||||
- Add sha1 hash to attachments to verify the integrity of files (thanks to [@astagi](https://github.com/astagi)).
|
||||
- i18n.
|
||||
- Add italian (it) translation.
|
||||
- Add polish (pl) translation.
|
||||
- Add portuguese (Brazil) (pt_BR) translation.
|
||||
- Add russian (ru) translation.
|
||||
|
||||
### Misc
|
||||
- Made compatible with python 3.5.
|
||||
- Migrated to django 1.8.
|
||||
- Update the rest of requirements to the last version.
|
||||
- Improve export system, now is more efficient and prevents possible crashes with heavy projects.
|
||||
- API: Mixin fields 'users', 'members' and 'memberships' in ProjectDetailSerializer.
|
||||
- API: Add stats/system resource with global server stats (total project, total users....)
|
||||
- API: Improve and fix some errors in issues/filters_data and userstories/filters_data.
|
||||
- API: resolver suport ref GET param and return a story, task or issue.
|
||||
- Webhooks: Add deleted datetime to webhooks responses when isues, tasks or USs are deleted.
|
||||
- Add headers to allow threading for notification emails about changes to issues, tasks, user stories,
|
||||
and wiki pages. (thanks to [@brett](https://github.com/brettp)).
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.8.0 Saracenia Purpurea (2015-06-18)
|
||||
|
||||
### Features
|
||||
- Improve timeline resource.
|
||||
- Add sitemap of taiga-front (the web client).
|
||||
- Search by reference (thanks to [@artlepool](https://github.com/artlepool))
|
||||
- Add call 'by_username' to the API resource User
|
||||
- i18n.
|
||||
- Add deutsch (de) translation.
|
||||
- Add nederlands (nl) translation.
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.7.0 Empetrum Nigrum (2015-05-21)
|
||||
|
||||
### Features
|
||||
- Make Taiga translatable (i18n support).
|
||||
- i18n.
|
||||
- Add spanish (es) translation.
|
||||
- Add french (fr) translation.
|
||||
- Add finish (fi) translation.
|
||||
- Add catalan (ca) translation.
|
||||
- Add traditional chinese (zh-Hant) translation.
|
||||
- Add Jitsi to our supported videoconference apps list
|
||||
- Add tags field to CSV reports.
|
||||
- Improve history (and email) comments created by all the GitHub actions
|
||||
|
||||
### Misc
|
||||
- New contrib plugin for letschat (by Δndrea Stagi)
|
||||
- Remove djangorestframework from requirements. Move useful code to core.
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.6.0 Abies Bifolia (2015-03-17)
|
||||
|
||||
### Features
|
||||
- Added custom fields per project for user stories, tasks and issues.
|
||||
- Support of export to CSV user stories, tasks and issues.
|
||||
- Allow public projects.
|
||||
|
||||
### Misc
|
||||
- New contrib plugin for HipChat (by Δndrea Stagi).
|
||||
- Lots of small and not so small bugfixes.
|
||||
- Updated some requirements.
|
||||
|
||||
|
||||
## 1.5.0 Betula Pendula - FOSDEM 2015 (2015-01-29)
|
||||
|
||||
### Features
|
||||
- Improving SQL queries and performance.
|
||||
- Now you can export and import projects between Taiga instances.
|
||||
- Email redesign.
|
||||
- Support for archived status (not shown by default in Kanban).
|
||||
- Removing files from filesystem when deleting attachments.
|
||||
- Support for contrib plugins (existing yet: slack, hall and gogs).
|
||||
- Webhooks added (crazy integrations are welcome).
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.4.0 Abies veitchii (2014-12-10)
|
||||
|
||||
### Features
|
||||
- Bitbucket integration:
|
||||
+ Change status of user stories, tasks and issues with the commit messages.
|
||||
- Gitlab integration:
|
||||
+ Change status of user stories, tasks and issues with the commit messages.
|
||||
+ Sync issues creation in Taiga from Gitlab.
|
||||
- Support throttling.
|
||||
+ for anonymous users
|
||||
+ for authenticated users
|
||||
+ in import mode
|
||||
- Add project members stats endpoint.
|
||||
- Support of leave project.
|
||||
- Control of leave a project without admin user.
|
||||
- Improving OCC (Optimistic concurrency control)
|
||||
- Improving some SQL queries using djrom directly
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.3.0 Dryas hookeriana (2014-11-18)
|
||||
|
||||
### Features
|
||||
- GitHub integration (Phase I):
|
||||
+ Login/singin connector.
|
||||
+ Change status of user stories, tasks and issues with the commit messages.
|
||||
+ Sync issues creation in Taiga from GitHub.
|
||||
+ Sync comments in Taiga from GitHub issues.
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.2.0 Picea obovata (2014-11-04)
|
||||
|
||||
### Features
|
||||
- Send an email to the user on signup.
|
||||
- Emit django signal on user signout.
|
||||
- Support for custom text when inviting users.
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes.
|
||||
|
||||
|
||||
## 1.1.0 Alnus maximowiczii (2014-10-13)
|
||||
|
||||
### Misc
|
||||
- Fix bugs related to unicode chars on attachments.
|
||||
- Fix wrong static url resolve usage on emails.
|
||||
- Fix some bugs on import/export api related with attachments.
|
||||
|
||||
|
||||
## 1.0.0 (2014-10-07)
|
||||
|
||||
### Misc
|
||||
- Lots of small and not so small bugfixes
|
||||
|
||||
### Features
|
||||
- New data exposed in the API for taskboard and backlog summaries
|
||||
- Allow feedback for users from the platform
|
||||
- Real time changes for backlog, taskboard, kanban and issues
|
|
@ -1,51 +0,0 @@
|
|||
# Taiga.io Community CoC (Code of Conduct)
|
||||
### Version 0.1
|
||||
|
||||
As contributors and maintainers of any Taiga.io project, and in the interest of
|
||||
fostering an open and welcoming community, we pledge to respect all people who
|
||||
contribute through reporting issues, posting feature requests, updating
|
||||
documentation, submitting pull requests or patches, and other activities.
|
||||
|
||||
We are committed to making participation in this projects a harassment-free
|
||||
experience for everyone, regardless of level of experience, gender, gender
|
||||
identity and expression, sexual orientation, disability, personal appearance,
|
||||
body size, race, ethnicity, age, religion, or nationality.
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery
|
||||
* Personal attacks
|
||||
* Trolling or insulting/derogatory comments
|
||||
* Public or private harassment
|
||||
* Publishing other's private information, such as physical or electronic
|
||||
addresses, without explicit permission
|
||||
* Other unethical or unprofessional conduct
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
By adopting this Code of Conduct, project maintainers commit themselves to
|
||||
fairly and consistently applying these principles to every aspect of managing
|
||||
this project. Project maintainers who do not follow or enforce the Code of
|
||||
Conduct may be permanently removed from the project team.
|
||||
|
||||
This code of conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community (like our
|
||||
mailing list, Google Groups, in Twitter, Facebook, etc.).
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting a project maintainer at
|
||||
[conduct@taiga.io](mailto:coc@taiga.io). All complaints will be reviewed
|
||||
and investigated and will result in a response that is deemed necessary and
|
||||
appropriate to the circumstances. Maintainers are obligated to maintain
|
||||
confidentiality with regard to the reporter of an incident.
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 1.3.0, available at
|
||||
[http://contributor-covenant.org/version/1/3/0/][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/3/0/
|
122
CONTRIBUTING.md
122
CONTRIBUTING.md
|
@ -1,122 +0,0 @@
|
|||
# How can I contribute to Taiga?
|
||||
|
||||
---
|
||||
|
||||
## Developer Certificate of Origin + License
|
||||
|
||||
By contributing to Taiga Agile LLC., You accept and agree to the following terms and conditions for Your present and future Contributions submitted to Taiga Agile LLC. Except for the license granted herein to Taiga Agile LLC. and recipients of software distributed by Taiga Agile LLC., You reserve all right, title, and interest in and to Your Contributions.
|
||||
|
||||
All Contributions are subject to the following DCO + License terms.
|
||||
|
||||
[DCO + License](https://github.com/taiga/taiga-back/blob/master/DCOLICENSE)
|
||||
|
||||
_This notice should stay as the first item in the CONTRIBUTING.md file._
|
||||
|
||||
---
|
||||
|
||||
We will be very happy to help us to improve Taiga, there are many different ways to contribute to Taiga's development, just find the one that best fits with your skills. Here are the guidelines we'd like you to follow.
|
||||
|
||||
## Our Code of Conduct
|
||||
|
||||
Help us keep the Taiga Community open and inclusive. Please read and follow our [Code of Conduct][CoC].
|
||||
|
||||
## Our License
|
||||
|
||||
Every code patch accepted in Taiga codebase is licensed under [AGPL v3.0][AGPL v3.0]. You must be careful to not include any code that can not be licensed under this license.
|
||||
|
||||
Please read carefully [our license][Taiga license] and ask us if you have any questions.
|
||||
|
||||
## Setup problems
|
||||
|
||||
If you follow our [setup guide][taiga Dev/Setup documentation] and you have some problem, please tell with us in our [mailing list][Taiga Mailing List].
|
||||
|
||||
## Sent us your feedback or questions
|
||||
|
||||
If you want to send us your feedback or have some questions about how to use Taiga, please direct these to our [mailing list][Taiga Mailing List]. If it's related to our SaaS https://taiga.io please write us to our support email [support@taiga.io][Support email].
|
||||
|
||||
Remember that you can find some help in our [support pages][Taiga User documentation].
|
||||
|
||||
## Did you find an issue or bug?
|
||||
|
||||
If you find an issue using the app (UX or UI bug) or reading our source code and it's not on our [Bug list][Taiga Bug list] at Taiga.io, please report it:
|
||||
|
||||
- in our [mailing list][Taiga Mailing List]
|
||||
- in the issue section of the appropriate repository at [GitHub][Taiga in GitHub].
|
||||
- send us a mail to [support@taiga.io][Support email] if is a bug related to [tree.taiga.io][Taiga.io].
|
||||
- send a mail to [security@taiga.io][Security email] if is a **security bug**.
|
||||
|
||||
Even better: you can submit a Pull Request with a fix.
|
||||
|
||||
Please, before reporting a bug write down
|
||||
|
||||
- explain why this is a bug for you
|
||||
- how can we reproduce it
|
||||
- your operating System
|
||||
- your browser and version
|
||||
- if it's possible, a screenshot
|
||||
|
||||
Sometimes it takes less time to fix a bug if the developer knows how to find it and we will solve your problem as fast as possible.
|
||||
|
||||
**Localization Issue:** Taiga use Transifex to manage the i18n files so don't submit a pull request to those files (except `-en.json`), to fix it just access our team of translators, set up an account in the [Taiga Transifex project][Taiga in Transifex] and start contributing.
|
||||
|
||||
## Propose some feature or enhancement
|
||||
|
||||
You can propose a new enhancement to our [mailing list][Taiga Mailing List] or review and upvote in the existing [list of enhancements][Taiga Enhancement list] in Taiga.io.
|
||||
|
||||
If you would like to implement it by yourself consider what kind of change it is:
|
||||
|
||||
### Small Changes
|
||||
|
||||
It can be crafted and submitted to the [GitHub Repositories][Taiga in GitHub] as a Pull Request.
|
||||
|
||||
### Major Changes
|
||||
|
||||
Before contributing with a major change to Taiga it should be discussed first with the Taiga Team so that we can better coordinate our efforts, prevent duplication of work, and help you to craft the change so that it is successfully accepted into the project. Please, contact us in the [mailing list][Taiga mailing list] or via [support@taiga.io][Support email].
|
||||
|
||||
We have defined a concrete workflow for this changes:
|
||||
|
||||
1. **User Story**: Send us a complete description of the functionality you'd like to develop, how it should work, for which profiles, as if you were writing a User Story. Please include some ideas of what would be a definition of Done of the User Story. The team will review it, decide whether or not it could make it into Taiga Core. If not, you can always write a plugin.
|
||||
2. **Mentorship**: If accepted, Taiga team will help you, and a person from the team will be your contact in the development process. The Story will be visible in the [Taiga Kanban][Taiga Kanban]
|
||||
3. **User Experience**: The functionality will require some wireframes or ideas to be developed correctly. A good UX its an essential part of Taiga success. You should create a user experience proposal and the Taiga UX team will help you.
|
||||
4. **Design**: The design should respect the Taiga style. Try to reproduce other areas of the site. The taiga design team will review this proposal as well.
|
||||
5. **Development**: The last step is the development. Remember to add unit and integration test in `taiga-back` code and unit and e2e test for `taiga-back` part. We have the API well documented too in [taiga-doc][Taiga Dev/Setup documentation].
|
||||
6. **Pull request**: Remember to add a good description and screenshots are welcome too. Once the pull request is done, someone else from the team will review the code to ensure that it fits with the good practices and styles. If it does, the PR will be merged and will be on the next Taiga release.
|
||||
|
||||
If you think you are not able to do one or more of the parts of the process, your contribution is still welcome, but we cannot ensure that it will make it soon into the Taiga core anytime soon. It will depend on our priority backlog.
|
||||
|
||||
Thanks a lot! It is really great that we could make Taiga better with the help of the community.
|
||||
|
||||
### Contrib plugins
|
||||
|
||||
Taiga support contrib plugins to add or overwrite some functionalities. You can find some example in [our organization at GitHub][Taiga in GitHub].
|
||||
|
||||
## Improve the documentation
|
||||
|
||||
We are gathering lots of information from our users to build and enhance our documentation. If you use the documentation to install or develop with Taiga and find any mistakes, omissions or confused sequences, it is enormously helpful to report it. Or better still, if you believe you can author additions, please make a pull-request to taiga project.
|
||||
|
||||
Currently, we have authored three main documentation hubs:
|
||||
|
||||
- [Taiga Setup/Dev documentation][Taiga Dev/Setup documentation repo]: If you need to install Taiga on your own server, this is the place to find some guides or our API documentation and reference for developing from Taiga API.
|
||||
- [Taiga User documentation][Taiga User documentation repo]: This page is intended to be the support reference page for the users. If you find any mistake, please report or fix it.
|
||||
|
||||
[Taiga.io]: https://taiga.io
|
||||
|
||||
[CoC]: https://github.com/taigaio/code-of-conduct/blob/master/CODE_OF_CONDUCT.md
|
||||
[AGPL v3.0]: http://www.gnu.org/licenses/agpl-3.0.html
|
||||
[Taiga license]: https://github.com/taigaio/taiga-back/blob/master/LICENSE
|
||||
|
||||
[Taiga Mailing List]: http://groups.google.co.uk/d/forum/taigaio
|
||||
[Support email]: mailto:support@taiga.io
|
||||
[Security email]: mailto:security@taiga.io
|
||||
|
||||
[Taiga in Transifex]: https://www.transifex.com/organization/taiga-agile-llc/
|
||||
[Taiga in GitHub]: https://github.com/taigaio
|
||||
|
||||
[Taiga kanban]: https://tree.taiga.io/project/taiga/kanban
|
||||
[Taiga Bug list]: https://tree.taiga.io/project/taiga/issues?statuses=1,2&orderBy=-created_date&page=1&types=1
|
||||
[Taiga Enhancement list]: https://tree.taiga.io/project/taiga/issues?statuses=1,2&orderBy=-total_voters&page=1&status=1,2&types=6
|
||||
|
||||
[Taiga Dev/Setup documentation]: http://taigaio.github.io/taiga-doc/dist/
|
||||
[Taiga Dev/Setup documentation repo]: https://github.com/taigaio/taiga-doc
|
||||
[Taiga User documentation]: https://tree.taiga.io/support/
|
||||
[Taiga User documentation repo]: https://github.com/taigaio/taiga-support
|
705
DCOLICENSE
705
DCOLICENSE
|
@ -1,705 +0,0 @@
|
|||
Developer Certificate of Origin + License
|
||||
|
||||
By contributing to Taiga Agile LLC., You accept and agree to the following
|
||||
terms and conditions for Your present and future Contributions submitted to
|
||||
Taiga Agile LLC. Except for the license granted herein to Taiga Agile LLC. and
|
||||
recipients of software distributed by Taiga Agile LLC., You reserve all right,
|
||||
title, and interest in and to Your Contributions.
|
||||
|
||||
Developer Certificate of Origin
|
||||
Version 1.1
|
||||
|
||||
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
|
||||
1 Letterman Drive
|
||||
Suite D4700
|
||||
San Francisco, CA, 94129
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license
|
||||
document, but changing it is not allowed.
|
||||
|
||||
Developer's Certificate of Origin 1.1
|
||||
|
||||
By making a contribution to this project, I certify that:
|
||||
|
||||
(a) The contribution was created in whole or in part by me and I have the right
|
||||
to submit it under the open source license indicated in the file; or
|
||||
|
||||
(b) The contribution is based upon previous work that, to the best of my
|
||||
knowledge, is covered under an appropriate open source license and I have the
|
||||
right under that license to submit that work with modifications, whether
|
||||
created in whole or in part by me, under the same open source license
|
||||
(unless I am permitted to submit under a different license), as indicated
|
||||
in the file; or
|
||||
|
||||
(c) The contribution was provided directly to me by some other person who
|
||||
certified (a), (b) or (c) and I have not modified it.
|
||||
|
||||
(d) I understand and agree that this project and the contribution are public
|
||||
and that a record of the contribution (including all personal information I
|
||||
submit with it, including my sign-off) is maintained indefinitely and may be
|
||||
redistributed consistent with this project or the open source license(s)
|
||||
involved.
|
||||
|
||||
All Contributions to this project are licensed under the following license:
|
||||
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
|
@ -1,19 +0,0 @@
|
|||
**Before adding an issue**
|
||||
Please ensure that your issue is not already reported in our [issues list](https://tree.taiga.io/project/taiga/issues?order_by=-created_date).
|
||||
If this issue was already reported, remember that you can upvote it to raise its importance.
|
||||
|
||||
**Do you want to request a *feature* or report a *bug*?**
|
||||
|
||||
**What is the current behavior?**
|
||||
|
||||
**If the current behavior is a bug, please provide the steps to reproduce.**
|
||||
|
||||
**What is the expected behavior?**
|
||||
|
||||
**Is it happening in taiga.io or in your own instance?**
|
||||
|
||||
**What browser/version are you using?**
|
||||
|
||||
**Are there any console errors *(Ctrl + F12)* in red?**
|
||||
|
||||
Thanks for reporting!
|
53
Pipfile
53
Pipfile
|
@ -1,53 +0,0 @@
|
|||
[[source]]
|
||||
url = "https://pypi.org/simple"
|
||||
verify_ssl = true
|
||||
name = "pypi"
|
||||
|
||||
[packages]
|
||||
asana = "==0.6.7"
|
||||
bleach = "==2.1.4"
|
||||
celery = "==4.0.2"
|
||||
cryptography = "==2.3.1"
|
||||
diff-match-patch = "==20121119"
|
||||
django-ipware = "==1.1.6"
|
||||
django-jinja = "==2.3.1"
|
||||
django-picklefield = "==0.3.2"
|
||||
django-pglocks = "==1.0.2"
|
||||
django-sampledatahelper = "==0.4.1"
|
||||
django-sites = "==0.9"
|
||||
django-sr = "==0.0.4"
|
||||
djmail = "==1.0.1"
|
||||
easy-thumbnails = "==2.4.1"
|
||||
fn = "==0.4.3"
|
||||
gunicorn = "==19.7.1"
|
||||
kombu = "==4.0.2" # The same as celery
|
||||
netaddr = "==0.7.19"
|
||||
premailer = "==3.0.1"
|
||||
psd-tools = "==1.4"
|
||||
"psycopg2-binary" = "==2.7.5"
|
||||
python-dateutil = "==2.7.5"
|
||||
python-magic = "==0.4.13"
|
||||
pytz = "*"
|
||||
raven = "==6.1.0"
|
||||
redis = "==2.10.5"
|
||||
requests = "==2.20.0"
|
||||
requests_oauthlib = "*"
|
||||
serpy = "==0.1.1"
|
||||
webcolors = "==1.7"
|
||||
CairoSVG = "==2.0.3"
|
||||
Django = "~=1.11.15"
|
||||
Markdown = "==3.0.1"
|
||||
Pillow = "==4.1.1"
|
||||
Unidecode = "==0.4.20"
|
||||
Pygments = "==2.2.0"
|
||||
oauthlib = {extras = ["signedtoken"],version = "*"}
|
||||
|
||||
[dev-packages]
|
||||
coverage = "*"
|
||||
coveralls = "*"
|
||||
pytest = "*"
|
||||
pytest-django = "*"
|
||||
factory-boy = "*"
|
||||
|
||||
[requires]
|
||||
python_version = "3.6"
|
|
@ -1,805 +0,0 @@
|
|||
{
|
||||
"_meta": {
|
||||
"hash": {
|
||||
"sha256": "2505838cdc4b5390130990ae63647a4447c5f146ab37ca8bf29f627091112cf7"
|
||||
},
|
||||
"pipfile-spec": 6,
|
||||
"requires": {
|
||||
"python_version": "3.6"
|
||||
},
|
||||
"sources": [
|
||||
{
|
||||
"name": "pypi",
|
||||
"url": "https://pypi.org/simple",
|
||||
"verify_ssl": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"default": {
|
||||
"amqp": {
|
||||
"hashes": [
|
||||
"sha256:073dd02fdd73041bffc913b767866015147b61f2a9bc104daef172fc1a0066eb",
|
||||
"sha256:eed41946890cd43e8dee44a316b85cf6fee5a1a34bb4a562b660a358eb529e1b"
|
||||
],
|
||||
"version": "==2.3.2"
|
||||
},
|
||||
"asana": {
|
||||
"hashes": [
|
||||
"sha256:412398ff0f72104f5fb602653b994cdd36de89aedff2d37229b237f300f5f01b",
|
||||
"sha256:d576601116764050c4cf63b417f1c24700b76cf6686f0e51e6b0b77d450e7973"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.6.7"
|
||||
},
|
||||
"asn1crypto": {
|
||||
"hashes": [
|
||||
"sha256:2f1adbb7546ed199e3c90ef23ec95c5cf3585bac7d11fb7eb562a3fe89c64e87",
|
||||
"sha256:9d5c20441baf0cb60a4ac34cc447c6c189024b6b4c6cd7877034f4965c464e49"
|
||||
],
|
||||
"version": "==0.24.0"
|
||||
},
|
||||
"billiard": {
|
||||
"hashes": [
|
||||
"sha256:42d9a227401ac4fba892918bba0a0c409def5435c4b483267ebfe821afaaba0e"
|
||||
],
|
||||
"version": "==3.5.0.5"
|
||||
},
|
||||
"bleach": {
|
||||
"hashes": [
|
||||
"sha256:0ee95f6167129859c5dce9b1ca291ebdb5d8cd7e382ca0e237dfd0dad63f63d8",
|
||||
"sha256:24754b9a7d530bf30ce7cbc805bc6cce785660b4a10ff3a43633728438c105ab"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.1.4"
|
||||
},
|
||||
"cairocffi": {
|
||||
"hashes": [
|
||||
"sha256:15386c3a9e08823d6826c4491eaccc7b7254b1dc587a3b9ce60c350c3f990337"
|
||||
],
|
||||
"version": "==0.9.0"
|
||||
},
|
||||
"cairosvg": {
|
||||
"hashes": [
|
||||
"sha256:d2da5aaa31ded26affd5cdffc371ec4cc48800bc2d822a9c28504360482418a1"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.0.3"
|
||||
},
|
||||
"celery": {
|
||||
"hashes": [
|
||||
"sha256:0e5b7e0d7f03aa02061abfd27aa9da05b6740281ca1f5228a54fbf7fe74d8afa",
|
||||
"sha256:e3d5a6c56a73ff8f2ddd4d06dc37f4c2afe4bb4da7928b884d0725ea865ef54d"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==4.0.2"
|
||||
},
|
||||
"certifi": {
|
||||
"hashes": [
|
||||
"sha256:47f9c83ef4c0c621eaef743f133f09fa8a74a9b75f037e8624f83bd1b6626cb7",
|
||||
"sha256:993f830721089fef441cdfeb4b2c8c9df86f0c63239f06bd025a76a7daddb033"
|
||||
],
|
||||
"version": "==2018.11.29"
|
||||
},
|
||||
"cffi": {
|
||||
"hashes": [
|
||||
"sha256:151b7eefd035c56b2b2e1eb9963c90c6302dc15fbd8c1c0a83a163ff2c7d7743",
|
||||
"sha256:1553d1e99f035ace1c0544050622b7bc963374a00c467edafac50ad7bd276aef",
|
||||
"sha256:1b0493c091a1898f1136e3f4f991a784437fac3673780ff9de3bcf46c80b6b50",
|
||||
"sha256:2ba8a45822b7aee805ab49abfe7eec16b90587f7f26df20c71dd89e45a97076f",
|
||||
"sha256:3bb6bd7266598f318063e584378b8e27c67de998a43362e8fce664c54ee52d30",
|
||||
"sha256:3c85641778460581c42924384f5e68076d724ceac0f267d66c757f7535069c93",
|
||||
"sha256:3eb6434197633b7748cea30bf0ba9f66727cdce45117a712b29a443943733257",
|
||||
"sha256:495c5c2d43bf6cebe0178eb3e88f9c4aa48d8934aa6e3cddb865c058da76756b",
|
||||
"sha256:4c91af6e967c2015729d3e69c2e51d92f9898c330d6a851bf8f121236f3defd3",
|
||||
"sha256:57b2533356cb2d8fac1555815929f7f5f14d68ac77b085d2326b571310f34f6e",
|
||||
"sha256:770f3782b31f50b68627e22f91cb182c48c47c02eb405fd689472aa7b7aa16dc",
|
||||
"sha256:79f9b6f7c46ae1f8ded75f68cf8ad50e5729ed4d590c74840471fc2823457d04",
|
||||
"sha256:7a33145e04d44ce95bcd71e522b478d282ad0eafaf34fe1ec5bbd73e662f22b6",
|
||||
"sha256:857959354ae3a6fa3da6651b966d13b0a8bed6bbc87a0de7b38a549db1d2a359",
|
||||
"sha256:87f37fe5130574ff76c17cab61e7d2538a16f843bb7bca8ebbc4b12de3078596",
|
||||
"sha256:95d5251e4b5ca00061f9d9f3d6fe537247e145a8524ae9fd30a2f8fbce993b5b",
|
||||
"sha256:9d1d3e63a4afdc29bd76ce6aa9d58c771cd1599fbba8cf5057e7860b203710dd",
|
||||
"sha256:a36c5c154f9d42ec176e6e620cb0dd275744aa1d804786a71ac37dc3661a5e95",
|
||||
"sha256:a6a5cb8809091ec9ac03edde9304b3ad82ad4466333432b16d78ef40e0cce0d5",
|
||||
"sha256:ae5e35a2c189d397b91034642cb0eab0e346f776ec2eb44a49a459e6615d6e2e",
|
||||
"sha256:b0f7d4a3df8f06cf49f9f121bead236e328074de6449866515cea4907bbc63d6",
|
||||
"sha256:b75110fb114fa366b29a027d0c9be3709579602ae111ff61674d28c93606acca",
|
||||
"sha256:ba5e697569f84b13640c9e193170e89c13c6244c24400fc57e88724ef610cd31",
|
||||
"sha256:be2a9b390f77fd7676d80bc3cdc4f8edb940d8c198ed2d8c0be1319018c778e1",
|
||||
"sha256:ca1bd81f40adc59011f58159e4aa6445fc585a32bb8ac9badf7a2c1aa23822f2",
|
||||
"sha256:d5d8555d9bfc3f02385c1c37e9f998e2011f0db4f90e250e5bc0c0a85a813085",
|
||||
"sha256:e55e22ac0a30023426564b1059b035973ec82186ddddbac867078435801c7801",
|
||||
"sha256:e90f17980e6ab0f3c2f3730e56d1fe9bcba1891eeea58966e89d352492cc74f4",
|
||||
"sha256:ecbb7b01409e9b782df5ded849c178a0aa7c906cf8c5a67368047daab282b184",
|
||||
"sha256:ed01918d545a38998bfa5902c7c00e0fee90e957ce036a4000a88e3fe2264917",
|
||||
"sha256:edabd457cd23a02965166026fd9bfd196f4324fe6032e866d0f3bd0301cd486f",
|
||||
"sha256:fdf1c1dc5bafc32bc5d08b054f94d659422b05aba244d6be4ddc1c72d9aa70fb"
|
||||
],
|
||||
"version": "==1.11.5"
|
||||
},
|
||||
"chardet": {
|
||||
"hashes": [
|
||||
"sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae",
|
||||
"sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"
|
||||
],
|
||||
"version": "==3.0.4"
|
||||
},
|
||||
"contextlib2": {
|
||||
"hashes": [
|
||||
"sha256:509f9419ee91cdd00ba34443217d5ca51f5a364a404e1dce9e8979cea969ca48",
|
||||
"sha256:f5260a6e679d2ff42ec91ec5252f4eeffdcf21053db9113bd0a8e4d953769c00"
|
||||
],
|
||||
"version": "==0.5.5"
|
||||
},
|
||||
"cryptography": {
|
||||
"hashes": [
|
||||
"sha256:02602e1672b62e803e08617ec286041cc453e8d43f093a5f4162095506bc0beb",
|
||||
"sha256:10b48e848e1edb93c1d3b797c83c72b4c387ab0eb4330aaa26da8049a6cbede0",
|
||||
"sha256:17db09db9d7c5de130023657be42689d1a5f60502a14f6f745f6f65a6b8195c0",
|
||||
"sha256:227da3a896df1106b1a69b1e319dce218fa04395e8cc78be7e31ca94c21254bc",
|
||||
"sha256:2cbaa03ac677db6c821dac3f4cdfd1461a32d0615847eedbb0df54bb7802e1f7",
|
||||
"sha256:31db8febfc768e4b4bd826750a70c79c99ea423f4697d1dab764eb9f9f849519",
|
||||
"sha256:4a510d268e55e2e067715d728e4ca6cd26a8e9f1f3d174faf88e6f2cb6b6c395",
|
||||
"sha256:6a88d9004310a198c474d8a822ee96a6dd6c01efe66facdf17cb692512ae5bc0",
|
||||
"sha256:76936ec70a9b72eb8c58314c38c55a0336a2b36de0c7ee8fb874a4547cadbd39",
|
||||
"sha256:7e3b4aecc4040928efa8a7cdaf074e868af32c58ffc9bb77e7bf2c1a16783286",
|
||||
"sha256:8168bcb08403ef144ff1fb880d416f49e2728101d02aaadfe9645883222c0aa5",
|
||||
"sha256:8229ceb79a1792823d87779959184a1bf95768e9248c93ae9f97c7a2f60376a1",
|
||||
"sha256:8a19e9f2fe69f6a44a5c156968d9fc8df56d09798d0c6a34ccc373bb186cee86",
|
||||
"sha256:8d10113ca826a4c29d5b85b2c4e045ffa8bad74fb525ee0eceb1d38d4c70dfd6",
|
||||
"sha256:be495b8ec5a939a7605274b6e59fbc35e76f5ad814ae010eb679529671c9e119",
|
||||
"sha256:dc2d3f3b1548f4d11786616cf0f4415e25b0fbecb8a1d2cd8c07568f13fdde38",
|
||||
"sha256:e4aecdd9d5a3d06c337894c9a6e2961898d3f64fe54ca920a72234a3de0f9cb3",
|
||||
"sha256:e79ab4485b99eacb2166f3212218dd858258f374855e1568f728462b0e6ee0d9",
|
||||
"sha256:f995d3667301e1754c57b04e0bae6f0fa9d710697a9f8d6712e8cca02550910f"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.3.1"
|
||||
},
|
||||
"cssselect": {
|
||||
"hashes": [
|
||||
"sha256:066d8bc5229af09617e24b3ca4d52f1f9092d9e061931f4184cd572885c23204",
|
||||
"sha256:3b5103e8789da9e936a68d993b70df732d06b8bb9a337a05ed4eb52c17ef7206"
|
||||
],
|
||||
"version": "==1.0.3"
|
||||
},
|
||||
"cssutils": {
|
||||
"hashes": [
|
||||
"sha256:a2fcf06467553038e98fea9cfe36af2bf14063eb147a70958cfcaa8f5786acaf",
|
||||
"sha256:c74dbe19c92f5052774eadb15136263548dd013250f1ed1027988e7fef125c8d"
|
||||
],
|
||||
"version": "==1.0.2"
|
||||
},
|
||||
"diff-match-patch": {
|
||||
"hashes": [
|
||||
"sha256:9dba5611fbf27893347349fd51cc1911cb403682a7163373adacc565d11e2e4c"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==20121119"
|
||||
},
|
||||
"django": {
|
||||
"hashes": [
|
||||
"sha256:29268cc47816a44f27308e60f71da635f549c47d8a1d003b28de55141df75791",
|
||||
"sha256:37f5876c1fbfd66085001f4c06fa0bf96ef05442c53daf8d4294b6f29e7fa6b8"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==1.11.16"
|
||||
},
|
||||
"django-ipware": {
|
||||
"hashes": [
|
||||
"sha256:93a90f9dd8caf2c633172aa8c8ba4e76e2b44f92a6942fa35e7624281e81ea03"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==1.1.6"
|
||||
},
|
||||
"django-jinja": {
|
||||
"hashes": [
|
||||
"sha256:5e826a0cce967f40e6fdc037ea23667a2d3cd072807c4c87ffcc010b3c59121f",
|
||||
"sha256:ebfde44cb716e57a9cdff6c1a4935fc49c7419ea4cd0b2b89bcecc696b9c0c86"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.3.1"
|
||||
},
|
||||
"django-pglocks": {
|
||||
"hashes": [
|
||||
"sha256:9405ee54bbf157bb16b814f20ea7ad9d82d5cf26f9bf3ea8e3a71032179844cf"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==1.0.2"
|
||||
},
|
||||
"django-picklefield": {
|
||||
"hashes": [
|
||||
"sha256:5489fef164de43725242d56e65e016137d3df0d1a00672bda72d807f5b2b0d99",
|
||||
"sha256:fab48a427c6310740755b242128f9300283bef159ffee42d3231a274c65d9ae2"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.3.2"
|
||||
},
|
||||
"django-sampledatahelper": {
|
||||
"hashes": [
|
||||
"sha256:96d0a599054979eb9669d44a1735236da42d56be0c45d4bcd34c2a3acefb259d"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.4.1"
|
||||
},
|
||||
"django-sites": {
|
||||
"hashes": [
|
||||
"sha256:fa1470bd72be589f3891b7cd28dd2d782d8b34539665d9334e49154566f3d916"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.9"
|
||||
},
|
||||
"django-sr": {
|
||||
"hashes": [
|
||||
"sha256:3586b852ae8af1b4b2796590534b0b867b523f47a5779b2ccb6ce010efc57e34"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.0.4"
|
||||
},
|
||||
"djmail": {
|
||||
"hashes": [
|
||||
"sha256:370f57230bf79004840ddd1cb8150a5b7676b2aa14bc5b62027106cb708a47a0"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==1.0.1"
|
||||
},
|
||||
"docopt": {
|
||||
"hashes": [
|
||||
"sha256:49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491"
|
||||
],
|
||||
"version": "==0.6.2"
|
||||
},
|
||||
"easy-thumbnails": {
|
||||
"hashes": [
|
||||
"sha256:5cc51c6ec7de110355d0f8cd56c9ede6e2949e87c2fcb34bc864a20ecd424270",
|
||||
"sha256:6e41e70a182a6d00af9f3f3a6d1cc87cb7da060a3d56982da51d266e40fc9b59"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.4.1"
|
||||
},
|
||||
"fn": {
|
||||
"hashes": [
|
||||
"sha256:f8cd80cdabf15367a2f07e7a9951fdc013d7200412743d85b88f2c896c95bada"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.4.3"
|
||||
},
|
||||
"gunicorn": {
|
||||
"hashes": [
|
||||
"sha256:75af03c99389535f218cc596c7de74df4763803f7b63eb09d77e92b3956b36c6",
|
||||
"sha256:eee1169f0ca667be05db3351a0960765620dad53f53434262ff8901b68a1b622"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==19.7.1"
|
||||
},
|
||||
"html5lib": {
|
||||
"hashes": [
|
||||
"sha256:20b159aa3badc9d5ee8f5c647e5efd02ed2a66ab8d354930bd9ff139fc1dc0a3",
|
||||
"sha256:66cb0dcfdbbc4f9c3ba1a63fdb511ffdbd4f513b2b6d81b80cd26ce6b3fb3736"
|
||||
],
|
||||
"version": "==1.0.1"
|
||||
},
|
||||
"idna": {
|
||||
"hashes": [
|
||||
"sha256:156a6814fb5ac1fc6850fb002e0852d56c0c8d2531923a51032d1b70760e186e",
|
||||
"sha256:684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16"
|
||||
],
|
||||
"version": "==2.7"
|
||||
},
|
||||
"jinja2": {
|
||||
"hashes": [
|
||||
"sha256:74c935a1b8bb9a3947c50a54766a969d4846290e1e788ea44c1392163723c3bd",
|
||||
"sha256:f84be1bb0040caca4cea721fcbbbbd61f9be9464ca236387158b0feea01914a4"
|
||||
],
|
||||
"version": "==2.10"
|
||||
},
|
||||
"kombu": {
|
||||
"hashes": [
|
||||
"sha256:385bf38e6de7f3851f674671dbfe24572ce999608d293a85fb8a630654d8bd9c",
|
||||
"sha256:d0fc6f2a36610a308f838db4b832dad79a681b516ac1d1a1f9d42edb58cc11a2"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==4.0.2"
|
||||
},
|
||||
"lxml": {
|
||||
"hashes": [
|
||||
"sha256:02bc220d61f46e9b9d5a53c361ef95e9f5e1d27171cd461dddb17677ae2289a5",
|
||||
"sha256:22f253b542a342755f6cfc047fe4d3a296515cf9b542bc6e261af45a80b8caf6",
|
||||
"sha256:2f31145c7ff665b330919bfa44aacd3a0211a76ca7e7b441039d2a0b0451e415",
|
||||
"sha256:36720698c29e7a9626a0dc802ef8885f8f0239bfd1689628ecd459a061f2807f",
|
||||
"sha256:438a1b0203545521f6616132bfe0f4bca86f8a401364008b30e2b26ec408ce85",
|
||||
"sha256:4815892904c336bbaf73dafd54f45f69f4021c22b5bad7332176bbf4fb830568",
|
||||
"sha256:5be031b0f15ad63910d8e5038b489d95a79929513b3634ad4babf77100602588",
|
||||
"sha256:5c93ae37c3c588e829b037fdfbd64a6e40c901d3f93f7beed6d724c44829a3ad",
|
||||
"sha256:60842230678674cdac4a1cf0f707ef12d75b9a4fc4a565add4f710b5fcf185d5",
|
||||
"sha256:62939a8bb6758d1bf923aa1c13f0bcfa9bf5b2fc0f5fa917a6e25db5fe0cfa4e",
|
||||
"sha256:75830c06a62fe7b8fe3bbb5f269f0b308f19f3949ac81cfd40062f47c1455faf",
|
||||
"sha256:81992565b74332c7c1aff6a913a3e906771aa81c9d0c68c68113cffcae45bc53",
|
||||
"sha256:8c892fb0ee52c594d9a7751c7d7356056a9682674b92cc1c4dc968ff0f30c52f",
|
||||
"sha256:9d862e3cf4fc1f2837dedce9c42269c8c76d027e49820a548ac89fdcee1e361f",
|
||||
"sha256:a623965c086a6e91bb703d4da62dabe59fe88888e82c4117d544e11fd74835d6",
|
||||
"sha256:a7783ab7f6a508b0510490cef9f857b763d796ba7476d9703f89722928d1e113",
|
||||
"sha256:aab09fbe8abfa3b9ce62aaf45aca2d28726b1b9ee44871dbe644050a2fff4940",
|
||||
"sha256:abf181934ac3ef193832fb973fd7f6149b5c531903c2ec0f1220941d73eee601",
|
||||
"sha256:ae07fa0c115733fce1e9da96a3ac3fa24801742ca17e917e0c79d63a01eeb843",
|
||||
"sha256:b9c78242219f674ab645ec571c9a95d70f381319a23911941cd2358a8e0521cf",
|
||||
"sha256:bccb267678b870d9782c3b44d0cefe3ba0e329f9af8c946d32bf3778e7a4f271",
|
||||
"sha256:c4df4d27f4c93b2cef74579f00b1d3a31a929c7d8023f870c4b476f03a274db4",
|
||||
"sha256:caf0e50b546bb60dfa99bb18dfa6748458a83131ecdceaf5c071d74907e7e78a",
|
||||
"sha256:d3266bd3ac59ac4edcd5fa75165dee80b94a3e5c91049df5f7c057ccf097551c",
|
||||
"sha256:db0d213987bcd4e6d41710fb4532b22315b0d8fb439ff901782234456556aed1",
|
||||
"sha256:dbbd5cf7690a40a9f0a9325ab480d0fccf46d16b378eefc08e195d84299bfae1",
|
||||
"sha256:e16e07a0ec3a75b5ee61f2b1003c35696738f937dc8148fbda9fe2147ccb6e61",
|
||||
"sha256:e175a006725c7faadbe69e791877d09936c0ef2cf49d01b60a6c1efcb0e8be6f",
|
||||
"sha256:edd9c13a97f6550f9da2236126bb51c092b3b1ce6187f2bd966533ad794bbb5e",
|
||||
"sha256:fa39ea60d527fbdd94215b5e5552f1c6a912624521093f1384a491a8ad89ad8b"
|
||||
],
|
||||
"version": "==4.2.5"
|
||||
},
|
||||
"markdown": {
|
||||
"hashes": [
|
||||
"sha256:c00429bd503a47ec88d5e30a751e147dcb4c6889663cd3e2ba0afe858e009baa",
|
||||
"sha256:d02e0f9b04c500cde6637c11ad7c72671f359b87b9fe924b2383649d8841db7c"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==3.0.1"
|
||||
},
|
||||
"markupsafe": {
|
||||
"hashes": [
|
||||
"sha256:048ef924c1623740e70204aa7143ec592504045ae4429b59c30054cb31e3c432",
|
||||
"sha256:130f844e7f5bdd8e9f3f42e7102ef1d49b2e6fdf0d7526df3f87281a532d8c8b",
|
||||
"sha256:19f637c2ac5ae9da8bfd98cef74d64b7e1bb8a63038a3505cd182c3fac5eb4d9",
|
||||
"sha256:1b8a7a87ad1b92bd887568ce54b23565f3fd7018c4180136e1cf412b405a47af",
|
||||
"sha256:1c25694ca680b6919de53a4bb3bdd0602beafc63ff001fea2f2fc16ec3a11834",
|
||||
"sha256:1f19ef5d3908110e1e891deefb5586aae1b49a7440db952454b4e281b41620cd",
|
||||
"sha256:1fa6058938190ebe8290e5cae6c351e14e7bb44505c4a7624555ce57fbbeba0d",
|
||||
"sha256:31cbb1359e8c25f9f48e156e59e2eaad51cd5242c05ed18a8de6dbe85184e4b7",
|
||||
"sha256:3e835d8841ae7863f64e40e19477f7eb398674da6a47f09871673742531e6f4b",
|
||||
"sha256:4e97332c9ce444b0c2c38dd22ddc61c743eb208d916e4265a2a3b575bdccb1d3",
|
||||
"sha256:525396ee324ee2da82919f2ee9c9e73b012f23e7640131dd1b53a90206a0f09c",
|
||||
"sha256:52b07fbc32032c21ad4ab060fec137b76eb804c4b9a1c7c7dc562549306afad2",
|
||||
"sha256:52ccb45e77a1085ec5461cde794e1aa037df79f473cbc69b974e73940655c8d7",
|
||||
"sha256:5c3fbebd7de20ce93103cb3183b47671f2885307df4a17a0ad56a1dd51273d36",
|
||||
"sha256:5e5851969aea17660e55f6a3be00037a25b96a9b44d2083651812c99d53b14d1",
|
||||
"sha256:5edfa27b2d3eefa2210fb2f5d539fbed81722b49f083b2c6566455eb7422fd7e",
|
||||
"sha256:7d263e5770efddf465a9e31b78362d84d015cc894ca2c131901a4445eaa61ee1",
|
||||
"sha256:83381342bfc22b3c8c06f2dd93a505413888694302de25add756254beee8449c",
|
||||
"sha256:857eebb2c1dc60e4219ec8e98dfa19553dae33608237e107db9c6078b1167856",
|
||||
"sha256:98e439297f78fca3a6169fd330fbe88d78b3bb72f967ad9961bcac0d7fdd1550",
|
||||
"sha256:bf54103892a83c64db58125b3f2a43df6d2cb2d28889f14c78519394feb41492",
|
||||
"sha256:d9ac82be533394d341b41d78aca7ed0e0f4ba5a2231602e2f05aa87f25c51672",
|
||||
"sha256:e982fe07ede9fada6ff6705af70514a52beb1b2c3d25d4e873e82114cf3c5401",
|
||||
"sha256:edce2ea7f3dfc981c4ddc97add8a61381d9642dc3273737e756517cc03e84dd6",
|
||||
"sha256:efdc45ef1afc238db84cb4963aa689c0408912a0239b0721cb172b4016eb31d6",
|
||||
"sha256:f137c02498f8b935892d5c0172560d7ab54bc45039de8805075e19079c639a9c",
|
||||
"sha256:f82e347a72f955b7017a39708a3667f106e6ad4d10b25f237396a7115d8ed5fd",
|
||||
"sha256:fb7c206e01ad85ce57feeaaa0bf784b97fa3cad0d4a5737bc5295785f5c613a1"
|
||||
],
|
||||
"version": "==1.1.0"
|
||||
},
|
||||
"netaddr": {
|
||||
"hashes": [
|
||||
"sha256:38aeec7cdd035081d3a4c306394b19d677623bf76fa0913f6695127c7753aefd",
|
||||
"sha256:56b3558bd71f3f6999e4c52e349f38660e54a7a8a9943335f73dfc96883e08ca"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.7.19"
|
||||
},
|
||||
"oauthlib": {
|
||||
"hashes": [
|
||||
"sha256:ac35665a61c1685c56336bda97d5eefa246f1202618a1d6f34fccb1bdd404162",
|
||||
"sha256:d883b36b21a6ad813953803edfa563b1b579d79ca758fe950d1bc9e8b326025b"
|
||||
],
|
||||
"version": "==2.1.0"
|
||||
},
|
||||
"olefile": {
|
||||
"hashes": [
|
||||
"sha256:133b031eaf8fd2c9399b78b8bc5b8fcbe4c31e85295749bb17a87cba8f3c3964"
|
||||
],
|
||||
"version": "==0.46"
|
||||
},
|
||||
"pillow": {
|
||||
"hashes": [
|
||||
"sha256:00b6a5f28d00f720235a937ebc2f50f4292a5c7e2d6ab9a8b26153b625c4f431",
|
||||
"sha256:025208f835383f425e93d574842f9c5d28918cd4cdf632c1ce2e72ab80d8fcc8",
|
||||
"sha256:059a9b4e064b70e1396a3ae64781a91512f773cae548c24b12014616f723f22d",
|
||||
"sha256:17f7702f22729ffeb69f5226abf3261ef2d2eb73ab5854c1294daa3bdb5bdfb7",
|
||||
"sha256:20a3549d7a83e969eb900c726d54b34673efc1d0e3c9856b8227350f7e21d968",
|
||||
"sha256:24258e1875c8a9de1b176bf1873436397669440d1561b06b00eb270bffefcb42",
|
||||
"sha256:318b4404c8ca34cc1514d60de81ac4a0b0d11031a70341c2b7cd4fc01c914d89",
|
||||
"sha256:33a71986741227c8c085ee5929171cd4c9376b2eee189cdc7acc7d81e1a3ca84",
|
||||
"sha256:3499deb97561d6cc75de725fcf744491dd2d10d6213a29c4d62e3980e1522715",
|
||||
"sha256:3ad24690882b68599b9e6b25309000881eebcc731ca499f8dcc549fab006e4a3",
|
||||
"sha256:3c05df947656d8538dfb39fb8ddb9fe3594c9345911aa19f07e2ed0a8d148a6d",
|
||||
"sha256:48cdae5e5291d355fc215ede2ea93738e243c2467b11e41fa5010a76fd278fc5",
|
||||
"sha256:4b382c0ee6ac822673e1a57c2e9878d2ac4cd52038be097bac8535a2ee60ec0e",
|
||||
"sha256:6458293cf299f02f17f58a1ee4b91f77b8ce7a38bc0e757838767f1389479953",
|
||||
"sha256:8ef6627adfe9314b4132d4f5207563ba147e3977019ab1ca3f0b11b04c83c84f",
|
||||
"sha256:9c508bf0b2aadad4349f69aebe080977dbf0cd055cefc15793c4165851a96933",
|
||||
"sha256:9d7c0706cd86fc17643d78674cdac7f05590a2da1d71c42c2ebfb27df3889f17",
|
||||
"sha256:a2a873b54881c4cf4d8b37f3c426c2b8f797b341e3893650763a62252bda3922",
|
||||
"sha256:b79fc81352a3c907a1223499d790a4a7b77be342b794e19628046c4c95676356",
|
||||
"sha256:c040a047209edaf860ce6dd5b55de718e047144b26b0ee4198dd19907c128eac",
|
||||
"sha256:d71992826cfed66f5ad68364b2c6c3c1ab305294a642deae96ad77004981fb0f",
|
||||
"sha256:e467d0977997b43ca80b7af42de3d1cfa779988f6507965e6d4fb1a004e963a0",
|
||||
"sha256:ecf810b5019ce62846a9203bab82eb02bb9ed60e258b2fd89e2ca19a7010da46",
|
||||
"sha256:f4fb801bfd2bcbfc4a7f2819c95ea6a1cfef197420ae9849b01b08b9970a51b3",
|
||||
"sha256:f63404731fa5fa0c21d00af119b867e30208e3fc148c9b13fb6a541a8df203b2",
|
||||
"sha256:f8e8f3f20e32f73f81ec408061f7a81ada07d7b3fac0787bdd233b93e4ff7d9c",
|
||||
"sha256:fb3eaba16b6cf01f12860edccac40f98362bc17225575f3bcabb333d0b4ed6dc"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==4.1.1"
|
||||
},
|
||||
"premailer": {
|
||||
"hashes": [
|
||||
"sha256:25c97c4c1838a8045ed1da1a14bd82ce458687878aa162378a78aa82a6aec6af",
|
||||
"sha256:4e71cc09ad1438f827d1070ffac54ceb3a6a07c995fa82cb34c1ef163adeb432"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==3.0.1"
|
||||
},
|
||||
"psd-tools": {
|
||||
"hashes": [
|
||||
"sha256:1a8dd69783c84217f3a25938916c289e5653543c5610e9013769520e8bd65b3c",
|
||||
"sha256:7f3fd8577fb627405a204a65d4ccea48299f95338a71fbd9709bdb9d7789cc4e",
|
||||
"sha256:f519a08049c19b3ef37ccc2b39af11ac5ded59d2674fc4c28103e4db57a9aa99"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==1.4"
|
||||
},
|
||||
"psycopg2-binary": {
|
||||
"hashes": [
|
||||
"sha256:04afb59bbbd2eab3148e6816beddc74348078b8c02a1113ea7f7822f5be4afe3",
|
||||
"sha256:098b18f4d8857a8f9b206d1dc54db56c2255d5d26458917e7bcad61ebfe4338f",
|
||||
"sha256:0bf855d4a7083e20ead961fda4923887094eaeace0ab2d76eb4aa300f4bbf5bd",
|
||||
"sha256:197dda3ffd02057820be83fe4d84529ea70bf39a9a4daee1d20ffc74eb3d042e",
|
||||
"sha256:278ef63afb4b3d842b4609f2c05ffbfb76795cf6a184deeb8707cd5ed3c981a5",
|
||||
"sha256:3cbf8c4fc8f22f0817220891cf405831559f4d4c12c4f73913730a2ea6c47a47",
|
||||
"sha256:4305aed922c4d9d6163ab3a41d80b5a1cfab54917467da8168552c42cad84d32",
|
||||
"sha256:47ee296f704fb8b2a616dec691cdcfd5fa0f11943955e88faa98cbd1dc3b3e3d",
|
||||
"sha256:4a0e38cb30457e70580903367161173d4a7d1381eb2f2cfe4e69b7806623f484",
|
||||
"sha256:4d6c294c6638a71cafb82a37f182f24321f1163b08b5d5ca076e11fe838a3086",
|
||||
"sha256:4f3233c366500730f839f92833194fd8f9a5c4529c8cd8040aa162c3740de8e5",
|
||||
"sha256:5221f5a3f4ca2ddf0d58e8b8a32ca50948be9a43351fda797eb4e72d7a7aa34d",
|
||||
"sha256:5c6ca0b507540a11eaf9e77dee4f07c131c2ec80ca0cffa146671bf690bc1c02",
|
||||
"sha256:789bd89d71d704db2b3d5e67d6d518b158985d791d3b2dec5ab85457cfc9677b",
|
||||
"sha256:7b94d29239efeaa6a967f3b5971bd0518d2a24edd1511edbf4a2c8b815220d07",
|
||||
"sha256:89bc65ef3301c74cf32db25334421ea6adbe8f65601ea45dcaaf095abed910bb",
|
||||
"sha256:89d6d3a549f405c20c9ae4dc94d7ed2de2fa77427a470674490a622070732e62",
|
||||
"sha256:97521704ac7127d7d8ba22877da3c7bf4a40366587d238ec679ff38e33177498",
|
||||
"sha256:a395b62d5f44ff6f633231abe568e2203b8fabf9797cd6386aa92497df912d9a",
|
||||
"sha256:a6d32c37f714c3f34158f3fa659f3a8f2658d5f53c4297d45579b9677cc4d852",
|
||||
"sha256:a89ee5c26f72f2d0d74b991ce49e42ddeb4ac0dc2d8c06a0f2770a1ab48f4fe0",
|
||||
"sha256:b4c8b0ef3608e59317bfc501df84a61e48b5445d45f24d0391a24802de5f2d84",
|
||||
"sha256:b5fcf07140219a1f71e18486b8dc28e2e1b76a441c19374805c617aa6d9a9d55",
|
||||
"sha256:b86f527f00956ecebad6ab3bb30e3a75fedf1160a8716978dd8ce7adddedd86f",
|
||||
"sha256:be4c4aa22ba22f70de36c98b06480e2f1697972d49eb20d525f400d204a6d272",
|
||||
"sha256:c2ac7aa1a144d4e0e613ac7286dae85671e99fe7a1353954d4905629c36b811c",
|
||||
"sha256:de26ef4787b5e778e8223913a3e50368b44e7480f83c76df1f51d23bd21cea16",
|
||||
"sha256:e70ebcfc5372dc7b699c0110454fc4263967f30c55454397e5769eb72c0eb0ce",
|
||||
"sha256:eadbd32b6bc48b67b0457fccc94c86f7ccc8178ab839f684eb285bb592dc143e",
|
||||
"sha256:ecbc6dfff6db06b8b72ae8a2f25ff20fbdcb83cb543811a08f7cb555042aa729"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.7.5"
|
||||
},
|
||||
"pycparser": {
|
||||
"hashes": [
|
||||
"sha256:a988718abfad80b6b157acce7bf130a30876d27603738ac39f140993246b25b3"
|
||||
],
|
||||
"version": "==2.19"
|
||||
},
|
||||
"pygments": {
|
||||
"hashes": [
|
||||
"sha256:78f3f434bcc5d6ee09020f92ba487f95ba50f1e3ef83ae96b9d5ffa1bab25c5d",
|
||||
"sha256:dbae1046def0efb574852fab9e90209b23f556367b5a320c0bcb871c77c3e8cc"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.2.0"
|
||||
},
|
||||
"pyjwt": {
|
||||
"hashes": [
|
||||
"sha256:00414bfef802aaecd8cc0d5258b6cb87bd8f553c2986c2c5f29b19dd5633aeb7",
|
||||
"sha256:ddec8409c57e9d371c6006e388f91daf3b0b43bdf9fcbf99451fb7cf5ce0a86d"
|
||||
],
|
||||
"version": "==1.7.0"
|
||||
},
|
||||
"python-dateutil": {
|
||||
"hashes": [
|
||||
"sha256:063df5763652e21de43de7d9e00ccf239f953a832941e37be541614732cdfc93",
|
||||
"sha256:88f9287c0174266bb0d8cedd395cfba9c58e87e5ad86b2ce58859bc11be3cf02"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.7.5"
|
||||
},
|
||||
"python-magic": {
|
||||
"hashes": [
|
||||
"sha256:604eace6f665809bebbb07070508dfa8cabb2d7cb05be9a56706c60f864f1289",
|
||||
"sha256:a1ec69e76cc513b1af164c02982607f96ff3bb668162a688f2b1bb5f6a5fe05d"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.4.13"
|
||||
},
|
||||
"pytz": {
|
||||
"hashes": [
|
||||
"sha256:31cb35c89bd7d333cd32c5f278fca91b523b0834369e757f4c5641ea252236ca",
|
||||
"sha256:8e0f8568c118d3077b46be7d654cc8167fa916092e28320cde048e54bfc9f1e6"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2018.7"
|
||||
},
|
||||
"raven": {
|
||||
"hashes": [
|
||||
"sha256:02cabffb173b99d860a95d4908e8b1864aad1b8452146e13fd7e212aa576a884",
|
||||
"sha256:56dc9062dd42bca97350e5048ff417c914376366caa3b1b5f788b27ddc0a34b7"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==6.1.0"
|
||||
},
|
||||
"redis": {
|
||||
"hashes": [
|
||||
"sha256:5dfbae6acfc54edf0a7a415b99e0b21c0a3c27a7f787b292eea727b1facc5533",
|
||||
"sha256:97156b37d7cda4e7d8658be1148c983984e1a975090ba458cc7e244025191dbd"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.10.5"
|
||||
},
|
||||
"requests": {
|
||||
"hashes": [
|
||||
"sha256:99dcfdaaeb17caf6e526f32b6a7b780461512ab3f1d992187801694cba42770c",
|
||||
"sha256:a84b8c9ab6239b578f22d1c21d51b696dcfe004032bb80ea832398d6909d7279"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.20.0"
|
||||
},
|
||||
"requests-oauthlib": {
|
||||
"hashes": [
|
||||
"sha256:50a8ae2ce8273e384895972b56193c7409601a66d4975774c60c2aed869639ca",
|
||||
"sha256:883ac416757eada6d3d07054ec7092ac21c7f35cb1d2cf82faf205637081f468"
|
||||
],
|
||||
"version": "==0.8.0"
|
||||
},
|
||||
"sampledata": {
|
||||
"hashes": [
|
||||
"sha256:b06916ef010d3c1a9db8aa314a144f24ad421f28597ff8c568603c451391a2cf"
|
||||
],
|
||||
"version": "==0.3.7"
|
||||
},
|
||||
"serpy": {
|
||||
"hashes": [
|
||||
"sha256:b1481f8cb93d767b23903d1df6cc0a7120cb0694095b6695eb78d9d453b23c65",
|
||||
"sha256:b774bfdf0c3b245660639e9fc5f311a8bbceb2725aaba72fce1fec00b453286e"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.1.1"
|
||||
},
|
||||
"six": {
|
||||
"hashes": [
|
||||
"sha256:70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9",
|
||||
"sha256:832dc0e10feb1aa2c68dcc57dbb658f1c7e65b9b61af69048abc87a2db00a0eb"
|
||||
],
|
||||
"version": "==1.11.0"
|
||||
},
|
||||
"tinycss": {
|
||||
"hashes": [
|
||||
"sha256:12306fb50e5e9e7eaeef84b802ed877488ba80e35c672867f548c0924a76716e"
|
||||
],
|
||||
"version": "==0.4"
|
||||
},
|
||||
"unidecode": {
|
||||
"hashes": [
|
||||
"sha256:ed4418b4b1b190487753f1cca6299e8076079258647284414e6d607d1f8a00e0",
|
||||
"sha256:eedac7bfd886f43484787206f6a141b232e2b2a58652c54d06499b187fd84660"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==0.4.20"
|
||||
},
|
||||
"urllib3": {
|
||||
"hashes": [
|
||||
"sha256:61bf29cada3fc2fbefad4fdf059ea4bd1b4a86d2b6d15e1c7c0b582b9752fe39",
|
||||
"sha256:de9529817c93f27c8ccbfead6985011db27bd0ddfcdb2d86f3f663385c6a9c22"
|
||||
],
|
||||
"version": "==1.24.1"
|
||||
},
|
||||
"vine": {
|
||||
"hashes": [
|
||||
"sha256:52116d59bc45392af9fdd3b75ed98ae48a93e822cee21e5fda249105c59a7a72",
|
||||
"sha256:6849544be74ec3638e84d90bc1cf2e1e9224cc10d96cd4383ec3f69e9bce077b"
|
||||
],
|
||||
"version": "==1.1.4"
|
||||
},
|
||||
"webcolors": {
|
||||
"hashes": [
|
||||
"sha256:e47e68644d41c0b1f1e4d939cfe4039bdf1ab31234df63c7a4f59d4766487206"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==1.7"
|
||||
},
|
||||
"webencodings": {
|
||||
"hashes": [
|
||||
"sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78",
|
||||
"sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923"
|
||||
],
|
||||
"version": "==0.5.1"
|
||||
}
|
||||
},
|
||||
"develop": {
|
||||
"atomicwrites": {
|
||||
"hashes": [
|
||||
"sha256:0312ad34fcad8fac3704d441f7b317e50af620823353ec657a53e981f92920c0",
|
||||
"sha256:ec9ae8adaae229e4f8446952d204a3e4b5fdd2d099f9be3aaf556120135fb3ee"
|
||||
],
|
||||
"version": "==1.2.1"
|
||||
},
|
||||
"attrs": {
|
||||
"hashes": [
|
||||
"sha256:10cbf6e27dbce8c30807caf056c8eb50917e0eaafe86347671b57254006c3e69",
|
||||
"sha256:ca4be454458f9dec299268d472aaa5a11f67a4ff70093396e1ceae9c76cf4bbb"
|
||||
],
|
||||
"version": "==18.2.0"
|
||||
},
|
||||
"certifi": {
|
||||
"hashes": [
|
||||
"sha256:47f9c83ef4c0c621eaef743f133f09fa8a74a9b75f037e8624f83bd1b6626cb7",
|
||||
"sha256:993f830721089fef441cdfeb4b2c8c9df86f0c63239f06bd025a76a7daddb033"
|
||||
],
|
||||
"version": "==2018.11.29"
|
||||
},
|
||||
"chardet": {
|
||||
"hashes": [
|
||||
"sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae",
|
||||
"sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691"
|
||||
],
|
||||
"version": "==3.0.4"
|
||||
},
|
||||
"coverage": {
|
||||
"hashes": [
|
||||
"sha256:09e47c529ff77bf042ecfe858fb55c3e3eb97aac2c87f0349ab5a7efd6b3939f",
|
||||
"sha256:0a1f9b0eb3aa15c990c328535655847b3420231af299386cfe5efc98f9c250fe",
|
||||
"sha256:0cc941b37b8c2ececfed341444a456912e740ecf515d560de58b9a76562d966d",
|
||||
"sha256:10e8af18d1315de936d67775d3a814cc81d0747a1a0312d84e27ae5610e313b0",
|
||||
"sha256:1b4276550b86caa60606bd3572b52769860a81a70754a54acc8ba789ce74d607",
|
||||
"sha256:1e8a2627c48266c7b813975335cfdea58c706fe36f607c97d9392e61502dc79d",
|
||||
"sha256:2b224052bfd801beb7478b03e8a66f3f25ea56ea488922e98903914ac9ac930b",
|
||||
"sha256:447c450a093766744ab53bf1e7063ec82866f27bcb4f4c907da25ad293bba7e3",
|
||||
"sha256:46101fc20c6f6568561cdd15a54018bb42980954b79aa46da8ae6f008066a30e",
|
||||
"sha256:4710dc676bb4b779c4361b54eb308bc84d64a2fa3d78e5f7228921eccce5d815",
|
||||
"sha256:510986f9a280cd05189b42eee2b69fecdf5bf9651d4cd315ea21d24a964a3c36",
|
||||
"sha256:5535dda5739257effef56e49a1c51c71f1d37a6e5607bb25a5eee507c59580d1",
|
||||
"sha256:5a7524042014642b39b1fcae85fb37556c200e64ec90824ae9ecf7b667ccfc14",
|
||||
"sha256:5f55028169ef85e1fa8e4b8b1b91c0b3b0fa3297c4fb22990d46ff01d22c2d6c",
|
||||
"sha256:6694d5573e7790a0e8d3d177d7a416ca5f5c150742ee703f3c18df76260de794",
|
||||
"sha256:6831e1ac20ac52634da606b658b0b2712d26984999c9d93f0c6e59fe62ca741b",
|
||||
"sha256:77f0d9fa5e10d03aa4528436e33423bfa3718b86c646615f04616294c935f840",
|
||||
"sha256:828ad813c7cdc2e71dcf141912c685bfe4b548c0e6d9540db6418b807c345ddd",
|
||||
"sha256:85a06c61598b14b015d4df233d249cd5abfa61084ef5b9f64a48e997fd829a82",
|
||||
"sha256:8cb4febad0f0b26c6f62e1628f2053954ad2c555d67660f28dfb1b0496711952",
|
||||
"sha256:a5c58664b23b248b16b96253880b2868fb34358911400a7ba39d7f6399935389",
|
||||
"sha256:aaa0f296e503cda4bc07566f592cd7a28779d433f3a23c48082af425d6d5a78f",
|
||||
"sha256:ab235d9fe64833f12d1334d29b558aacedfbca2356dfb9691f2d0d38a8a7bfb4",
|
||||
"sha256:b3b0c8f660fae65eac74fbf003f3103769b90012ae7a460863010539bb7a80da",
|
||||
"sha256:bab8e6d510d2ea0f1d14f12642e3f35cefa47a9b2e4c7cea1852b52bc9c49647",
|
||||
"sha256:c45297bbdbc8bb79b02cf41417d63352b70bcb76f1bbb1ee7d47b3e89e42f95d",
|
||||
"sha256:d19bca47c8a01b92640c614a9147b081a1974f69168ecd494687c827109e8f42",
|
||||
"sha256:d64b4340a0c488a9e79b66ec9f9d77d02b99b772c8b8afd46c1294c1d39ca478",
|
||||
"sha256:da969da069a82bbb5300b59161d8d7c8d423bc4ccd3b410a9b4d8932aeefc14b",
|
||||
"sha256:ed02c7539705696ecb7dc9d476d861f3904a8d2b7e894bd418994920935d36bb",
|
||||
"sha256:ee5b8abc35b549012e03a7b1e86c09491457dba6c94112a2482b18589cc2bdb9"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==4.5.2"
|
||||
},
|
||||
"coveralls": {
|
||||
"hashes": [
|
||||
"sha256:ab638e88d38916a6cedbf80a9cd8992d5fa55c77ab755e262e00b36792b7cd6d",
|
||||
"sha256:b2388747e2529fa4c669fb1e3e2756e4e07b6ee56c7d9fce05f35ccccc913aa0"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==1.5.1"
|
||||
},
|
||||
"docopt": {
|
||||
"hashes": [
|
||||
"sha256:49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491"
|
||||
],
|
||||
"version": "==0.6.2"
|
||||
},
|
||||
"factory-boy": {
|
||||
"hashes": [
|
||||
"sha256:6f25cc4761ac109efd503f096e2ad99421b1159f01a29dbb917359dcd68e08ca",
|
||||
"sha256:d552cb872b310ae78bd7429bf318e42e1e903b1a109e899a523293dfa762ea4f"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.11.1"
|
||||
},
|
||||
"faker": {
|
||||
"hashes": [
|
||||
"sha256:c61a41d0dab8865b850bd00454fb11e90f3fd2a092d8bc90120d1e1c01cff906",
|
||||
"sha256:f909ff9133ce0625ca388b6838190630ad7a593f87eaf058d872338a76241d5d"
|
||||
],
|
||||
"version": "==1.0.0"
|
||||
},
|
||||
"idna": {
|
||||
"hashes": [
|
||||
"sha256:156a6814fb5ac1fc6850fb002e0852d56c0c8d2531923a51032d1b70760e186e",
|
||||
"sha256:684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16"
|
||||
],
|
||||
"version": "==2.7"
|
||||
},
|
||||
"more-itertools": {
|
||||
"hashes": [
|
||||
"sha256:c187a73da93e7a8acc0001572aebc7e3c69daf7bf6881a2cea10650bd4420092",
|
||||
"sha256:c476b5d3a34e12d40130bc2f935028b5f636df8f372dc2c1c01dc19681b2039e",
|
||||
"sha256:fcbfeaea0be121980e15bc97b3817b5202ca73d0eae185b4550cbfce2a3ebb3d"
|
||||
],
|
||||
"version": "==4.3.0"
|
||||
},
|
||||
"pluggy": {
|
||||
"hashes": [
|
||||
"sha256:447ba94990e8014ee25ec853339faf7b0fc8050cdc3289d4d71f7f410fb90095",
|
||||
"sha256:bde19360a8ec4dfd8a20dcb811780a30998101f078fc7ded6162f0076f50508f"
|
||||
],
|
||||
"version": "==0.8.0"
|
||||
},
|
||||
"py": {
|
||||
"hashes": [
|
||||
"sha256:bf92637198836372b520efcba9e020c330123be8ce527e535d185ed4b6f45694",
|
||||
"sha256:e76826342cefe3c3d5f7e8ee4316b80d1dd8a300781612ddbc765c17ba25a6c6"
|
||||
],
|
||||
"version": "==1.7.0"
|
||||
},
|
||||
"pytest": {
|
||||
"hashes": [
|
||||
"sha256:3f193df1cfe1d1609d4c583838bea3d532b18d6160fd3f55c9447fdca30848ec",
|
||||
"sha256:e246cf173c01169b9617fc07264b7b1316e78d7a650055235d6d897bc80d9660"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==3.10.1"
|
||||
},
|
||||
"pytest-django": {
|
||||
"hashes": [
|
||||
"sha256:49e9ffc856bc6a1bec1c26c5c7b7213dff7cc8bc6b64d624c4d143d04aff0bcf",
|
||||
"sha256:b379282feaf89069cb790775ab6bbbd2bd2038a68c7ef9b84a41898e0b551081"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==3.4.3"
|
||||
},
|
||||
"python-dateutil": {
|
||||
"hashes": [
|
||||
"sha256:063df5763652e21de43de7d9e00ccf239f953a832941e37be541614732cdfc93",
|
||||
"sha256:88f9287c0174266bb0d8cedd395cfba9c58e87e5ad86b2ce58859bc11be3cf02"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.7.5"
|
||||
},
|
||||
"requests": {
|
||||
"hashes": [
|
||||
"sha256:99dcfdaaeb17caf6e526f32b6a7b780461512ab3f1d992187801694cba42770c",
|
||||
"sha256:a84b8c9ab6239b578f22d1c21d51b696dcfe004032bb80ea832398d6909d7279"
|
||||
],
|
||||
"index": "pypi",
|
||||
"version": "==2.20.0"
|
||||
},
|
||||
"six": {
|
||||
"hashes": [
|
||||
"sha256:70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9",
|
||||
"sha256:832dc0e10feb1aa2c68dcc57dbb658f1c7e65b9b61af69048abc87a2db00a0eb"
|
||||
],
|
||||
"version": "==1.11.0"
|
||||
},
|
||||
"text-unidecode": {
|
||||
"hashes": [
|
||||
"sha256:5a1375bb2ba7968740508ae38d92e1f889a0832913cb1c447d5e2046061a396d",
|
||||
"sha256:801e38bd550b943563660a91de8d4b6fa5df60a542be9093f7abf819f86050cc"
|
||||
],
|
||||
"version": "==1.2"
|
||||
},
|
||||
"urllib3": {
|
||||
"hashes": [
|
||||
"sha256:61bf29cada3fc2fbefad4fdf059ea4bd1b4a86d2b6d15e1c7c0b582b9752fe39",
|
||||
"sha256:de9529817c93f27c8ccbfead6985011db27bd0ddfcdb2d86f3f663385c6a9c22"
|
||||
],
|
||||
"version": "==1.24.1"
|
||||
}
|
||||
}
|
||||
}
|
104
README.md
104
README.md
|
@ -1,104 +0,0 @@
|
|||
# Taiga Backend #
|
||||
|
||||
[](https://github.com/kaleidos "Kaleidos Project")
|
||||
[](https://tree.taiga.io/project/taiga/ "Managed with Taiga.io")
|
||||
[](https://travis-ci.org/taigaio/taiga-back "Build Status")
|
||||
[](https://coveralls.io/r/taigaio/taiga-back?branch=master "Coverage Status")
|
||||
|
||||
|
||||
## Contribute to Taiga ##
|
||||
|
||||
#### Where to start ####
|
||||
|
||||
There are many different ways to contribute to Taiga's development, just find the one that best fits with your skills. Examples of contributions we would love to receive include:
|
||||
|
||||
- **Code patches**
|
||||
- **Documentation improvements**
|
||||
- **Translations**
|
||||
- **Bug reports**
|
||||
- **Patch reviews**
|
||||
- **UI enhancements**
|
||||
|
||||
Big features are also welcome but if you want to see your contributions included in Taiga codebase we strongly recommend you start by initiating a chat though our [mailing list](http://groups.google.co.uk/d/forum/taigaio)
|
||||
|
||||
|
||||
#### Code of Conduct ####
|
||||
|
||||
Help us keep the Taiga Community open and inclusive. Please read and follow our [Code of Conduct](https://github.com/taigaio/code-of-conduct/blob/master/CODE_OF_CONDUCT.md).
|
||||
|
||||
|
||||
#### License ####
|
||||
|
||||
Every code patch accepted in taiga codebase is licensed under [AGPL v3.0](http://www.gnu.org/licenses/agpl-3.0.html). You must be careful to not include any code that can not be licensed under this license.
|
||||
|
||||
Please read carefully [our license](https://github.com/taigaio/taiga-back/blob/master/LICENSE) and ask us if you have any questions as well as the [Contribution policy](https://github.com/taigaio/taiga-back/blob/master/CONTRIBUTING.md).
|
||||
|
||||
|
||||
#### Bug reports, enhancements and support ####
|
||||
|
||||
If you **need help to setup Taiga**, want to **talk about some cool enhancemnt** or you have **some questions**, please write us to our [mailing list](http://groups.google.com/d/forum/taigaio).
|
||||
|
||||
If you **find a bug** in Taiga you can always report it:
|
||||
|
||||
- in our [mailing list](http://groups.google.com/d/forum/taigaio).
|
||||
- in [github issues](https://github.com/taigaio/taiga-back/issues).
|
||||
- send us a mail to support@taiga.io if is a bug related to [tree.taiga.io](https://tree.taiga.io).
|
||||
- send a mail to security@taiga.io if is a **security bug**.
|
||||
|
||||
One of our fellow Taiga developers will search, find and hunt it as soon as possible.
|
||||
|
||||
Please, before reporting a bug write down how can we reproduce it, your operating system, your browser and version, and if it's possible, a screenshot. Sometimes it takes less time to fix a bug if the developer knows how to find it and we will solve your problem as fast as possible.
|
||||
|
||||
|
||||
#### Documentation improvements ####
|
||||
|
||||
We are gathering lots of information from our users to build and enhance our documentation. If you use the documentation to install or develop with Taiga and find any mistakes, omissions or confused sequences, it is enormously helpful to report it. Or better still, if you believe you can author additions, please make a pull-request to taiga project.
|
||||
|
||||
Currently, we have authored three main documentation hubs:
|
||||
|
||||
- **[API Docs](https://github.com/taigaio/taiga-doc)**: Our API documentation and reference for developing from Taiga API.
|
||||
- **[Installation Guide](https://github.com/taigaio/taiga-doc)**: If you need to install Taiga on your own server, this is the place to find some guides.
|
||||
- **[Taiga Support](https://github.com/taigaio/taiga-doc)**: This page is intended to be the support reference page for the users. If you find any mistake, please report it.
|
||||
|
||||
|
||||
#### Translation ####
|
||||
|
||||
We are ready now to accept your help translating Taiga. It's easy (and fun!) just access our team of translators with the link below, set up an account in Transifex and start contributing. Join us to make sure your language is covered! **[Help Taiga to translate content](https://www.transifex.com/taiga-agile-llc/taiga-back/ "Help Taiga to trasnlatecontent")**
|
||||
|
||||
|
||||
#### Code patches ####
|
||||
|
||||
Taiga will always be glad to receive code patches to update, fix or improve its code.
|
||||
|
||||
If you know how to improve our code base or you found a bug, a security vulnerability or a performance issue and you think you can solve it, we will be very happy to accept your pull-request. If your code requires considerable changes, we recommend you first talk to us directly. We will find the best way to help.
|
||||
|
||||
|
||||
#### UI enhancements ####
|
||||
|
||||
Taiga is made for developers and designers. We care enormously about UI because usability and design are both critical aspects of the Taiga experience.
|
||||
|
||||
There are two possible ways to contribute to our UI:
|
||||
- **Bugs**: If you find a bug regarding front-end, please report it as previously indicated in the Bug reports section or send a pull-request as indicated in the Code Patches section.
|
||||
- **Enhancements**: If its a design or UX bug or enhancement we will love to receive your feedback. Please send us your enhancement, with the reason and, if possible, an example. Our design and UX team will review your enhancement and fix it as soon as possible. We recommend you to use our [mailing list](http://groups.google.co.uk/d/forum/taigaio) so we can have a lot of different opinions and debate.
|
||||
- **Language Localization**: We are eager to offer localized versions of Taiga. Some members of the community have already volunteered to work to provide a variety of languages. We are working to implement some changes to allow for this and expect to accept these requests in the near future.
|
||||
|
||||
|
||||
|
||||
## Setup development environment ##
|
||||
|
||||
Just execute these commands in your virtualenv(wrapper):
|
||||
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
python manage.py migrate --noinput
|
||||
python manage.py loaddata initial_user
|
||||
python manage.py loaddata initial_project_templates
|
||||
python manage.py sample_data
|
||||
```
|
||||
|
||||
**IMPORTANT: Taiga only runs with python 3.5+**
|
||||
|
||||
Initial auth data: admin/123123
|
||||
|
||||
If you want a complete environment for production usage, you can try the taiga bootstrapping
|
||||
scripts https://github.com/taigaio/taiga-scripts (warning: alpha state). All the information about the different installation methods (production, development, vagrant, docker...) can be found here http://taigaio.github.io/taiga-doc/dist/#_installation_guide.
|
|
@ -0,0 +1,42 @@
|
|||
Taiga Backend
|
||||
=================
|
||||
|
||||
.. image:: http://kaleidos.net/static/img/badge.png
|
||||
:target: http://kaleidos.net/community/taiga/
|
||||
|
||||
.. image:: https://travis-ci.org/taigaio/taiga-back.png?branch=master
|
||||
:target: https://travis-ci.org/taigaio/taiga-back
|
||||
|
||||
.. image:: https://coveralls.io/repos/taigaio/taiga-back/badge.png?branch=master
|
||||
:target: https://coveralls.io/r/taigaio/taiga-back?branch=master
|
||||
|
||||
|
||||
|
||||
Setup development environment
|
||||
-----------------------------
|
||||
|
||||
Just execute these commands in your virtualenv(wrapper):
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
pip install -r requirements.txt
|
||||
python manage.py migrate --noinput
|
||||
python manage.py loaddata initial_user
|
||||
python manage.py loaddata initial_project_templates
|
||||
python manage.py loaddata initial_role
|
||||
python manage.py sample_data
|
||||
|
||||
|
||||
Note: taiga only runs with python 3.3+.
|
||||
|
||||
Note: Initial auth data: admin/123123
|
||||
|
||||
|
||||
Polyfills
|
||||
---------
|
||||
|
||||
Django-Rest Framework by default returns 403 for not authenticated requests and permission denied
|
||||
requests. The file ``taiga/base/monkey.py`` contains a temporary fix for this bug.
|
||||
|
||||
This patch is applied when the module ``base.models`` it's loaded. Once it's solved on django rest
|
||||
framework, this patch can be removed.
|
|
@ -0,0 +1 @@
|
|||
build
|
|
@ -0,0 +1,153 @@
|
|||
# Makefile for Sphinx documentation
|
||||
#
|
||||
|
||||
# You can set these variables from the command line.
|
||||
SPHINXOPTS =
|
||||
SPHINXBUILD = sphinx-build
|
||||
PAPER =
|
||||
BUILDDIR = build
|
||||
|
||||
# Internal variables.
|
||||
PAPEROPT_a4 = -D latex_paper_size=a4
|
||||
PAPEROPT_letter = -D latex_paper_size=letter
|
||||
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
|
||||
# the i18n builder cannot share the environment and doctrees with the others
|
||||
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
|
||||
|
||||
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
|
||||
|
||||
help:
|
||||
@echo "Please use \`make <target>' where <target> is one of"
|
||||
@echo " html to make standalone HTML files"
|
||||
@echo " dirhtml to make HTML files named index.html in directories"
|
||||
@echo " singlehtml to make a single large HTML file"
|
||||
@echo " pickle to make pickle files"
|
||||
@echo " json to make JSON files"
|
||||
@echo " htmlhelp to make HTML files and a HTML help project"
|
||||
@echo " qthelp to make HTML files and a qthelp project"
|
||||
@echo " devhelp to make HTML files and a Devhelp project"
|
||||
@echo " epub to make an epub"
|
||||
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
|
||||
@echo " latexpdf to make LaTeX files and run them through pdflatex"
|
||||
@echo " text to make text files"
|
||||
@echo " man to make manual pages"
|
||||
@echo " texinfo to make Texinfo files"
|
||||
@echo " info to make Texinfo files and run them through makeinfo"
|
||||
@echo " gettext to make PO message catalogs"
|
||||
@echo " changes to make an overview of all changed/added/deprecated items"
|
||||
@echo " linkcheck to check all external links for integrity"
|
||||
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
|
||||
|
||||
clean:
|
||||
-rm -rf $(BUILDDIR)/*
|
||||
|
||||
html:
|
||||
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
|
||||
|
||||
dirhtml:
|
||||
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
|
||||
|
||||
singlehtml:
|
||||
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
|
||||
@echo
|
||||
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
|
||||
|
||||
pickle:
|
||||
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
|
||||
@echo
|
||||
@echo "Build finished; now you can process the pickle files."
|
||||
|
||||
json:
|
||||
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
|
||||
@echo
|
||||
@echo "Build finished; now you can process the JSON files."
|
||||
|
||||
htmlhelp:
|
||||
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run HTML Help Workshop with the" \
|
||||
".hhp project file in $(BUILDDIR)/htmlhelp."
|
||||
|
||||
qthelp:
|
||||
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
|
||||
@echo
|
||||
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
|
||||
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
|
||||
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Green-Mine.qhcp"
|
||||
@echo "To view the help file:"
|
||||
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Green-Mine.qhc"
|
||||
|
||||
devhelp:
|
||||
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
|
||||
@echo
|
||||
@echo "Build finished."
|
||||
@echo "To view the help file:"
|
||||
@echo "# mkdir -p $$HOME/.local/share/devhelp/Green-Mine"
|
||||
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Green-Mine"
|
||||
@echo "# devhelp"
|
||||
|
||||
epub:
|
||||
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
|
||||
@echo
|
||||
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
|
||||
|
||||
latex:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo
|
||||
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
|
||||
@echo "Run \`make' in that directory to run these through (pdf)latex" \
|
||||
"(use \`make latexpdf' here to do that automatically)."
|
||||
|
||||
latexpdf:
|
||||
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
|
||||
@echo "Running LaTeX files through pdflatex..."
|
||||
$(MAKE) -C $(BUILDDIR)/latex all-pdf
|
||||
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
|
||||
|
||||
text:
|
||||
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
|
||||
@echo
|
||||
@echo "Build finished. The text files are in $(BUILDDIR)/text."
|
||||
|
||||
man:
|
||||
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
|
||||
@echo
|
||||
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
|
||||
|
||||
texinfo:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo
|
||||
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
|
||||
@echo "Run \`make' in that directory to run these through makeinfo" \
|
||||
"(use \`make info' here to do that automatically)."
|
||||
|
||||
info:
|
||||
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
|
||||
@echo "Running Texinfo files through makeinfo..."
|
||||
make -C $(BUILDDIR)/texinfo info
|
||||
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
|
||||
|
||||
gettext:
|
||||
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
|
||||
@echo
|
||||
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
|
||||
|
||||
changes:
|
||||
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
|
||||
@echo
|
||||
@echo "The overview file is in $(BUILDDIR)/changes."
|
||||
|
||||
linkcheck:
|
||||
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
|
||||
@echo
|
||||
@echo "Link check complete; look for any errors in the above output " \
|
||||
"or in $(BUILDDIR)/linkcheck/output.txt."
|
||||
|
||||
doctest:
|
||||
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
|
||||
@echo "Testing of doctests in the sources finished, look at the " \
|
||||
"results in $(BUILDDIR)/doctest/output.txt."
|
|
@ -0,0 +1,39 @@
|
|||
{% extends "!layout.html" %}
|
||||
|
||||
{% block body %}
|
||||
<div class="deck">
|
||||
|
||||
{% if version == "0.7" or version == "0.8" %}
|
||||
<p class="developmentversion">
|
||||
This document is for Celery's development version, which can be
|
||||
significantly different from previous releases. Get old docs here:
|
||||
|
||||
<a href="http://docs.celeryproject.org/en/latest/{{ pagename }}{{ file_suffix }}">2.5</a>.
|
||||
</p>
|
||||
{% else %}
|
||||
<p>
|
||||
This document describes stdnet {{ version }}. For development docs,
|
||||
<a href="http://lsbardel.github.com/python-stdnet/{{ pagename }}{{ file_suffix }}">go here</a>.
|
||||
</p>
|
||||
{% endif %}
|
||||
|
||||
</div>
|
||||
{{ body }}
|
||||
{% endblock %}
|
||||
|
||||
{% block footer %}
|
||||
{{ super() }}
|
||||
<script type="text/javascript">
|
||||
|
||||
var _gaq = _gaq || [];
|
||||
_gaq.push(['_setAccount', 'UA-3900561-6']);
|
||||
_gaq.push(['_trackPageview']);
|
||||
|
||||
(function() {
|
||||
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
|
||||
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
|
||||
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
|
||||
})();
|
||||
|
||||
</script>
|
||||
{% endblock %}
|
|
@ -0,0 +1,9 @@
|
|||
<h3>Green-Mine</h3>
|
||||
<p>
|
||||
Green-Mine is a project managment web application
|
||||
build on top of django (1.4).
|
||||
</p>
|
||||
<h3>Useful Links</h3>
|
||||
<ul>
|
||||
<li><a href="https://github.com/lsbardel/python-stdnet">Green-Mine @ github</a></li>
|
||||
</ul>
|
|
@ -0,0 +1,5 @@
|
|||
<p class="logo">
|
||||
<a href="{{ pathto(master_doc) }}">
|
||||
<img class="logo" width="200" src="{{ pathto('_static/net.jpg', 1) }}" alt="Logo"/>
|
||||
</a>
|
||||
</p>
|
|
@ -0,0 +1,394 @@
|
|||
/*
|
||||
* celery.css_t
|
||||
* ~~~~~~~~~~~~
|
||||
*
|
||||
* :copyright: Copyright 2010 by Armin Ronacher.
|
||||
* :license: BSD, see LICENSE for details.
|
||||
*/
|
||||
|
||||
{% set page_width = 940 %}
|
||||
{% set sidebar_width = 220 %}
|
||||
{% set body_font_stack = 'Optima, Segoe, "Segoe UI", Candara, Calibri, Arial, sans-serif' %}
|
||||
{% set headline_font_stack = 'Futura, "Trebuchet MS", Arial, sans-serif' %}
|
||||
{% set code_font_stack = "'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace" %}
|
||||
|
||||
@import url("basic.css");
|
||||
|
||||
/* -- page layout ----------------------------------------------------------- */
|
||||
|
||||
body {
|
||||
font-family: {{ body_font_stack }};
|
||||
font-size: 17px;
|
||||
background-color: white;
|
||||
color: #000;
|
||||
margin: 30px 0 0 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
div.document {
|
||||
width: {{ page_width }}px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
div.related {
|
||||
width: {{ page_width - 20 }}px;
|
||||
padding: 5px 10px;
|
||||
background: #F2FCEE;
|
||||
margin: 15px auto 15px auto;
|
||||
}
|
||||
|
||||
div.documentwrapper {
|
||||
float: left;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
div.bodywrapper {
|
||||
margin: 0 0 0 {{ sidebar_width }}px;
|
||||
}
|
||||
|
||||
div.sphinxsidebar {
|
||||
width: {{ sidebar_width }}px;
|
||||
}
|
||||
|
||||
hr {
|
||||
border: 1px solid #B1B4B6;
|
||||
}
|
||||
|
||||
div.body {
|
||||
background-color: #ffffff;
|
||||
color: #3E4349;
|
||||
padding: 0 30px 0 30px;
|
||||
}
|
||||
|
||||
img.celerylogo {
|
||||
padding: 0 0 10px 10px;
|
||||
float: right;
|
||||
}
|
||||
|
||||
div.footer {
|
||||
width: {{ page_width - 15 }}px;
|
||||
margin: 10px auto 30px auto;
|
||||
padding-right: 15px;
|
||||
font-size: 14px;
|
||||
color: #888;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
div.footer a {
|
||||
color: #888;
|
||||
}
|
||||
|
||||
div.sphinxsidebar a {
|
||||
color: #444;
|
||||
text-decoration: none;
|
||||
border-bottom: 1px dashed #DCF0D5;
|
||||
}
|
||||
|
||||
div.sphinxsidebar a:hover {
|
||||
border-bottom: 1px solid #999;
|
||||
}
|
||||
|
||||
div.sphinxsidebar {
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
div.sphinxsidebarwrapper {
|
||||
padding: 7px 10px;
|
||||
}
|
||||
|
||||
div.sphinxsidebarwrapper p.logo {
|
||||
padding: 0 0 20px 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
div.sphinxsidebar h3,
|
||||
div.sphinxsidebar h4 {
|
||||
font-family: {{ headline_font_stack }};
|
||||
color: #444;
|
||||
font-size: 24px;
|
||||
font-weight: normal;
|
||||
margin: 0 0 5px 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
div.sphinxsidebar h4 {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
div.sphinxsidebar h3 a {
|
||||
color: #444;
|
||||
}
|
||||
|
||||
div.sphinxsidebar p.logo a,
|
||||
div.sphinxsidebar h3 a,
|
||||
div.sphinxsidebar p.logo a:hover,
|
||||
div.sphinxsidebar h3 a:hover {
|
||||
border: none;
|
||||
}
|
||||
|
||||
div.sphinxsidebar p {
|
||||
color: #555;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
div.sphinxsidebar ul {
|
||||
margin: 10px 0;
|
||||
padding: 0;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
div.sphinxsidebar input {
|
||||
border: 1px solid #ccc;
|
||||
font-family: {{ body_font_stack }};
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
/* -- body styles ----------------------------------------------------------- */
|
||||
|
||||
a {
|
||||
color: #348613;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #59B833;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
div.body h1,
|
||||
div.body h2,
|
||||
div.body h3,
|
||||
div.body h4,
|
||||
div.body h5,
|
||||
div.body h6 {
|
||||
font-family: {{ headline_font_stack }};
|
||||
font-weight: normal;
|
||||
margin: 30px 0px 10px 0px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
div.body h1 { margin-top: 0; padding-top: 0; font-size: 200%; }
|
||||
div.body h2 { font-size: 180%; }
|
||||
div.body h3 { font-size: 150%; }
|
||||
div.body h4 { font-size: 130%; }
|
||||
div.body h5 { font-size: 100%; }
|
||||
div.body h6 { font-size: 100%; }
|
||||
|
||||
div.body h1 a.toc-backref,
|
||||
div.body h2 a.toc-backref,
|
||||
div.body h3 a.toc-backref,
|
||||
div.body h4 a.toc-backref,
|
||||
div.body h5 a.toc-backref,
|
||||
div.body h6 a.toc-backref {
|
||||
color: inherit!important;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a.headerlink {
|
||||
color: #ddd;
|
||||
padding: 0 4px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a.headerlink:hover {
|
||||
color: #444;
|
||||
background: #eaeaea;
|
||||
}
|
||||
|
||||
div.body p, div.body dd, div.body li {
|
||||
line-height: 1.4em;
|
||||
}
|
||||
|
||||
div.admonition {
|
||||
background: #fafafa;
|
||||
margin: 20px -30px;
|
||||
padding: 10px 30px;
|
||||
border-top: 1px solid #ccc;
|
||||
border-bottom: 1px solid #ccc;
|
||||
}
|
||||
|
||||
div.admonition p.admonition-title {
|
||||
font-family: {{ headline_font_stack }};
|
||||
font-weight: normal;
|
||||
font-size: 24px;
|
||||
margin: 0 0 10px 0;
|
||||
padding: 0;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
div.admonition p.last {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
div.highlight{
|
||||
background-color: white;
|
||||
}
|
||||
|
||||
dt:target, .highlight {
|
||||
background: #FAF3E8;
|
||||
}
|
||||
|
||||
div.note {
|
||||
background-color: #eee;
|
||||
border: 1px solid #ccc;
|
||||
}
|
||||
|
||||
div.seealso {
|
||||
background-color: #ffc;
|
||||
border: 1px solid #ff6;
|
||||
}
|
||||
|
||||
div.topic {
|
||||
background-color: #eee;
|
||||
}
|
||||
|
||||
div.warning {
|
||||
background-color: #ffe4e4;
|
||||
border: 1px solid #f66;
|
||||
}
|
||||
|
||||
p.admonition-title {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
p.admonition-title:after {
|
||||
content: ":";
|
||||
}
|
||||
|
||||
pre, tt {
|
||||
font-family: {{ code_font_stack }};
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
img.screenshot {
|
||||
}
|
||||
|
||||
tt.descname, tt.descclassname {
|
||||
font-size: 0.95em;
|
||||
}
|
||||
|
||||
tt.descname {
|
||||
padding-right: 0.08em;
|
||||
}
|
||||
|
||||
img.screenshot {
|
||||
-moz-box-shadow: 2px 2px 4px #eee;
|
||||
-webkit-box-shadow: 2px 2px 4px #eee;
|
||||
box-shadow: 2px 2px 4px #eee;
|
||||
}
|
||||
|
||||
table.docutils {
|
||||
border: 1px solid #888;
|
||||
-moz-box-shadow: 2px 2px 4px #eee;
|
||||
-webkit-box-shadow: 2px 2px 4px #eee;
|
||||
box-shadow: 2px 2px 4px #eee;
|
||||
}
|
||||
|
||||
table.docutils td, table.docutils th {
|
||||
border: 1px solid #888;
|
||||
padding: 0.25em 0.7em;
|
||||
}
|
||||
|
||||
table.field-list, table.footnote {
|
||||
border: none;
|
||||
-moz-box-shadow: none;
|
||||
-webkit-box-shadow: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
table.footnote {
|
||||
margin: 15px 0;
|
||||
width: 100%;
|
||||
border: 1px solid #eee;
|
||||
background: #fdfdfd;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
table.footnote + table.footnote {
|
||||
margin-top: -15px;
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
table.field-list th {
|
||||
padding: 0 0.8em 0 0;
|
||||
}
|
||||
|
||||
table.field-list td {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
table.footnote td.label {
|
||||
width: 0px;
|
||||
padding: 0.3em 0 0.3em 0.5em;
|
||||
}
|
||||
|
||||
table.footnote td {
|
||||
padding: 0.3em 0.5em;
|
||||
}
|
||||
|
||||
dl {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
dl dd {
|
||||
margin-left: 30px;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
margin: 0 0 0 30px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
ul {
|
||||
margin: 10px 0 10px 30px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
pre {
|
||||
background: #F0FFEB;
|
||||
padding: 7px 10px;
|
||||
margin: 15px 0;
|
||||
border: 1px solid #C7ECB8;
|
||||
border-radius: 2px;
|
||||
-moz-border-radius: 2px;
|
||||
-webkit-border-radius: 2px;
|
||||
line-height: 1.3em;
|
||||
}
|
||||
|
||||
tt {
|
||||
background: #F0FFEB;
|
||||
color: #222;
|
||||
/* padding: 1px 2px; */
|
||||
}
|
||||
|
||||
tt.xref, a tt {
|
||||
background: #F0FFEB;
|
||||
border-bottom: 1px solid white;
|
||||
}
|
||||
|
||||
a.reference {
|
||||
text-decoration: none;
|
||||
border-bottom: 1px dashed #DCF0D5;
|
||||
}
|
||||
|
||||
a.reference:hover {
|
||||
border-bottom: 1px solid #6D4100;
|
||||
}
|
||||
|
||||
a.footnote-reference {
|
||||
text-decoration: none;
|
||||
font-size: 0.7em;
|
||||
vertical-align: top;
|
||||
border-bottom: 1px dashed #DCF0D5;
|
||||
}
|
||||
|
||||
a.footnote-reference:hover {
|
||||
border-bottom: 1px solid #6D4100;
|
||||
}
|
||||
|
||||
a:hover tt {
|
||||
background: #EEE;
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
[theme]
|
||||
inherit = basic
|
||||
stylesheet = celery.css
|
||||
|
||||
[options]
|
|
@ -0,0 +1,57 @@
|
|||
|
||||
============
|
||||
Coding rules
|
||||
============
|
||||
|
||||
Django models
|
||||
=============
|
||||
|
||||
* All model names in singular an CamelCase.
|
||||
|
||||
* All models have a **Meta** with at least:
|
||||
|
||||
- **verbose_name** and **verbose_name_plural**: unicode strings, lowercase, with spaces.
|
||||
- **ordering**: return a consistent order, using pk if no other unique field or combination exists.
|
||||
|
||||
* All models have **__unicode__** method, returning a human-readable, descriptive, short text.
|
||||
|
||||
* All fields have **verbose_name**. Also **help_text** if needed to fully explain the field meaning.
|
||||
|
||||
* All fields have explicit **blank** and **null** parameters. Use only those combinations, unless
|
||||
there a documented need of other thing:
|
||||
|
||||
Normal fields (IntegerField, DateField, ForeignKey, FileField...)
|
||||
- (optional) **null = True**, **blank = True**
|
||||
- (required) **null = False**, **blank = False**
|
||||
|
||||
Text fields (CharField, TextField, URLField...)
|
||||
- (optional) **null = False**, **blank = True**
|
||||
- (required) **null = False**, **blank = False**
|
||||
|
||||
Boolean fields:
|
||||
- (two values, T/F) **null = False**, **blank = True**
|
||||
- (three values, T/F/Null) **null = False**, **blank = True**
|
||||
|
||||
* Don't create text fields with **null = True**, unless you need to distinguish between empty string and None.
|
||||
|
||||
* Don't create boolean fields with **blank = False**, otherwise they could only be True.
|
||||
|
||||
Example::
|
||||
|
||||
class SomeClass(models.Model):
|
||||
name = models.CharField(max_length=100, null = False, blank = False, unique=True,
|
||||
verbose_name = _(u'name'))
|
||||
slug = models.SlugField(max_length=100, null = False, blank = False, unique=True,
|
||||
verbose_name = _(u'slug'),
|
||||
help_text = (u'Identifier of this object. Only letters, digits and underscore "_" allowed.'))
|
||||
text = models.TextField(null = False, blank = True,
|
||||
verbose_name = _(u'text'))
|
||||
|
||||
class Meta:
|
||||
verbose_name = _(u'some class')
|
||||
verbose_name_plural = _(u'some classes')
|
||||
ordering = ['name']
|
||||
|
||||
def __unicode__(self):
|
||||
return self.name
|
||||
|
|
@ -0,0 +1,255 @@
|
|||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import sys, os
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#sys.path.insert(0, os.path.abspath('.'))
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = []
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.rst'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'taiga'
|
||||
copyright = u'2012, Andrei Antoukh'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '0.0.10'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '0.0.10'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
#language = None
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = []
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'default'
|
||||
html_theme = 'celery'
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
#html_theme_path = []
|
||||
html_theme_path = ["_theme"]
|
||||
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
#html_title = None
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = ['_static']
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
#html_sidebars = {}
|
||||
html_sidebars = {
|
||||
'index': ['sidebarlogo.html', 'sidebarintro.html',
|
||||
'sourcelink.html', 'searchbox.html'],
|
||||
'**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',
|
||||
'sourcelink.html', 'searchbox.html'],
|
||||
}
|
||||
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = None
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
htmlhelp_basename = 'taigadoc'
|
||||
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
latex_elements = {
|
||||
# The paper size ('letterpaper' or 'a4paper').
|
||||
#'papersize': 'letterpaper',
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#'pointsize': '10pt',
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#'preamble': '',
|
||||
}
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
latex_documents = [
|
||||
('index', 'taiga.tex', u'taiga documentation',
|
||||
u'Andrei Antoukh', 'manual'),
|
||||
]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
|
||||
# -- Options for manual page output --------------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
man_pages = [
|
||||
('index', 'green-mine', u'taiga documentation',
|
||||
[u'Andrei Antoukh'], 1)
|
||||
]
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#man_show_urls = False
|
||||
|
||||
|
||||
# -- Options for Texinfo output ------------------------------------------------
|
||||
|
||||
# Grouping the document tree into Texinfo files. List of tuples
|
||||
# (source start file, target name, title, author,
|
||||
# dir menu entry, description, category)
|
||||
texinfo_documents = [
|
||||
('index', 'taiga', u'taiga documentation',
|
||||
u'Andrei Antoukh', 'taiga', 'One line description of project.',
|
||||
'Miscellaneous'),
|
||||
]
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#texinfo_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#texinfo_domain_indices = True
|
||||
|
||||
# How to display URL addresses: 'footnote', 'no', or 'inline'.
|
||||
#texinfo_show_urls = 'footnote'
|
|
@ -0,0 +1,43 @@
|
|||
==========
|
||||
Green-Mine
|
||||
==========
|
||||
|
||||
.. rubric:: Project management web application build on top of Django.
|
||||
|
||||
Currently there is no stable version, but the project is already usable. All contributions and bug fixes is welcome.
|
||||
|
||||
|
||||
First steps
|
||||
===========
|
||||
|
||||
**From scratch:**
|
||||
:ref:`Overview and Installation <intro-overview>`
|
||||
|
||||
**Tutorials:** TODO
|
||||
|
||||
**Miscellaneous:**
|
||||
:ref:`Contributing <contributing>` |
|
||||
:ref:`Tests <runtests>` |
|
||||
:ref:`Changelog <changelog>` |
|
||||
:ref:`License <license>`
|
||||
|
||||
|
||||
Contents:
|
||||
=========
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
overview.rst
|
||||
settings.rst
|
||||
coding_rules.rst
|
||||
|
||||
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
* :ref:`genindex`
|
||||
* :ref:`modindex`
|
||||
* :ref:`search`
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
.. _intro-overview:
|
||||
|
||||
========
|
||||
Overview
|
||||
========
|
||||
|
||||
Requirements
|
||||
============
|
||||
|
||||
* python 2.6 or 2.7
|
||||
* django-superview >= 0.2
|
||||
* psycopg2 >= 2.4 (if postgresql is used)
|
||||
* pyzmq >= 2.2 (for async mailserver)
|
||||
* sphinx >= 1.1.3 (for build this documentation)
|
||||
* django >= 1.4 (builtin)
|
||||
* markdown >= 2.1 (for markdown wiki)
|
||||
* docutils >= 0.7 (for restructuredtext wiki)
|
||||
|
||||
Philosophy
|
||||
==========
|
||||
|
||||
TODO
|
||||
|
||||
Installing
|
||||
==========
|
||||
|
||||
TODO
|
||||
|
||||
Version Check
|
||||
=============
|
||||
|
||||
TODO
|
||||
|
||||
.. _runtests:
|
||||
|
||||
Running tests
|
||||
=============
|
||||
|
||||
Requirements for running tests: same as standard requierements.
|
||||
|
||||
To run tests, open a shell on a package directory and type::
|
||||
|
||||
python manage.py test -v2 taiga
|
||||
|
||||
To access coverage of tests you need to install the coverage_ package and run the tests using::
|
||||
|
||||
coverage run --omit=extern manage.py test -v2 taiga
|
||||
|
||||
and to check out the coverage report::
|
||||
|
||||
coverage html
|
||||
|
||||
|
||||
.. _contributing:
|
||||
|
||||
Contributing
|
||||
============
|
||||
|
||||
Develpment of Green-Mine happens at github: https://github.com/niwibe/Green-Mine
|
||||
|
||||
We very much welcome your contribution of course. To do so, simply follow these guidelines:
|
||||
|
||||
1. Fork ``taiga`` on github.
|
||||
2. Create feature branch. Example: ``git checkout -b my_new_feature``
|
||||
3. Push your changes. Example: ``git push -u origin my_new_feature``
|
||||
4. Send me a pull-request.
|
||||
|
||||
.. _license:
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
This software is licensed under the `GNU Affero General Public License`_, Version
|
||||
3. See the LICENSE file in the top distribution directory for the full license
|
||||
text.
|
||||
|
||||
.. _coverage: http://nedbatchelder.com/code/coverage/
|
||||
.. _`GNU Affero General Public License`: http://www.gnu.org/licenses/agpl.html
|
|
@ -0,0 +1,22 @@
|
|||
Settings introduced by taiga.
|
||||
=============================
|
||||
|
||||
Default settings
|
||||
----------------
|
||||
|
||||
The setting instance contains few default parameters used in throughout
|
||||
the library. This parameters can be changed by the user by simply
|
||||
overriding them.
|
||||
|
||||
.. attribute:: settings.HOST
|
||||
|
||||
Set a full host name, this is used for making urls for email
|
||||
notifications. In the future, it will be automatic.
|
||||
|
||||
Default: ``"http://localhost:8000"`` (ready for developers)
|
||||
|
||||
.. attribute:: settings.DISABLE_REGISTRATION
|
||||
|
||||
Set this, disables user registration.
|
||||
|
||||
Default: ``False``
|
19
manage.py
19
manage.py
|
@ -1,23 +1,4 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
|
|
@ -1,6 +1,3 @@
|
|||
[pytest]
|
||||
DJANGO_SETTINGS_MODULE = settings.testing
|
||||
filterwarnings =
|
||||
once
|
||||
ignore::django.utils.deprecation.RemovedInDjango20Warning
|
||||
ignore::DeprecationWarning:taiga.base.api.serializers
|
||||
python_paths = .
|
|
@ -1,37 +1,20 @@
|
|||
#!/bin/bash
|
||||
|
||||
show_answer=true
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
-y)
|
||||
show_answer=false
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
if $show_answer ; then
|
||||
echo "WARNING!! This script REMOVE your Taiga's database and you LOSE all the data."
|
||||
read -p "Are you sure you want to delete all data? (Press Y to continue): " -n 1 -r
|
||||
echo # (optional) move to a new line
|
||||
if [[ ! $REPLY =~ ^[Yy]$ ]] ; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
# For postgresql
|
||||
echo "-> Remove taiga DB"
|
||||
dropdb taiga
|
||||
echo "-> Create taiga DB"
|
||||
createdb taiga
|
||||
|
||||
echo "-> Load migrations"
|
||||
echo "-> Run syncdb"
|
||||
python manage.py migrate
|
||||
echo "-> Load initial user (admin/123123)"
|
||||
# echo "-> Load initial Site"
|
||||
# python manage.py loaddata initial_site --traceback
|
||||
echo "-> Load initial user"
|
||||
python manage.py loaddata initial_user --traceback
|
||||
echo "-> Load initial project_templates (scrum/kanban)"
|
||||
echo "-> Load initial project_templates"
|
||||
python manage.py loaddata initial_project_templates --traceback
|
||||
echo "-> Load initial roles"
|
||||
python manage.py loaddata initial_role --traceback
|
||||
echo "-> Generate sample data"
|
||||
python manage.py sample_data --traceback
|
||||
echo "-> Rebuilding timeline"
|
||||
python manage.py rebuild_timeline --purge
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
-r requirements.txt
|
||||
|
||||
factory_boy==2.4.1
|
||||
py==1.4.23
|
||||
pytest==2.6.1
|
||||
pytest-django==2.6.2
|
||||
pytest-pythonpath==0.3
|
||||
|
||||
coverage==3.7.1
|
||||
coveralls==0.4.2
|
||||
django-slowdown==0.0.1
|
|
@ -1,63 +1,26 @@
|
|||
-i https://pypi.org/simple
|
||||
amqp==2.3.2
|
||||
asana==0.6.7
|
||||
asn1crypto==0.24.0
|
||||
billiard==3.5.0.5
|
||||
bleach==2.1.4
|
||||
cairocffi==0.9.0
|
||||
cairosvg==2.0.3
|
||||
celery==4.0.2
|
||||
certifi==2018.11.29
|
||||
cffi==1.11.5
|
||||
chardet==3.0.4
|
||||
contextlib2==0.5.5
|
||||
cryptography==2.3.1
|
||||
cssselect==1.0.3
|
||||
cssutils==1.0.2
|
||||
djangorestframework==2.3.13
|
||||
Django==1.7
|
||||
django-picklefield==0.3.1
|
||||
django-sampledatahelper==0.2.2
|
||||
gunicorn==18.0
|
||||
psycopg2==2.5.4
|
||||
pillow==2.5.3
|
||||
pytz==2014.4
|
||||
six==1.8.0
|
||||
djmail==0.9
|
||||
django-pgjson==0.2.0
|
||||
djorm-pgarray==1.0.4
|
||||
django-jinja==1.0.4
|
||||
jinja2==2.7.2
|
||||
pygments==1.6
|
||||
django-sites==0.8
|
||||
Markdown==2.4.1
|
||||
fn==0.2.13
|
||||
diff-match-patch==20121119
|
||||
django-ipware==1.1.6
|
||||
django-jinja==2.3.1
|
||||
django-pglocks==1.0.2
|
||||
django-picklefield==0.3.2
|
||||
django-sampledatahelper==0.4.1
|
||||
django-sites==0.9
|
||||
django-sr==0.0.4
|
||||
django==1.11.16
|
||||
djmail==1.0.1
|
||||
docopt==0.6.2
|
||||
easy-thumbnails==2.4.1
|
||||
fn==0.4.3
|
||||
gunicorn==19.7.1
|
||||
html5lib==1.0.1
|
||||
idna==2.7
|
||||
jinja2==2.10
|
||||
kombu==4.0.2
|
||||
lxml==4.2.5
|
||||
markdown==3.0.1
|
||||
markupsafe==1.1.0
|
||||
netaddr==0.7.19
|
||||
oauthlib==2.1.0
|
||||
olefile==0.46
|
||||
pillow==4.1.1
|
||||
premailer==3.0.1
|
||||
psd-tools==1.4
|
||||
psycopg2-binary==2.7.5
|
||||
pycparser==2.19
|
||||
pygments==2.2.0
|
||||
pyjwt==1.7.0
|
||||
python-dateutil==2.7.5
|
||||
python-magic==0.4.13
|
||||
pytz==2018.7
|
||||
raven==6.1.0
|
||||
redis==2.10.5
|
||||
requests-oauthlib==0.8.0
|
||||
requests==2.20.0
|
||||
sampledata==0.3.7
|
||||
serpy==0.1.1
|
||||
six==1.11.0
|
||||
tinycss==0.4
|
||||
unidecode==0.4.20
|
||||
urllib3==1.24.1
|
||||
vine==1.1.4
|
||||
webcolors==1.7
|
||||
webencodings==0.5.1
|
||||
requests==2.4.1
|
||||
|
||||
# Comment it if you are using python >= 3.4
|
||||
enum34==1.0
|
||||
easy-thumbnails==2.1
|
||||
celery==3.1.12
|
||||
redis==2.10.3
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
python ./manage.py dumpdata --format json \
|
||||
--indent 4 \
|
||||
--output './taiga/projects/fixtures/initial_project_templates.json' \
|
||||
'projects.ProjectTemplate'
|
|
@ -1,280 +0,0 @@
|
|||
#!/usr/bin/env python
|
||||
#
|
||||
# NOTE: This script is based on django's manage_translations.py script
|
||||
# (https://github.com/django/django/blob/master/scripts/manage_translations.py)
|
||||
#
|
||||
# This python file contains utility scripts to manage taiga translations.
|
||||
# It has to be run inside the taiga-back git root directory.
|
||||
#
|
||||
# The following commands are available:
|
||||
#
|
||||
# * update_catalogs: check for new strings in taiga-back catalogs, and
|
||||
# output how much strings are new/changed.
|
||||
#
|
||||
# * lang_stats: output statistics for each catalog/language combination
|
||||
#
|
||||
# * fetch: fetch translations from transifex.com
|
||||
#
|
||||
# * commit: update resources in transifex.com with the local files
|
||||
#
|
||||
# Each command support the --languages and --resources options to limit their
|
||||
# operation to the specified language or resource. For example, to get stats
|
||||
# for Spanish in contrib.admin, run:
|
||||
#
|
||||
# $ python scripts/manage_translations.py lang_stats --language=es --resources=taiga
|
||||
|
||||
|
||||
import os
|
||||
from argparse import ArgumentParser
|
||||
from argparse import RawTextHelpFormatter
|
||||
|
||||
from subprocess import PIPE, Popen, call
|
||||
|
||||
from django_jinja.management.commands import makemessages
|
||||
|
||||
|
||||
def _get_locale_dirs(resources):
|
||||
"""
|
||||
Return a tuple (app name, absolute path) for all locale directories.
|
||||
If resources list is not None, filter directories matching resources content.
|
||||
"""
|
||||
contrib_dir = os.getcwd()
|
||||
dirs = []
|
||||
|
||||
# Collect all locale directories
|
||||
for contrib_name in os.listdir(contrib_dir):
|
||||
path = os.path.join(contrib_dir, contrib_name, "locale")
|
||||
if os.path.isdir(path):
|
||||
dirs.append((contrib_name, path))
|
||||
|
||||
# Filter by resources, if any
|
||||
if resources is not None:
|
||||
res_names = [d[0] for d in dirs]
|
||||
dirs = [ld for ld in dirs if ld[0] in resources]
|
||||
if len(resources) > len(dirs):
|
||||
print("You have specified some unknown resources. "
|
||||
"Available resource names are: {0}".format(", ".join(res_names)))
|
||||
exit(1)
|
||||
|
||||
return dirs
|
||||
|
||||
|
||||
def _tx_resource_for_name(name):
|
||||
""" Return the Transifex resource name """
|
||||
return "taiga-back.{}".format(name)
|
||||
|
||||
|
||||
def _check_diff(cat_name, base_path):
|
||||
"""
|
||||
Output the approximate number of changed/added strings in the en catalog.
|
||||
"""
|
||||
po_path = "{path}/en/LC_MESSAGES/django.po".format(path=base_path)
|
||||
p = Popen("git diff -U0 {0} | egrep '^[-+]msgid' | wc -l".format(po_path),
|
||||
stdout=PIPE, stderr=PIPE, shell=True)
|
||||
output, errors = p.communicate()
|
||||
num_changes = int(output.strip())
|
||||
print("{0} changed/added messages in '{1}' catalog.".format(num_changes, cat_name))
|
||||
|
||||
|
||||
def update_catalogs(resources=None, languages=None):
|
||||
"""
|
||||
Update the en/LC_MESSAGES/django.po (all) files with
|
||||
new/updated translatable strings.
|
||||
"""
|
||||
cmd = makemessages.Command()
|
||||
opts = {
|
||||
"locale": ["en"],
|
||||
"exclude": [],
|
||||
"extensions": ["py", "jinja"],
|
||||
|
||||
# Default values
|
||||
"domain": "django",
|
||||
"all": False,
|
||||
"symlinks": False,
|
||||
"ignore_patterns": [],
|
||||
"use_default_ignore_patterns": True,
|
||||
"no_wrap": False,
|
||||
"no_location": False,
|
||||
"no_obsolete": False,
|
||||
"keep_pot": False,
|
||||
"verbosity": 0,
|
||||
}
|
||||
|
||||
if resources is not None:
|
||||
print("`update_catalogs` will always process all resources.")
|
||||
|
||||
os.chdir(os.getcwd())
|
||||
print("Updating en catalogs for all taiga-back resourcess...")
|
||||
cmd.handle(**opts)
|
||||
|
||||
# Output changed stats
|
||||
contrib_dirs = _get_locale_dirs(None)
|
||||
for name, dir_ in contrib_dirs:
|
||||
_check_diff(name, dir_)
|
||||
|
||||
|
||||
def lang_stats(resources=None, languages=None):
|
||||
"""
|
||||
Output language statistics of committed translation files for each catalog.
|
||||
If resources is provided, it should be a list of translation resource to
|
||||
limit the output (e.g. ['main', 'taiga']).
|
||||
"""
|
||||
locale_dirs = _get_locale_dirs(resources)
|
||||
|
||||
for name, dir_ in locale_dirs:
|
||||
print("\nShowing translations stats for '{res}':".format(res=name))
|
||||
|
||||
langs = []
|
||||
for d in os.listdir(dir_):
|
||||
if not d.startswith('_') and os.path.isdir(os.path.join(dir_, d)):
|
||||
langs.append(d)
|
||||
langs = sorted(langs)
|
||||
|
||||
for lang in langs:
|
||||
if languages and lang not in languages:
|
||||
continue
|
||||
|
||||
# TODO: merge first with the latest en catalog
|
||||
p = Popen("msgfmt -vc -o /dev/null {path}/{lang}/LC_MESSAGES/django.po".format(path=dir_, lang=lang),
|
||||
stdout=PIPE, stderr=PIPE, shell=True)
|
||||
output, errors = p.communicate()
|
||||
|
||||
if p.returncode == 0:
|
||||
# msgfmt output stats on stderr
|
||||
print("{0}: {1}".format(lang, errors.strip().decode("utf-8")))
|
||||
else:
|
||||
print("Errors happened when checking {0} translation for {1}:\n{2}".format(lang, name, errors))
|
||||
|
||||
|
||||
def fetch(resources=None, languages=None):
|
||||
"""
|
||||
Fetch translations from Transifex, wrap long lines, generate mo files.
|
||||
"""
|
||||
locale_dirs = _get_locale_dirs(resources)
|
||||
errors = []
|
||||
|
||||
for name, dir_ in locale_dirs:
|
||||
# Transifex pull
|
||||
if languages is None:
|
||||
call("tx pull -r {res} -f --minimum-perc=5".format(res=_tx_resource_for_name(name)), shell=True)
|
||||
languages = sorted([d for d in os.listdir(dir_) if not d.startswith("_") and os.path.isdir(os.path.join(dir_, d)) and d != "en"])
|
||||
else:
|
||||
for lang in languages:
|
||||
call("tx pull -r {res} -f -l {lang}".format(res=_tx_resource_for_name(name), lang=lang), shell=True)
|
||||
|
||||
# msgcat to wrap lines and msgfmt for compilation of .mo file
|
||||
for lang in languages:
|
||||
po_path = "{path}/{lang}/LC_MESSAGES/django.po".format(path=dir_, lang=lang)
|
||||
|
||||
if not os.path.exists(po_path):
|
||||
print("No {lang} translation for resource {res}".format(lang=lang, res=name))
|
||||
continue
|
||||
|
||||
call("msgcat -o {0} {0}".format(po_path), shell=True)
|
||||
res = call("msgfmt -c -o {0}.mo {1}".format(po_path[:-3], po_path), shell=True)
|
||||
|
||||
if res != 0:
|
||||
errors.append((name, lang))
|
||||
|
||||
if errors:
|
||||
print("\nWARNING: Errors have occurred in following cases:")
|
||||
for resource, lang in errors:
|
||||
print("\tResource {res} for language {lang}".format(res=resource, lang=lang))
|
||||
|
||||
exit(1)
|
||||
|
||||
|
||||
def regenerate(resources=None, languages=None):
|
||||
"""
|
||||
Wrap long lines and generate mo files.
|
||||
"""
|
||||
locale_dirs = _get_locale_dirs(resources)
|
||||
errors = []
|
||||
|
||||
for name, dir_ in locale_dirs:
|
||||
if languages is None:
|
||||
languages = sorted([d for d in os.listdir(dir_) if not d.startswith("_") and os.path.isdir(os.path.join(dir_, d)) and d != "en"])
|
||||
|
||||
for lang in languages:
|
||||
po_path = "{path}/{lang}/LC_MESSAGES/django.po".format(path=dir_, lang=lang)
|
||||
|
||||
if not os.path.exists(po_path):
|
||||
print("No {lang} translation for resource {res}".format(lang=lang, res=name))
|
||||
continue
|
||||
|
||||
call("msgcat -o {0} {0}".format(po_path), shell=True)
|
||||
res = call("msgfmt -c -o {0}.mo {1}".format(po_path[:-3], po_path), shell=True)
|
||||
|
||||
if res != 0:
|
||||
errors.append((name, lang))
|
||||
|
||||
if errors:
|
||||
print("\nWARNING: Errors have occurred in following cases:")
|
||||
for resource, lang in errors:
|
||||
print("\tResource {res} for language {lang}".format(res=resource, lang=lang))
|
||||
|
||||
exit(1)
|
||||
|
||||
def commit(resources=None, languages=None):
|
||||
"""
|
||||
Commit messages to Transifex,
|
||||
"""
|
||||
locale_dirs = _get_locale_dirs(resources)
|
||||
errors = []
|
||||
|
||||
for name, dir_ in locale_dirs:
|
||||
# Transifex push
|
||||
if languages is None:
|
||||
call("tx push -r {res} -s -l en".format(res=_tx_resource_for_name(name)), shell=True)
|
||||
else:
|
||||
for lang in languages:
|
||||
call("tx push -r {res} -l {lang}".format(res= _tx_resource_for_name(name), lang=lang), shell=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
devnull = open(os.devnull)
|
||||
Popen(["tx"], stdout=devnull, stderr=devnull).communicate()
|
||||
except OSError as e:
|
||||
if e.errno == os.errno.ENOENT:
|
||||
print("""
|
||||
You need transifex-client, install it.
|
||||
|
||||
1. Install transifex-client, use
|
||||
|
||||
$ pip install --upgrade transifex-client
|
||||
|
||||
2. Create ~/.transifexrc file:
|
||||
|
||||
$ vim ~/.transifexrc"
|
||||
|
||||
[https://www.transifex.com]
|
||||
hostname = https://www.transifex.com
|
||||
token =
|
||||
username = <YOUR_USERNAME>
|
||||
password = <YOUR_PASSWOR>
|
||||
""")
|
||||
exit(1)
|
||||
|
||||
RUNABLE_SCRIPTS = {
|
||||
"update_catalogs": "regenerate .po files of main lang (en).",
|
||||
"commit": "send .po file to transifex ('en' by default).",
|
||||
"fetch": "get .po files from transifex and regenerate .mo files.",
|
||||
"regenerate": "regenerate .mo files.",
|
||||
"lang_stats": "get stats of local translations",
|
||||
}
|
||||
|
||||
parser = ArgumentParser(description="manage translations in taiga-back between the repo and transifex.",
|
||||
formatter_class=RawTextHelpFormatter)
|
||||
parser.add_argument("cmd", nargs=1,
|
||||
help="\n".join(["{0} - {1}".format(c, h) for c, h in RUNABLE_SCRIPTS.items()]))
|
||||
parser.add_argument("-r", "--resources", action="append",
|
||||
help="limit operation to the specified resources")
|
||||
parser.add_argument("-l", "--languages", action="append",
|
||||
help="limit operation to the specified languages")
|
||||
options = parser.parse_args()
|
||||
|
||||
if options.cmd[0] in RUNABLE_SCRIPTS.keys():
|
||||
eval(options.cmd[0])(options.resources, options.languages)
|
||||
else:
|
||||
print("Available commands are: {}".format(", ".join(RUNABLE_SCRIPTS.keys())))
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,22 +14,19 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from kombu import Queue
|
||||
from kombu import Exchange, Queue
|
||||
|
||||
broker_url = 'amqp://guest:guest@localhost:5672//'
|
||||
result_backend = 'redis://localhost:6379/0'
|
||||
BROKER_URL = 'amqp://guest:guest@localhost:5672//'
|
||||
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
|
||||
|
||||
accept_content = ['pickle',] # Values are 'pickle', 'json', 'msgpack' and 'yaml'
|
||||
task_serializer = "pickle"
|
||||
result_serializer = "pickle"
|
||||
CELERY_TIMEZONE = 'Europe/Madrid'
|
||||
CELERY_ENABLE_UTC = True
|
||||
|
||||
timezone = 'Europe/Madrid'
|
||||
|
||||
task_default_queue = 'tasks'
|
||||
task_queues = (
|
||||
CELERY_DEFAULT_QUEUE = 'tasks'
|
||||
CELERY_QUEUES = (
|
||||
Queue('tasks', routing_key='task.#'),
|
||||
Queue('transient', routing_key='transient.#', delivery_mode=1)
|
||||
)
|
||||
task_default_exchange = 'tasks'
|
||||
task_default_exchange_type = 'topic'
|
||||
task_default_routing_key = 'task.default'
|
||||
CELERY_DEFAULT_EXCHANGE = 'tasks'
|
||||
CELERY_DEFAULT_EXCHANGE_TYPE = 'topic'
|
||||
CELERY_DEFAULT_ROUTING_KEY = 'task.default'
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -17,6 +15,7 @@
|
|||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os.path, sys, os
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
||||
|
||||
|
@ -27,11 +26,14 @@ ADMINS = (
|
|||
("Admin", "example@example.com"),
|
||||
)
|
||||
|
||||
DEBUG = False
|
||||
LANGUAGES = (
|
||||
("en", _("English")),
|
||||
("es", _("Spanish")),
|
||||
)
|
||||
|
||||
DATABASES = {
|
||||
"default": {
|
||||
"ENGINE": "django.db.backends.postgresql",
|
||||
"ENGINE": "django.db.backends.postgresql_psycopg2",
|
||||
"NAME": "taiga",
|
||||
}
|
||||
}
|
||||
|
@ -56,112 +58,15 @@ SEND_BROKEN_LINK_EMAILS = True
|
|||
IGNORABLE_404_ENDS = (".php", ".cgi")
|
||||
IGNORABLE_404_STARTS = ("/phpmyadmin/",)
|
||||
|
||||
|
||||
# Default django tz/i18n config
|
||||
ATOMIC_REQUESTS = True
|
||||
TIME_ZONE = "UTC"
|
||||
LOGIN_URL="/auth/login/"
|
||||
USE_TZ = True
|
||||
|
||||
LANGUAGE_CODE = "en"
|
||||
USE_I18N = True
|
||||
USE_L10N = True
|
||||
# Language code for this installation. All choices can be found here:
|
||||
# http://www.i18nguy.com/unicode/language-identifiers.html
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
# Languages we provide translations for, out of the box.
|
||||
LANGUAGES = [
|
||||
#("af", "Afrikaans"), # Afrikaans
|
||||
#("ar", "العربية"), # Arabic
|
||||
#("ast", "Asturiano"), # Asturian
|
||||
#("az", "Azərbaycan dili"), # Azerbaijani
|
||||
#("bg", "Български"), # Bulgarian
|
||||
#("be", "Беларуская"), # Belarusian
|
||||
#("bn", "বাংলা"), # Bengali
|
||||
#("br", "Bretón"), # Breton
|
||||
#("bs", "Bosanski"), # Bosnian
|
||||
("ca", "Català"), # Catalan
|
||||
#("cs", "Čeština"), # Czech
|
||||
#("cy", "Cymraeg"), # Welsh
|
||||
#("da", "Dansk"), # Danish
|
||||
("de", "Deutsch"), # German
|
||||
#("el", "Ελληνικά"), # Greek
|
||||
("en", "English (US)"), # English
|
||||
#("en-au", "English (Australia)"), # Australian English
|
||||
#("en-gb", "English (UK)"), # British English
|
||||
#("eo", "esperanta"), # Esperanto
|
||||
("es", "Español"), # Spanish
|
||||
#("es-ar", "Español (Argentina)"), # Argentinian Spanish
|
||||
#("es-mx", "Español (México)"), # Mexican Spanish
|
||||
#("es-ni", "Español (Nicaragua)"), # Nicaraguan Spanish
|
||||
#("es-ve", "Español (Venezuela)"), # Venezuelan Spanish
|
||||
#("et", "Eesti"), # Estonian
|
||||
#("eu", "Euskara"), # Basque
|
||||
("fa", "فارسی"), # Persian
|
||||
("fi", "Suomi"), # Finnish
|
||||
("fr", "Français"), # French
|
||||
#("fy", "Frysk"), # Frisian
|
||||
#("ga", "Irish"), # Irish
|
||||
#("gl", "Galego"), # Galician
|
||||
#("he", "עברית"), # Hebrew
|
||||
#("hi", "हिन्दी"), # Hindi
|
||||
#("hr", "Hrvatski"), # Croatian
|
||||
#("hu", "Magyar"), # Hungarian
|
||||
#("ia", "Interlingua"), # Interlingua
|
||||
#("id", "Bahasa Indonesia"), # Indonesian
|
||||
#("io", "IDO"), # Ido
|
||||
#("is", "Íslenska"), # Icelandic
|
||||
("it", "Italiano"), # Italian
|
||||
("ja", "日本語"), # Japanese
|
||||
#("ka", "ქართული"), # Georgian
|
||||
#("kk", "Қазақша"), # Kazakh
|
||||
#("km", "ភាសាខ្មែរ"), # Khmer
|
||||
#("kn", "ಕನ್ನಡ"), # Kannada
|
||||
("ko", "한국어"), # Korean
|
||||
#("lb", "Lëtzebuergesch"), # Luxembourgish
|
||||
#("lt", "Lietuvių"), # Lithuanian
|
||||
#("lv", "Latviešu"), # Latvian
|
||||
#("mk", "Македонски"), # Macedonian
|
||||
#("ml", "മലയാളം"), # Malayalam
|
||||
#("mn", "Монгол"), # Mongolian
|
||||
#("mr", "मराठी"), # Marathi
|
||||
#("my", "မြန်မာ"), # Burmese
|
||||
("nb", "Norsk (bokmål)"), # Norwegian Bokmal
|
||||
#("ne", "नेपाली"), # Nepali
|
||||
("nl", "Nederlands"), # Dutch
|
||||
#("nn", "Norsk (nynorsk)"), # Norwegian Nynorsk
|
||||
#("os", "Ирон æвзаг"), # Ossetic
|
||||
#("pa", "ਪੰਜਾਬੀ"), # Punjabi
|
||||
("pl", "Polski"), # Polish
|
||||
#("pt", "Português (Portugal)"), # Portuguese
|
||||
("pt-br", "Português (Brasil)"), # Brazilian Portuguese
|
||||
#("ro", "Română"), # Romanian
|
||||
("ru", "Русский"), # Russian
|
||||
#("sk", "Slovenčina"), # Slovak
|
||||
#("sl", "Slovenščina"), # Slovenian
|
||||
#("sq", "Shqip"), # Albanian
|
||||
#("sr", "Српски"), # Serbian
|
||||
#("sr-latn", "srpski"), # Serbian Latin
|
||||
("sv", "Svenska"), # Swedish
|
||||
#("sw", "Kiswahili"), # Swahili
|
||||
#("ta", "தமிழ்"), # Tamil
|
||||
#("te", "తెలుగు"), # Telugu
|
||||
#("th", "ภาษาไทย"), # Thai
|
||||
("tr", "Türkçe"), # Turkish
|
||||
#("tt", "татар теле"), # Tatar
|
||||
#("udm", "удмурт кыл"), # Udmurt
|
||||
("uk", "Українська"), # Ukrainian
|
||||
#("ur", "اردو"), # Urdu
|
||||
#("vi", "Tiếng Việt"), # Vietnamese
|
||||
("zh-hans", "中文(简体)"), # Simplified Chinese
|
||||
("zh-hant", "中文(香港)"), # Traditional Chinese
|
||||
]
|
||||
|
||||
# Languages using BiDi (right-to-left) layout
|
||||
LANGUAGES_BIDI = ["he", "ar", "fa", "ur"]
|
||||
|
||||
LOCALE_PATHS = (
|
||||
os.path.join(BASE_DIR, "locale"),
|
||||
os.path.join(BASE_DIR, "taiga", "locale"),
|
||||
)
|
||||
LOGIN_URL="/auth/login/"
|
||||
USE_TZ = True
|
||||
|
||||
SITES = {
|
||||
"api": {"domain": "localhost:8000", "scheme": "http", "name": "api"},
|
||||
|
@ -185,21 +90,16 @@ DJMAIL_TEMPLATE_EXTENSION = "jinja"
|
|||
|
||||
# Events backend
|
||||
EVENTS_PUSH_BACKEND = "taiga.events.backends.postgresql.EventsPushBackend"
|
||||
# EVENTS_PUSH_BACKEND = "taiga.events.backends.rabbitmq.EventsPushBackend"
|
||||
# EVENTS_PUSH_BACKEND_OPTIONS = {"url": "//guest:guest@127.0.0.1/"}
|
||||
|
||||
# Message System
|
||||
MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage"
|
||||
|
||||
# The absolute url is mandatory because attachments
|
||||
# urls depends on it. On production should be set
|
||||
# something like https://media.taiga.io/
|
||||
MEDIA_URL = "http://localhost:8000/media/"
|
||||
STATIC_URL = "http://localhost:8000/static/"
|
||||
|
||||
# Static configuration.
|
||||
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
|
||||
MEDIA_URL = "/media/"
|
||||
STATIC_ROOT = os.path.join(BASE_DIR, "static")
|
||||
STATIC_URL = "/static/"
|
||||
ADMIN_MEDIA_PREFIX = "/static/admin/"
|
||||
|
||||
STATICFILES_FINDERS = [
|
||||
"django.contrib.staticfiles.finders.FileSystemFinder",
|
||||
|
@ -211,54 +111,22 @@ STATICFILES_DIRS = (
|
|||
# Don't forget to use absolute paths, not relative paths.
|
||||
)
|
||||
|
||||
# Default storage
|
||||
|
||||
# Defautl storage
|
||||
DEFAULT_FILE_STORAGE = "taiga.base.storage.FileSystemStorage"
|
||||
|
||||
FILE_UPLOAD_PERMISSIONS = 0o644
|
||||
|
||||
LOCALE_PATHS = (
|
||||
os.path.join(BASE_DIR, "locale"),
|
||||
)
|
||||
|
||||
SECRET_KEY = "aw3+t2r(8(0kkrhg8)gx6i96v5^kv%6cfep9wxfom0%7dy0m9e"
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
"BACKEND": "django_jinja.backend.Jinja2",
|
||||
"DIRS": [
|
||||
os.path.join(BASE_DIR, "templates"),
|
||||
],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
'context_processors': [
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.template.context_processors.request",
|
||||
"django.template.context_processors.i18n",
|
||||
"django.template.context_processors.media",
|
||||
"django.template.context_processors.static",
|
||||
"django.template.context_processors.tz",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
"match_extension": ".jinja",
|
||||
}
|
||||
},
|
||||
{
|
||||
"BACKEND": "django.template.backends.django.DjangoTemplates",
|
||||
"DIRS": [
|
||||
os.path.join(BASE_DIR, "templates"),
|
||||
],
|
||||
"APP_DIRS": True,
|
||||
"OPTIONS": {
|
||||
'context_processors': [
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.template.context_processors.request",
|
||||
"django.template.context_processors.i18n",
|
||||
"django.template.context_processors.media",
|
||||
"django.template.context_processors.static",
|
||||
"django.template.context_processors.tz",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
],
|
||||
}
|
||||
},
|
||||
TEMPLATE_LOADERS = [
|
||||
"django_jinja.loaders.AppLoader",
|
||||
"django_jinja.loaders.FileSystemLoader",
|
||||
]
|
||||
|
||||
|
||||
MIDDLEWARE_CLASSES = [
|
||||
"taiga.base.middleware.cors.CoorsMiddleware",
|
||||
"taiga.events.middleware.SessionIDMiddleware",
|
||||
|
@ -273,9 +141,22 @@ MIDDLEWARE_CLASSES = [
|
|||
"django.contrib.messages.middleware.MessageMiddleware",
|
||||
]
|
||||
|
||||
TEMPLATE_CONTEXT_PROCESSORS = [
|
||||
"django.contrib.auth.context_processors.auth",
|
||||
"django.core.context_processors.request",
|
||||
"django.core.context_processors.i18n",
|
||||
"django.core.context_processors.media",
|
||||
"django.core.context_processors.static",
|
||||
"django.core.context_processors.tz",
|
||||
"django.contrib.messages.context_processors.messages",
|
||||
]
|
||||
|
||||
ROOT_URLCONF = "taiga.urls"
|
||||
|
||||
TEMPLATE_DIRS = [
|
||||
os.path.join(BASE_DIR, "templates"),
|
||||
]
|
||||
|
||||
INSTALLED_APPS = [
|
||||
"django.contrib.auth",
|
||||
"django.contrib.contenttypes",
|
||||
|
@ -283,52 +164,32 @@ INSTALLED_APPS = [
|
|||
"django.contrib.messages",
|
||||
"django.contrib.admin",
|
||||
"django.contrib.staticfiles",
|
||||
"django.contrib.sitemaps",
|
||||
"django.contrib.postgres",
|
||||
|
||||
"taiga.base",
|
||||
"taiga.base.api",
|
||||
"taiga.locale",
|
||||
"taiga.events",
|
||||
"taiga.front",
|
||||
"taiga.users",
|
||||
"taiga.userstorage",
|
||||
"taiga.external_apps",
|
||||
"taiga.projects",
|
||||
"taiga.projects.references",
|
||||
"taiga.projects.custom_attributes",
|
||||
"taiga.projects.history",
|
||||
"taiga.projects.notifications",
|
||||
"taiga.projects.attachments",
|
||||
"taiga.projects.likes",
|
||||
"taiga.projects.votes",
|
||||
"taiga.projects.milestones",
|
||||
"taiga.projects.epics",
|
||||
"taiga.projects.userstories",
|
||||
"taiga.projects.tasks",
|
||||
"taiga.projects.issues",
|
||||
"taiga.projects.references",
|
||||
"taiga.projects.wiki",
|
||||
"taiga.projects.contact",
|
||||
"taiga.projects.settings",
|
||||
"taiga.projects.history",
|
||||
"taiga.projects.notifications",
|
||||
"taiga.projects.votes",
|
||||
"taiga.searches",
|
||||
"taiga.timeline",
|
||||
"taiga.mdrender",
|
||||
"taiga.export_import",
|
||||
"taiga.feedback",
|
||||
"taiga.stats",
|
||||
"taiga.hooks.github",
|
||||
"taiga.hooks.gitlab",
|
||||
"taiga.hooks.bitbucket",
|
||||
"taiga.hooks.gogs",
|
||||
"taiga.webhooks",
|
||||
"taiga.importers",
|
||||
|
||||
"rest_framework",
|
||||
"djmail",
|
||||
"django_jinja",
|
||||
"django_jinja.contrib._humanize",
|
||||
"sr",
|
||||
"easy_thumbnails",
|
||||
"raven.contrib.django.raven_compat",
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = "taiga.wsgi.application"
|
||||
|
@ -351,15 +212,11 @@ LOGGING = {
|
|||
"null": {
|
||||
"format": "%(message)s",
|
||||
},
|
||||
"django.server": {
|
||||
"()": "django.utils.log.ServerFormatter",
|
||||
"format": "[%(server_time)s] %(message)s",
|
||||
},
|
||||
},
|
||||
"handlers": {
|
||||
"null": {
|
||||
"level":"DEBUG",
|
||||
"class":"logging.NullHandler",
|
||||
"class":"django.utils.log.NullHandler",
|
||||
},
|
||||
"console":{
|
||||
"level":"DEBUG",
|
||||
|
@ -370,12 +227,7 @@ LOGGING = {
|
|||
"level": "ERROR",
|
||||
"filters": ["require_debug_false"],
|
||||
"class": "django.utils.log.AdminEmailHandler",
|
||||
},
|
||||
"django.server": {
|
||||
"level": "INFO",
|
||||
"class": "logging.StreamHandler",
|
||||
"formatter": "django.server",
|
||||
},
|
||||
}
|
||||
},
|
||||
"loggers": {
|
||||
"django": {
|
||||
|
@ -388,28 +240,22 @@ LOGGING = {
|
|||
"level": "ERROR",
|
||||
"propagate": False,
|
||||
},
|
||||
"taiga.export_import": {
|
||||
"handlers": ["mail_admins", "console"],
|
||||
"level": "ERROR",
|
||||
"propagate": False,
|
||||
},
|
||||
"taiga": {
|
||||
"handlers": ["console"],
|
||||
"level": "DEBUG",
|
||||
"propagate": False,
|
||||
},
|
||||
"django.server": {
|
||||
"handlers": ["django.server"],
|
||||
"taiga.domains": {
|
||||
"handlers": ["console"],
|
||||
"level": "INFO",
|
||||
"propagate": False,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
AUTH_USER_MODEL = "users.User"
|
||||
FORMAT_MODULE_PATH = "taiga.base.formats"
|
||||
|
||||
DATE_INPUT_FORMATS = (
|
||||
"%Y-%m-%d", "%m/%d/%Y", "%d/%m/%Y", "%b %d %Y",
|
||||
"%b %d, %Y", "%d %b %Y", "%d %b, %Y", "%B %d %Y",
|
||||
|
@ -421,8 +267,13 @@ AUTHENTICATION_BACKENDS = (
|
|||
"django.contrib.auth.backends.ModelBackend", # default
|
||||
)
|
||||
|
||||
MAX_AGE_AUTH_TOKEN = None
|
||||
MAX_AGE_CANCEL_ACCOUNT = 30 * 24 * 60 * 60 # 30 days in seconds
|
||||
ANONYMOUS_USER_ID = -1
|
||||
GRAPPELLI_INDEX_DASHBOARD = "taiga.dashboard.CustomIndexDashboard"
|
||||
|
||||
MAX_SEARCH_RESULTS = 100
|
||||
|
||||
# FIXME: this seems not be used by any module
|
||||
API_LIMIT_PER_PAGE = 0
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
"DEFAULT_AUTHENTICATION_CLASSES": (
|
||||
|
@ -431,27 +282,7 @@ REST_FRAMEWORK = {
|
|||
|
||||
# Mainly used for api debug.
|
||||
"taiga.auth.backends.Session",
|
||||
|
||||
# Application tokens auth
|
||||
"taiga.external_apps.auth_backends.Token",
|
||||
),
|
||||
"DEFAULT_THROTTLE_CLASSES": (
|
||||
"taiga.base.throttling.CommonThrottle",
|
||||
),
|
||||
"DEFAULT_THROTTLE_RATES": {
|
||||
"anon-write": None,
|
||||
"user-write": None,
|
||||
"anon-read": None,
|
||||
"user-read": None,
|
||||
"import-mode": None,
|
||||
"import-dump-mode": "1/minute",
|
||||
"create-memberships": None,
|
||||
"login-fail": None,
|
||||
"register-success": None,
|
||||
"user-detail": None,
|
||||
"user-update": None,
|
||||
},
|
||||
"DEFAULT_THROTTLE_WHITELIST": [],
|
||||
"FILTER_BACKEND": "taiga.base.filters.FilterBackend",
|
||||
"EXCEPTION_HANDLER": "taiga.base.exceptions.exception_handler",
|
||||
"PAGINATE_BY": 30,
|
||||
|
@ -460,19 +291,8 @@ REST_FRAMEWORK = {
|
|||
"DATETIME_FORMAT": "%Y-%m-%dT%H:%M:%S%z"
|
||||
}
|
||||
|
||||
# Extra expose header related to Taiga APP (see taiga.base.middleware.cors=)
|
||||
APP_EXTRA_EXPOSE_HEADERS = [
|
||||
"taiga-info-total-opened-milestones",
|
||||
"taiga-info-total-closed-milestones",
|
||||
"taiga-info-project-memberships",
|
||||
"taiga-info-project-is-private",
|
||||
"taiga-info-order-updated"
|
||||
]
|
||||
|
||||
DEFAULT_PROJECT_TEMPLATE = "scrum"
|
||||
PUBLIC_REGISTER_ENABLED = False
|
||||
# None or [] values in USER_EMAIL_ALLOWED_DOMAINS means allow any domain
|
||||
USER_EMAIL_ALLOWED_DOMAINS = None
|
||||
|
||||
SEARCHES_MAX_RESULTS = 150
|
||||
|
||||
|
@ -480,36 +300,30 @@ SOUTH_MIGRATION_MODULES = {
|
|||
'easy_thumbnails': 'easy_thumbnails.south_migrations',
|
||||
}
|
||||
|
||||
DEFAULT_AVATAR_SIZE = 80 # 80x80 pixels
|
||||
DEFAULT_BIG_AVATAR_SIZE = 300 # 300x300 pixels
|
||||
|
||||
THN_AVATAR_SIZE = 80 # 80x80 pixels
|
||||
THN_AVATAR_BIG_SIZE = 300 # 300x300 pixels
|
||||
THN_LOGO_SMALL_SIZE = 80 # 80x80 pixels
|
||||
THN_LOGO_BIG_SIZE = 300 # 300x300 pixels
|
||||
THN_TIMELINE_IMAGE_SIZE = 640 # 640x??? pixels
|
||||
THN_CARD_IMAGE_WIDTH = 300 # 300 pixels
|
||||
THN_CARD_IMAGE_HEIGHT = 200 # 200 pixels
|
||||
THN_PREVIEW_IMAGE_WIDTH = 800 # 800 pixels
|
||||
|
||||
THN_AVATAR_SMALL = "avatar"
|
||||
THN_AVATAR_BIG = "big-avatar"
|
||||
THN_LOGO_SMALL = "logo-small"
|
||||
THN_LOGO_BIG = "logo-big"
|
||||
THN_ATTACHMENT_TIMELINE = "timeline-image"
|
||||
THN_ATTACHMENT_CARD = "card-image"
|
||||
THN_ATTACHMENT_PREVIEW = "preview-image"
|
||||
DEFAULT_AVATAR_URL = ''
|
||||
|
||||
THUMBNAIL_ALIASES = {
|
||||
"": {
|
||||
THN_AVATAR_SMALL: {"size": (THN_AVATAR_SIZE, THN_AVATAR_SIZE), "crop": True},
|
||||
THN_AVATAR_BIG: {"size": (THN_AVATAR_BIG_SIZE, THN_AVATAR_BIG_SIZE), "crop": True},
|
||||
THN_LOGO_SMALL: {"size": (THN_LOGO_SMALL_SIZE, THN_LOGO_SMALL_SIZE), "crop": True},
|
||||
THN_LOGO_BIG: {"size": (THN_LOGO_BIG_SIZE, THN_LOGO_BIG_SIZE), "crop": True},
|
||||
THN_ATTACHMENT_TIMELINE: {"size": (THN_TIMELINE_IMAGE_SIZE, 0), "crop": True},
|
||||
THN_ATTACHMENT_CARD: {"size": (THN_CARD_IMAGE_WIDTH, THN_CARD_IMAGE_HEIGHT), "crop": True},
|
||||
THN_ATTACHMENT_PREVIEW: {"size": (THN_PREVIEW_IMAGE_WIDTH, 0), "crop": False},
|
||||
'': {
|
||||
'avatar': {'size': (DEFAULT_AVATAR_SIZE, DEFAULT_AVATAR_SIZE), 'crop': True},
|
||||
'big-avatar': {'size': (DEFAULT_BIG_AVATAR_SIZE, DEFAULT_BIG_AVATAR_SIZE), 'crop': True},
|
||||
},
|
||||
}
|
||||
|
||||
GRAVATAR_DEFAULT_OPTIONS = {
|
||||
'default': DEFAULT_AVATAR_URL, # default avatar to show if there's no gravatar image
|
||||
'size': DEFAULT_AVATAR_SIZE
|
||||
}
|
||||
|
||||
try:
|
||||
IN_DEVELOPMENT_SERVER = sys.argv[1] == 'runserver'
|
||||
except IndexError:
|
||||
IN_DEVELOPMENT_SERVER = False
|
||||
|
||||
ATTACHMENTS_TOKEN_SALT = "ATTACHMENTS_TOKEN_SALT"
|
||||
|
||||
TAGS_PREDEFINED_COLORS = ["#fce94f", "#edd400", "#c4a000", "#8ae234",
|
||||
"#73d216", "#4e9a06", "#d3d7cf", "#fcaf3e",
|
||||
"#f57900", "#ce5c00", "#729fcf", "#3465a4",
|
||||
|
@ -517,84 +331,12 @@ TAGS_PREDEFINED_COLORS = ["#fce94f", "#edd400", "#c4a000", "#8ae234",
|
|||
"#5c3566", "#ef2929", "#cc0000", "#a40000",
|
||||
"#2e3436",]
|
||||
|
||||
# Feedback module settings
|
||||
FEEDBACK_ENABLED = True
|
||||
FEEDBACK_EMAIL = "support@taiga.io"
|
||||
|
||||
# Stats module settings
|
||||
STATS_ENABLED = False
|
||||
STATS_CACHE_TIMEOUT = 60*60 # In second
|
||||
|
||||
# 0 notifications will work in a synchronous way
|
||||
# >0 an external process will check the pending notifications and will send them
|
||||
# collapsed during that interval
|
||||
CHANGE_NOTIFICATIONS_MIN_INTERVAL = 0 #seconds
|
||||
|
||||
|
||||
# List of functions called for filling correctly the ProjectModulesConfig associated to a project
|
||||
# This functions should receive a Project parameter and return a dict with the desired configuration
|
||||
PROJECT_MODULES_CONFIGURATORS = {
|
||||
"github": "taiga.hooks.github.services.get_or_generate_config",
|
||||
"gitlab": "taiga.hooks.gitlab.services.get_or_generate_config",
|
||||
"bitbucket": "taiga.hooks.bitbucket.services.get_or_generate_config",
|
||||
"gogs": "taiga.hooks.gogs.services.get_or_generate_config",
|
||||
}
|
||||
|
||||
BITBUCKET_VALID_ORIGIN_IPS = ["131.103.20.165", "131.103.20.166", "104.192.143.192/28", "104.192.143.208/28"]
|
||||
|
||||
GITLAB_VALID_ORIGIN_IPS = []
|
||||
|
||||
EXPORTS_TTL = 60 * 60 * 24 # 24 hours
|
||||
|
||||
CELERY_ENABLED = False
|
||||
WEBHOOKS_ENABLED = False
|
||||
WEBHOOKS_BLOCK_PRIVATE_ADDRESS = False
|
||||
|
||||
|
||||
# If is True /front/sitemap.xml show a valid sitemap of taiga-front client
|
||||
FRONT_SITEMAP_ENABLED = False
|
||||
FRONT_SITEMAP_CACHE_TIMEOUT = 24*60*60 # In second
|
||||
|
||||
EXTRA_BLOCKING_CODES = []
|
||||
|
||||
MAX_PRIVATE_PROJECTS_PER_USER = None # None == no limit
|
||||
MAX_PUBLIC_PROJECTS_PER_USER = None # None == no limit
|
||||
MAX_MEMBERSHIPS_PRIVATE_PROJECTS = None # None == no limit
|
||||
MAX_MEMBERSHIPS_PUBLIC_PROJECTS = None # None == no limit
|
||||
|
||||
MAX_PENDING_MEMBERSHIPS = 30 # Max number of unconfirmed memberships in a project
|
||||
|
||||
from .sr import *
|
||||
|
||||
IMPORTERS = {
|
||||
"github": {
|
||||
"active": False,
|
||||
"client_id": "",
|
||||
"client_secret": "",
|
||||
},
|
||||
"trello": {
|
||||
"active": False,
|
||||
"api_key": "",
|
||||
"secret_key": "",
|
||||
},
|
||||
"jira": {
|
||||
"active": False,
|
||||
"consumer_key": "",
|
||||
"cert": "",
|
||||
"pub_cert": "",
|
||||
},
|
||||
"asana": {
|
||||
"active": False,
|
||||
"callback_url": "",
|
||||
"app_id": "",
|
||||
"app_secret": "",
|
||||
}
|
||||
}
|
||||
|
||||
# NOTE: DON'T INSERT MORE SETTINGS AFTER THIS LINE
|
||||
|
||||
TEST_RUNNER="django.test.runner.DiscoverRunner"
|
||||
|
||||
if "test" in sys.argv:
|
||||
print ("\033[1;91mNo django tests.\033[0m")
|
||||
print ("Try: \033[1;33mpy.test\033[0m")
|
||||
sys.exit(0)
|
||||
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -19,5 +17,8 @@
|
|||
from .common import *
|
||||
|
||||
DEBUG = True
|
||||
TEMPLATE_DEBUG = DEBUG
|
||||
|
||||
TEMPLATES[0]["OPTIONS"]['context_processors'] += "django.template.context_processors.debug"
|
||||
TEMPLATE_CONTEXT_PROCESSORS += [
|
||||
"django.core.context_processors.debug",
|
||||
]
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -18,188 +16,40 @@
|
|||
|
||||
from .development import *
|
||||
|
||||
#########################################
|
||||
## GENERIC
|
||||
#########################################
|
||||
|
||||
#DEBUG = False
|
||||
|
||||
#ADMINS = (
|
||||
# ("Admin", "example@example.com"),
|
||||
#)
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.postgresql',
|
||||
'NAME': 'taiga',
|
||||
'USER': 'taiga',
|
||||
'PASSWORD': 'changeme',
|
||||
'HOST': '',
|
||||
'PORT': '',
|
||||
}
|
||||
}
|
||||
|
||||
#SITES = {
|
||||
# "api": {
|
||||
# "scheme": "http",
|
||||
# "domain": "localhost:8000",
|
||||
# "name": "api"
|
||||
# },
|
||||
# "front": {
|
||||
# "scheme": "http",
|
||||
# "domain": "localhost:9001",
|
||||
# "name": "front"
|
||||
# },
|
||||
#DATABASES = {
|
||||
# 'default': {
|
||||
# 'ENGINE': 'django.db.backends.postgresql_psycopg2',
|
||||
# 'NAME': 'taiga',
|
||||
# 'USER': 'taiga',
|
||||
# 'PASSWORD': '',
|
||||
# 'HOST': '',
|
||||
# 'PORT': '',
|
||||
# }
|
||||
#}
|
||||
|
||||
#SITE_ID = "api"
|
||||
|
||||
#
|
||||
#HOST="http://taiga.projects.kaleidos.net"
|
||||
#
|
||||
#MEDIA_ROOT = '/home/taiga/media'
|
||||
#STATIC_ROOT = '/home/taiga/static'
|
||||
|
||||
|
||||
#########################################
|
||||
## THROTTLING
|
||||
#########################################
|
||||
|
||||
#REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"] = {
|
||||
# "anon-write": "20/min",
|
||||
# "user-write": None,
|
||||
# "anon-read": None,
|
||||
# "user-read": None,
|
||||
# "import-mode": None,
|
||||
# "import-dump-mode": "1/minute",
|
||||
# "create-memberships": None,
|
||||
# "login-fail": None,
|
||||
# "register-success": None,
|
||||
# "user-detail": None,
|
||||
# "user-update": None,
|
||||
#}
|
||||
|
||||
# This list should containt:
|
||||
# - Tiga users IDs
|
||||
# - Valid clients IP addresses (X-Forwarded-For header)
|
||||
#REST_FRAMEWORK["DEFAULT_THROTTLE_WHITELIST"] = []
|
||||
|
||||
|
||||
#########################################
|
||||
## MAIL SYSTEM SETTINGS
|
||||
#########################################
|
||||
|
||||
#DEFAULT_FROM_EMAIL = "john@doe.com"
|
||||
#CHANGE_NOTIFICATIONS_MIN_INTERVAL = 300 #seconds
|
||||
|
||||
# EMAIL SETTINGS EXAMPLE
|
||||
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
|
||||
#EMAIL_USE_TLS = False
|
||||
#EMAIL_USE_SSL = False # You cannot use both (TLS and SSL) at the same time!
|
||||
#EMAIL_HOST = 'localhost'
|
||||
#EMAIL_PORT = 25
|
||||
#EMAIL_HOST_USER = 'user'
|
||||
#EMAIL_HOST_PASSWORD = 'password'
|
||||
#EMAIL_PORT = 25
|
||||
#DEFAULT_FROM_EMAIL = "john@doe.com"
|
||||
|
||||
# GMAIL SETTINGS EXAMPLE
|
||||
#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
|
||||
#EMAIL_USE_TLS = True
|
||||
#EMAIL_HOST = 'smtp.gmail.com'
|
||||
#EMAIL_PORT = 587
|
||||
#EMAIL_HOST_USER = 'youremail@gmail.com'
|
||||
#EMAIL_HOST_PASSWORD = 'yourpassword'
|
||||
#EMAIL_PORT = 587
|
||||
|
||||
|
||||
#########################################
|
||||
## REGISTRATION
|
||||
#########################################
|
||||
|
||||
#PUBLIC_REGISTER_ENABLED = True
|
||||
|
||||
# LIMIT ALLOWED DOMAINS FOR REGISTER AND INVITE
|
||||
# None or [] values in USER_EMAIL_ALLOWED_DOMAINS means allow any domain
|
||||
#USER_EMAIL_ALLOWED_DOMAINS = None
|
||||
|
||||
# PUCLIC OR PRIVATE NUMBER OF PROJECT PER USER
|
||||
#MAX_PRIVATE_PROJECTS_PER_USER = None # None == no limit
|
||||
#MAX_PUBLIC_PROJECTS_PER_USER = None # None == no limit
|
||||
#MAX_MEMBERSHIPS_PRIVATE_PROJECTS = None # None == no limit
|
||||
#MAX_MEMBERSHIPS_PUBLIC_PROJECTS = None # None == no limit
|
||||
|
||||
# GITHUB SETTINGS
|
||||
# GITHUP SETTINGS
|
||||
#GITHUB_URL = "https://github.com/"
|
||||
#GITHUB_API_URL = "https://api.github.com/"
|
||||
#GITHUB_API_CLIENT_ID = "yourgithubclientid"
|
||||
#GITHUB_API_CLIENT_SECRET = "yourgithubclientsecret"
|
||||
|
||||
|
||||
#########################################
|
||||
## SITEMAP
|
||||
#########################################
|
||||
|
||||
# If is True /front/sitemap.xml show a valid sitemap of taiga-front client
|
||||
#FRONT_SITEMAP_ENABLED = False
|
||||
#FRONT_SITEMAP_CACHE_TIMEOUT = 24*60*60 # In second
|
||||
|
||||
|
||||
#########################################
|
||||
## FEEDBACK
|
||||
#########################################
|
||||
|
||||
# Note: See config in taiga-front too
|
||||
#FEEDBACK_ENABLED = True
|
||||
#FEEDBACK_EMAIL = "support@taiga.io"
|
||||
|
||||
|
||||
#########################################
|
||||
## STATS
|
||||
#########################################
|
||||
|
||||
#STATS_ENABLED = False
|
||||
#FRONT_SITEMAP_CACHE_TIMEOUT = 60*60 # In second
|
||||
|
||||
|
||||
#########################################
|
||||
## CELERY
|
||||
#########################################
|
||||
# Set to True to enable celery and work in async mode or False
|
||||
# to disable it and work in sync mode. You can find the celery
|
||||
# settings in settings/celery.py and settings/celery-local.py
|
||||
#CELERY_ENABLED = True
|
||||
|
||||
|
||||
#########################################
|
||||
## IMPORTERS
|
||||
#########################################
|
||||
|
||||
# Configuration for the GitHub importer
|
||||
# Remember to enable it in the front client too.
|
||||
#IMPORTERS["github"] = {
|
||||
# "active": True, # Enable or disable the importer
|
||||
# "client_id": "XXXXXX_get_a_valid_client_id_from_github_XXXXXX",
|
||||
# "client_secret": "XXXXXX_get_a_valid_client_secret_from_github_XXXXXX"
|
||||
#}
|
||||
|
||||
# Configuration for the Trello importer
|
||||
# Remember to enable it in the front client too.
|
||||
#IMPORTERS["trello"] = {
|
||||
# "active": True, # Enable or disable the importer
|
||||
# "api_key": "XXXXXX_get_a_valid_api_key_from_trello_XXXXXX",
|
||||
# "secret_key": "XXXXXX_get_a_valid_secret_key_from_trello_XXXXXX"
|
||||
#}
|
||||
|
||||
# Configuration for the Jira importer
|
||||
# Remember to enable it in the front client too.
|
||||
#IMPORTERS["jira"] = {
|
||||
# "active": True, # Enable or disable the importer
|
||||
# "consumer_key": "XXXXXX_get_a_valid_consumer_key_from_jira_XXXXXX",
|
||||
# "cert": "XXXXXX_get_a_valid_cert_from_jira_XXXXXX",
|
||||
# "pub_cert": "XXXXXX_get_a_valid_pub_cert_from_jira_XXXXXX"
|
||||
#}
|
||||
|
||||
# Configuration for the Asane importer
|
||||
# Remember to enable it in the front client too.
|
||||
#IMPORTERS["asana"] = {
|
||||
# "active": True, # Enable or disable the importer
|
||||
# "callback_url": "{}://{}/project/new/import/asana".format(SITES["front"]["scheme"],
|
||||
# SITES["front"]["domain"]),
|
||||
# "app_id": "XXXXXX_get_a_valid_app_id_from_asana_XXXXXX",
|
||||
# "app_secret": "XXXXXX_get_a_valid_app_secret_from_asana_XXXXXX"
|
||||
#}
|
||||
|
|
|
@ -1,31 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
SR = {
|
||||
"taigaio_url": "https://taiga.io",
|
||||
"social": {
|
||||
"twitter_url": "https://twitter.com/taigaio",
|
||||
"github_url": "https://github.com/taigaio",
|
||||
},
|
||||
"support": {
|
||||
"url": "https://tree.taiga.io/support",
|
||||
"email": "support@taiga.io",
|
||||
"mailing_list": "https://groups.google.com/forum/#!forum/taigaio",
|
||||
}
|
||||
}
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -18,31 +16,11 @@
|
|||
|
||||
from .development import *
|
||||
|
||||
CELERY_ENABLED = False
|
||||
SKIP_SOUTH_TESTS = True
|
||||
SOUTH_TESTS_MIGRATE = False
|
||||
CELERY_ALWAYS_EAGER = True
|
||||
|
||||
MEDIA_ROOT = "/tmp"
|
||||
|
||||
EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
|
||||
INSTALLED_APPS = INSTALLED_APPS + [
|
||||
"tests",
|
||||
]
|
||||
|
||||
REST_FRAMEWORK["DEFAULT_THROTTLE_RATES"] = {
|
||||
"anon-write": None,
|
||||
"anon-read": None,
|
||||
"user-write": None,
|
||||
"user-read": None,
|
||||
"import-mode": None,
|
||||
"import-dump-mode": None,
|
||||
"create-memberships": None,
|
||||
"login-fail": None,
|
||||
"register-success": None,
|
||||
"user-detail": None,
|
||||
"user-update": None,
|
||||
}
|
||||
|
||||
|
||||
IMPORTERS['github']['active'] = True
|
||||
IMPORTERS['jira']['active'] = True
|
||||
IMPORTERS['asana']['active'] = True
|
||||
IMPORTERS['trello']['active'] = True
|
||||
INSTALLED_APPS = INSTALLED_APPS + ["tests"]
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,4 +14,12 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
default_app_config = "taiga.feedback.apps.FeedbackAppConfig"
|
||||
from .testing import *
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.postgresql_psycopg2',
|
||||
'NAME': 'taiga',
|
||||
'USERNAME': 'postgres',
|
||||
}
|
||||
}
|
14
setup.cfg
14
setup.cfg
|
@ -1,14 +0,0 @@
|
|||
[flake8]
|
||||
ignore = E41,E266
|
||||
max-line-length = 120
|
||||
exclude =
|
||||
.cache,
|
||||
.git,
|
||||
.tox,
|
||||
.venv,
|
||||
*__pycache__*,
|
||||
*tests*,
|
||||
*scripts*,
|
||||
*migrations*,
|
||||
*management*
|
||||
max-complexity = 10
|
|
@ -1,19 +1 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from . import celery
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -17,32 +15,38 @@
|
|||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from functools import partial
|
||||
from enum import Enum
|
||||
|
||||
from django.utils.translation import ugettext as _
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.conf import settings
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import status
|
||||
from rest_framework import serializers
|
||||
|
||||
from taiga.base.api import viewsets
|
||||
from taiga.base.decorators import list_route
|
||||
from taiga.base import exceptions as exc
|
||||
from taiga.base import response
|
||||
from taiga.base.connectors import github
|
||||
from taiga.users.services import get_and_validate_user
|
||||
|
||||
from .validators import PublicRegisterValidator
|
||||
from .validators import PrivateRegisterValidator
|
||||
from .serializers import PublicRegisterSerializer
|
||||
from .serializers import PrivateRegisterForExistingUserSerializer
|
||||
from .serializers import PrivateRegisterForNewUserSerializer
|
||||
|
||||
from .services import private_register_for_existing_user
|
||||
from .services import private_register_for_new_user
|
||||
from .services import public_register
|
||||
from .services import github_register
|
||||
from .services import make_auth_response_data
|
||||
from .services import get_auth_plugins
|
||||
from .services import accept_invitation_by_existing_user
|
||||
|
||||
from .permissions import AuthPermission
|
||||
from .throttling import LoginFailRateThrottle, RegisterSuccessRateThrottle
|
||||
|
||||
|
||||
def _parse_data(data:dict, *, cls):
|
||||
"""
|
||||
Generic function for parse user data using
|
||||
specified validator on `cls` keyword parameter.
|
||||
specified serializer on `cls` keyword parameter.
|
||||
|
||||
Raises: RequestValidationError exception if
|
||||
some errors found when data is validated.
|
||||
|
@ -50,21 +54,49 @@ def _parse_data(data:dict, *, cls):
|
|||
Returns the parsed data.
|
||||
"""
|
||||
|
||||
validator = cls(data=data)
|
||||
if not validator.is_valid():
|
||||
raise exc.RequestValidationError(validator.errors)
|
||||
return validator.data
|
||||
serializer = cls(data=data)
|
||||
if not serializer.is_valid():
|
||||
raise exc.RequestValidationError(serializer.errors)
|
||||
return serializer.data
|
||||
|
||||
# Parse public register data
|
||||
parse_public_register_data = partial(_parse_data, cls=PublicRegisterValidator)
|
||||
parse_public_register_data = partial(_parse_data, cls=PublicRegisterSerializer)
|
||||
|
||||
# Parse private register data for existing user
|
||||
parse_private_register_for_existing_user_data = \
|
||||
partial(_parse_data, cls=PrivateRegisterForExistingUserSerializer)
|
||||
|
||||
# Parse private register data for new user
|
||||
parse_private_register_data = partial(_parse_data, cls=PrivateRegisterValidator)
|
||||
parse_private_register_for_new_user_data = \
|
||||
partial(_parse_data, cls=PrivateRegisterForNewUserSerializer)
|
||||
|
||||
|
||||
class RegisterTypeEnum(Enum):
|
||||
new_user = 1
|
||||
existing_user = 2
|
||||
|
||||
|
||||
def parse_register_type(userdata:dict) -> str:
|
||||
"""
|
||||
Parses user data and detects that register type is.
|
||||
It returns RegisterTypeEnum value.
|
||||
"""
|
||||
# Create adhoc inner serializer for avoid parse
|
||||
# manually the user data.
|
||||
class _serializer(serializers.Serializer):
|
||||
existing = serializers.BooleanField()
|
||||
|
||||
instance = _serializer(data=userdata)
|
||||
if not instance.is_valid():
|
||||
raise exc.RequestValidationError(instance.errors)
|
||||
|
||||
if instance.data["existing"]:
|
||||
return RegisterTypeEnum.existing_user
|
||||
return RegisterTypeEnum.new_user
|
||||
|
||||
|
||||
class AuthViewSet(viewsets.ViewSet):
|
||||
permission_classes = (AuthPermission,)
|
||||
throttle_classes = (LoginFailRateThrottle, RegisterSuccessRateThrottle)
|
||||
|
||||
def _public_register(self, request):
|
||||
if not settings.PUBLIC_REGISTER_ENABLED:
|
||||
|
@ -77,21 +109,23 @@ class AuthViewSet(viewsets.ViewSet):
|
|||
raise exc.BadRequest(e.detail)
|
||||
|
||||
data = make_auth_response_data(user)
|
||||
return response.Created(data)
|
||||
return Response(data, status=status.HTTP_201_CREATED)
|
||||
|
||||
def _private_register(self, request):
|
||||
data = parse_private_register_data(request.DATA)
|
||||
register_type = parse_register_type(request.DATA)
|
||||
|
||||
if register_type is RegisterTypeEnum.existing_user:
|
||||
data = parse_private_register_for_existing_user_data(request.DATA)
|
||||
user = private_register_for_existing_user(**data)
|
||||
else:
|
||||
data = parse_private_register_for_new_user_data(request.DATA)
|
||||
user = private_register_for_new_user(**data)
|
||||
|
||||
data = make_auth_response_data(user)
|
||||
return response.Created(data)
|
||||
return Response(data, status=status.HTTP_201_CREATED)
|
||||
|
||||
@list_route(methods=["POST"])
|
||||
def register(self, request, **kwargs):
|
||||
accepted_terms = request.DATA.get("accepted_terms", None)
|
||||
if accepted_terms in (None, False):
|
||||
raise exc.BadRequest(_("You must accept our terms of service and privacy policy"))
|
||||
|
||||
self.check_permissions(request, 'register', None)
|
||||
|
||||
type = request.DATA.get("type", None)
|
||||
|
@ -101,18 +135,36 @@ class AuthViewSet(viewsets.ViewSet):
|
|||
return self._private_register(request)
|
||||
raise exc.BadRequest(_("invalid register type"))
|
||||
|
||||
def _login(self, request):
|
||||
username = request.DATA.get('username', None)
|
||||
password = request.DATA.get('password', None)
|
||||
|
||||
user = get_and_validate_user(username=username, password=password)
|
||||
data = make_auth_response_data(user)
|
||||
return Response(data, status=status.HTTP_200_OK)
|
||||
|
||||
def _github_login(self, request):
|
||||
code = request.DATA.get('code', None)
|
||||
token = request.DATA.get('token', None)
|
||||
|
||||
email, user_info = github.me(code)
|
||||
|
||||
user = github_register(username=user_info.username,
|
||||
email=email,
|
||||
full_name=user_info.full_name,
|
||||
github_id=user_info.id,
|
||||
bio=user_info.bio,
|
||||
token=token)
|
||||
data = make_auth_response_data(user)
|
||||
return Response(data, status=status.HTTP_200_OK)
|
||||
|
||||
# Login view: /api/v1/auth
|
||||
def create(self, request, **kwargs):
|
||||
self.check_permissions(request, 'create', None)
|
||||
auth_plugins = get_auth_plugins()
|
||||
|
||||
login_type = request.DATA.get("type", None)
|
||||
invitation_token = request.DATA.get("invitation_token", None)
|
||||
|
||||
if login_type in auth_plugins:
|
||||
data = auth_plugins[login_type]['login_func'](request)
|
||||
if invitation_token:
|
||||
accept_invitation_by_existing_user(invitation_token, data['id'])
|
||||
return response.Ok(data)
|
||||
|
||||
type = request.DATA.get("type", None)
|
||||
if type == "normal":
|
||||
return self._login(request)
|
||||
elif type == "github":
|
||||
return self._github_login(request)
|
||||
raise exc.BadRequest(_("invalid login type"))
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -34,20 +32,19 @@ selfcontained tokens. This trust tokes from external
|
|||
fraudulent modifications.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import re
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils import timezone
|
||||
from datetime import timedelta
|
||||
from taiga.base.api.authentication import BaseAuthentication
|
||||
|
||||
from .tokens import get_user_for_token
|
||||
from django.core import signing
|
||||
from django.db.models import get_model
|
||||
from rest_framework.authentication import BaseAuthentication
|
||||
from taiga.base import exceptions as exc
|
||||
|
||||
|
||||
class Session(BaseAuthentication):
|
||||
"""
|
||||
Session based authentication like the standard
|
||||
`taiga.base.api.authentication.SessionAuthentication`
|
||||
`rest_framework.authentication.SessionAuthentication`
|
||||
but with csrf disabled (for obvious reasons because
|
||||
it is for api.
|
||||
|
||||
|
@ -65,6 +62,39 @@ class Session(BaseAuthentication):
|
|||
return (user, None)
|
||||
|
||||
|
||||
def get_token_for_user(user):
|
||||
"""
|
||||
Generate a new signed token containing
|
||||
a specified user.
|
||||
"""
|
||||
data = {"user_id": user.id}
|
||||
return signing.dumps(data)
|
||||
|
||||
|
||||
def get_user_for_token(token):
|
||||
"""
|
||||
Given a selfcontained token, try parse and
|
||||
unsign it.
|
||||
|
||||
If token passes a validation, returns
|
||||
a user instance corresponding with user_id stored
|
||||
in the incoming token.
|
||||
"""
|
||||
try:
|
||||
data = signing.loads(token)
|
||||
except signing.BadSignature:
|
||||
raise exc.NotAuthenticated("Invalid token")
|
||||
|
||||
model_cls = get_model("users", "User")
|
||||
|
||||
try:
|
||||
user = model_cls.objects.get(pk=data["user_id"])
|
||||
except model_cls.DoesNotExist:
|
||||
raise exc.NotAuthenticated("Invalid token")
|
||||
else:
|
||||
return user
|
||||
|
||||
|
||||
class Token(BaseAuthentication):
|
||||
"""
|
||||
Self-contained stateles authentication implementatrion
|
||||
|
@ -84,14 +114,7 @@ class Token(BaseAuthentication):
|
|||
return None
|
||||
|
||||
token = token_rx_match.group(1)
|
||||
max_age_auth_token = getattr(settings, "MAX_AGE_AUTH_TOKEN", None)
|
||||
user = get_user_for_token(token, "authentication",
|
||||
max_age=max_age_auth_token)
|
||||
|
||||
if user.last_login is None or user.last_login < (timezone.now() - timedelta(minutes=1)):
|
||||
user.last_login = timezone.now()
|
||||
user.save(update_fields=["last_login"])
|
||||
|
||||
user = get_user_for_token(token)
|
||||
return (user, token)
|
||||
|
||||
def authenticate_header(self, request):
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
|
|
@ -0,0 +1,53 @@
|
|||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
from django.core import validators
|
||||
from django.core.exceptions import ValidationError
|
||||
import re
|
||||
|
||||
|
||||
class BaseRegisterSerializer(serializers.Serializer):
|
||||
full_name = serializers.CharField(max_length=256)
|
||||
email = serializers.EmailField(max_length=200)
|
||||
username = serializers.CharField(max_length=30)
|
||||
password = serializers.CharField(min_length=4)
|
||||
|
||||
def validate_username(self, attrs, source):
|
||||
value = attrs[source]
|
||||
validator = validators.RegexValidator(re.compile('^[\w.-]+$'), "invalid username", "invalid")
|
||||
|
||||
try:
|
||||
validator(value)
|
||||
except ValidationError:
|
||||
raise serializers.ValidationError("Required. 30 characters or fewer. Letters, numbers "
|
||||
"and /./-/_ characters'")
|
||||
return attrs
|
||||
|
||||
|
||||
class PublicRegisterSerializer(BaseRegisterSerializer):
|
||||
pass
|
||||
|
||||
|
||||
class PrivateRegisterForNewUserSerializer(BaseRegisterSerializer):
|
||||
token = serializers.CharField(max_length=255, required=True)
|
||||
|
||||
|
||||
class PrivateRegisterForExistingUserSerializer(serializers.Serializer):
|
||||
username = serializers.CharField(max_length=30)
|
||||
password = serializers.CharField(min_length=4)
|
||||
token = serializers.CharField(max_length=255, required=True)
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -25,60 +23,59 @@ should be contained in a class". Because of that, it
|
|||
not uses clasess and uses simple functions.
|
||||
"""
|
||||
|
||||
from django.apps import apps
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db.models.loading import get_model
|
||||
from django.db.models import Q
|
||||
from django.db import transaction as tx
|
||||
from django.db import IntegrityError
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from djmail.template_mail import MagicMailBuilder
|
||||
|
||||
from taiga.base import exceptions as exc
|
||||
from taiga.base.mails import mail_builder
|
||||
from taiga.users.serializers import UserAdminSerializer
|
||||
from taiga.users.serializers import UserSerializer
|
||||
from taiga.users.services import get_and_validate_user
|
||||
|
||||
from .tokens import get_token_for_user
|
||||
from .signals import user_registered as user_registered_signal
|
||||
|
||||
auth_plugins = {}
|
||||
from .backends import get_token_for_user
|
||||
|
||||
|
||||
def register_auth_plugin(name, login_func):
|
||||
auth_plugins[name] = {
|
||||
"login_func": login_func,
|
||||
}
|
||||
|
||||
|
||||
def get_auth_plugins():
|
||||
return auth_plugins
|
||||
|
||||
|
||||
def send_register_email(user) -> bool:
|
||||
def send_public_register_email(user) -> bool:
|
||||
"""
|
||||
Given a user, send register welcome email
|
||||
Given a user, send public register welcome email
|
||||
message to specified user.
|
||||
"""
|
||||
cancel_token = get_token_for_user(user, "cancel_account")
|
||||
context = {"user": user, "cancel_token": cancel_token}
|
||||
email = mail_builder.registered_user(user, context)
|
||||
|
||||
context = {"user": user}
|
||||
mbuilder = MagicMailBuilder()
|
||||
email = mbuilder.public_register_user(user.email, context)
|
||||
return bool(email.send())
|
||||
|
||||
|
||||
def is_user_already_registered(*, username:str, email:str) -> (bool, str):
|
||||
def send_private_register_email(user, **kwargs) -> bool:
|
||||
"""
|
||||
Given a user, send private register welcome
|
||||
email message to specified user.
|
||||
"""
|
||||
context = {"user": user}
|
||||
context.update(kwargs)
|
||||
|
||||
mbuilder = MagicMailBuilder()
|
||||
email = mbuilder.private_register_user(user.email, context)
|
||||
return bool(email.send())
|
||||
|
||||
|
||||
def is_user_already_registred(*, username:str, email:str, github_id:int=None) -> bool:
|
||||
"""
|
||||
Checks if a specified user is already registred.
|
||||
|
||||
Returns a tuple containing a boolean value that indicates if the user exists
|
||||
and in case he does whats the duplicated attribute
|
||||
"""
|
||||
|
||||
user_model = get_user_model()
|
||||
if user_model.objects.filter(username=username):
|
||||
return (True, _("Username is already in use."))
|
||||
user_model = get_model("users", "User")
|
||||
|
||||
if user_model.objects.filter(email=email):
|
||||
return (True, _("Email is already in use."))
|
||||
or_expr = Q(username=username) | Q(email=email)
|
||||
if github_id:
|
||||
or_expr = or_expr | Q(email=email)
|
||||
|
||||
return (False, None)
|
||||
qs = user_model.objects.filter(or_expr)
|
||||
return qs.exists()
|
||||
|
||||
|
||||
def get_membership_by_token(token:str):
|
||||
|
@ -89,10 +86,10 @@ def get_membership_by_token(token:str):
|
|||
If not matches with any membership NotFound exception
|
||||
is raised.
|
||||
"""
|
||||
membership_model = apps.get_model("projects", "Membership")
|
||||
membership_model = get_model("projects", "Membership")
|
||||
qs = membership_model.objects.filter(token=token)
|
||||
if len(qs) == 0:
|
||||
raise exc.NotFound(_("Token not matches any valid invitation."))
|
||||
raise exc.NotFound("Token not matches any valid invitation.")
|
||||
return qs[0]
|
||||
|
||||
|
||||
|
@ -108,37 +105,37 @@ def public_register(username:str, password:str, email:str, full_name:str):
|
|||
:returns: User
|
||||
"""
|
||||
|
||||
is_registered, reason = is_user_already_registered(username=username, email=email)
|
||||
if is_registered:
|
||||
raise exc.WrongArguments(reason)
|
||||
if is_user_already_registred(username=username, email=email):
|
||||
raise exc.IntegrityError("User is already registred.")
|
||||
|
||||
user_model = get_user_model()
|
||||
user_model = get_model("users", "User")
|
||||
user = user_model(username=username,
|
||||
email=email,
|
||||
full_name=full_name,
|
||||
read_new_terms=True)
|
||||
full_name=full_name)
|
||||
user.set_password(password)
|
||||
try:
|
||||
user.save()
|
||||
except IntegrityError:
|
||||
raise exc.WrongArguments(_("User is already registered."))
|
||||
|
||||
send_register_email(user)
|
||||
user_registered_signal.send(sender=user.__class__, user=user)
|
||||
# send_public_register_email(user)
|
||||
return user
|
||||
|
||||
|
||||
@tx.atomic
|
||||
def accept_invitation_by_existing_user(token:str, user_id:int):
|
||||
user_model = get_user_model()
|
||||
user = user_model.objects.get(id=user_id)
|
||||
def private_register_for_existing_user(token:str, username:str, password:str):
|
||||
"""
|
||||
Register works not only for register users, also serves for accept
|
||||
inviatations for projects as existing user.
|
||||
|
||||
Given a invitation token with parsed parameters, accept inviation
|
||||
as existing user.
|
||||
"""
|
||||
|
||||
user = get_and_validate_user(username=username, password=password)
|
||||
membership = get_membership_by_token(token)
|
||||
|
||||
try:
|
||||
membership.user = user
|
||||
membership.save(update_fields=["user"])
|
||||
except IntegrityError:
|
||||
raise exc.IntegrityError(_("This user is already a member of the project."))
|
||||
|
||||
# send_private_register_email(user)
|
||||
return user
|
||||
|
||||
|
||||
|
@ -149,11 +146,10 @@ def private_register_for_new_user(token:str, username:str, email:str,
|
|||
Given a inviation token, try register new user matching
|
||||
the invitation token.
|
||||
"""
|
||||
is_registered, reason = is_user_already_registered(username=username, email=email)
|
||||
if is_registered:
|
||||
raise exc.WrongArguments(reason)
|
||||
if is_user_already_registred(username=username, email=email):
|
||||
raise exc.WrongArguments(_("Username or Email is already in use."))
|
||||
|
||||
user_model = get_user_model()
|
||||
user_model = get_model("users", "User")
|
||||
user = user_model(username=username,
|
||||
email=email,
|
||||
full_name=full_name)
|
||||
|
@ -162,13 +158,35 @@ def private_register_for_new_user(token:str, username:str, email:str,
|
|||
try:
|
||||
user.save()
|
||||
except IntegrityError:
|
||||
raise exc.WrongArguments(_("Error on creating new user."))
|
||||
raise exc.IntegrityError(_("Error on creating new user."))
|
||||
|
||||
membership = get_membership_by_token(token)
|
||||
membership.user = user
|
||||
membership.save(update_fields=["user"])
|
||||
send_register_email(user)
|
||||
user_registered_signal.send(sender=user.__class__, user=user)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@tx.atomic
|
||||
def github_register(username:str, email:str, full_name:str, github_id:int, bio:str, token:str=None):
|
||||
"""
|
||||
Register a new user from github.
|
||||
|
||||
This can raise `exc.IntegrityError` exceptions in
|
||||
case of conflics found.
|
||||
|
||||
:returns: User
|
||||
"""
|
||||
user_model = get_model("users", "User")
|
||||
user, created = user_model.objects.get_or_create(github_id=github_id,
|
||||
defaults={"username": username,
|
||||
"email": email,
|
||||
"full_name": full_name,
|
||||
"bio": bio})
|
||||
if token:
|
||||
membership = get_membership_by_token(token)
|
||||
membership.user = user
|
||||
membership.save(update_fields=["user"])
|
||||
|
||||
return user
|
||||
|
||||
|
@ -179,19 +197,7 @@ def make_auth_response_data(user) -> dict:
|
|||
using python dict containing a representation
|
||||
of the logged user.
|
||||
"""
|
||||
serializer = UserAdminSerializer(user)
|
||||
serializer = UserSerializer(user)
|
||||
data = dict(serializer.data)
|
||||
data["auth_token"] = get_token_for_user(user, "authentication")
|
||||
data["auth_token"] = get_token_for_user(user)
|
||||
return data
|
||||
|
||||
|
||||
def normal_login_func(request):
|
||||
username = request.DATA.get('username', None)
|
||||
password = request.DATA.get('password', None)
|
||||
|
||||
user = get_and_validate_user(username=username, password=password)
|
||||
data = make_auth_response_data(user)
|
||||
return data
|
||||
|
||||
|
||||
register_auth_plugin("normal", normal_login_func)
|
||||
|
|
|
@ -1,22 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import django.dispatch
|
||||
|
||||
|
||||
user_registered = django.dispatch.Signal(providing_args=["user"])
|
|
@ -1,46 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from taiga.base import throttling
|
||||
|
||||
|
||||
class LoginFailRateThrottle(throttling.GlobalThrottlingMixin, throttling.ThrottleByActionMixin, throttling.SimpleRateThrottle):
|
||||
scope = "login-fail"
|
||||
throttled_actions = ["create"]
|
||||
|
||||
def throttle_success(self, request, view):
|
||||
return True
|
||||
|
||||
def finalize(self, request, response, view):
|
||||
if response.status_code == 400:
|
||||
self.history.insert(0, self.now)
|
||||
self.cache.set(self.key, self.history, self.duration)
|
||||
|
||||
|
||||
class RegisterSuccessRateThrottle(throttling.GlobalThrottlingMixin, throttling.ThrottleByActionMixin, throttling.SimpleRateThrottle):
|
||||
scope = "register-success"
|
||||
throttled_actions = ["register"]
|
||||
|
||||
def throttle_success(self, request, view):
|
||||
return True
|
||||
|
||||
def finalize(self, request, response, view):
|
||||
if response.status_code == 201:
|
||||
self.history.insert(0, self.now)
|
||||
self.cache.set(self.key, self.history, self.duration)
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
from django.contrib.auth import get_user_model
|
||||
from taiga.base import exceptions as exc
|
||||
|
||||
from django.apps import apps
|
||||
from django.core import signing
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
|
||||
def get_token_for_user(user, scope):
|
||||
"""
|
||||
Generate a new signed token containing
|
||||
a specified user limited for a scope (identified as a string).
|
||||
"""
|
||||
data = {"user_%s_id" % (scope): user.id}
|
||||
return signing.dumps(data)
|
||||
|
||||
|
||||
def get_user_for_token(token, scope, max_age=None):
|
||||
"""
|
||||
Given a selfcontained token and a scope try to parse and
|
||||
unsign it.
|
||||
|
||||
If max_age is specified it checks token expiration.
|
||||
|
||||
If token passes a validation, returns
|
||||
a user instance corresponding with user_id stored
|
||||
in the incoming token.
|
||||
"""
|
||||
try:
|
||||
data = signing.loads(token, max_age=max_age)
|
||||
except signing.BadSignature:
|
||||
raise exc.NotAuthenticated(_("Invalid token"))
|
||||
|
||||
model_cls = get_user_model()
|
||||
|
||||
try:
|
||||
user = model_cls.objects.get(pk=data["user_%s_id" % (scope)])
|
||||
except (model_cls.DoesNotExist, KeyError):
|
||||
raise exc.NotAuthenticated(_("Invalid token"))
|
||||
else:
|
||||
return user
|
|
@ -1,52 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from django.core import validators as core_validators
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from taiga.base.api import serializers
|
||||
from taiga.base.api import validators
|
||||
from taiga.base.exceptions import ValidationError
|
||||
|
||||
import re
|
||||
|
||||
|
||||
class BaseRegisterValidator(validators.Validator):
|
||||
full_name = serializers.CharField(max_length=256)
|
||||
email = serializers.EmailField(max_length=255)
|
||||
username = serializers.CharField(max_length=255)
|
||||
password = serializers.CharField(min_length=4)
|
||||
|
||||
def validate_username(self, attrs, source):
|
||||
value = attrs[source]
|
||||
validator = core_validators.RegexValidator(re.compile('^[\w.-]+$'), _("invalid username"), "invalid")
|
||||
|
||||
try:
|
||||
validator(value)
|
||||
except ValidationError:
|
||||
raise ValidationError(_("Required. 255 characters or fewer. Letters, numbers "
|
||||
"and /./-/_ characters'"))
|
||||
return attrs
|
||||
|
||||
|
||||
class PublicRegisterValidator(BaseRegisterValidator):
|
||||
pass
|
||||
|
||||
|
||||
class PrivateRegisterValidator(BaseRegisterValidator):
|
||||
token = serializers.CharField(max_length=255, required=True)
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,51 +14,15 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# This code is partially taken from django-rest-framework:
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
VERSION = "2.3.13-taiga" # Based on django-resframework 2.3.13
|
||||
|
||||
# Header encoding (see RFC5987)
|
||||
HTTP_HEADER_ENCODING = 'iso-8859-1'
|
||||
|
||||
# Default datetime input and output formats
|
||||
ISO_8601 = 'iso-8601'
|
||||
|
||||
|
||||
from .viewsets import ModelListViewSet
|
||||
from .viewsets import ModelCrudViewSet
|
||||
from .viewsets import ModelUpdateRetrieveViewSet
|
||||
from .viewsets import GenericViewSet
|
||||
from .viewsets import ReadOnlyListViewSet
|
||||
from .viewsets import ModelRetrieveViewSet
|
||||
|
||||
__all__ = ["ModelCrudViewSet",
|
||||
"ModelListViewSet",
|
||||
"ModelUpdateRetrieveViewSet",
|
||||
"GenericViewSet",
|
||||
"ReadOnlyListViewSet",
|
||||
"ModelRetrieveViewSet"]
|
||||
"ReadOnlyListViewSet"]
|
||||
|
|
|
@ -1,173 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Provides various authentication policies.
|
||||
"""
|
||||
import base64
|
||||
|
||||
from django.contrib.auth import authenticate
|
||||
from django.middleware.csrf import CsrfViewMiddleware
|
||||
|
||||
from taiga.base import exceptions
|
||||
|
||||
from . import HTTP_HEADER_ENCODING
|
||||
|
||||
|
||||
def get_authorization_header(request):
|
||||
"""
|
||||
Return request's 'Authorization:' header, as a bytestring.
|
||||
|
||||
Hide some test client ickyness where the header can be unicode.
|
||||
"""
|
||||
auth = request.META.get('HTTP_AUTHORIZATION', b'')
|
||||
if type(auth) == type(''):
|
||||
# Work around django test client oddness
|
||||
auth = auth.encode(HTTP_HEADER_ENCODING)
|
||||
return auth
|
||||
|
||||
|
||||
class CSRFCheck(CsrfViewMiddleware):
|
||||
def _reject(self, request, reason):
|
||||
# Return the failure reason instead of an HttpResponse
|
||||
return reason
|
||||
|
||||
|
||||
class BaseAuthentication(object):
|
||||
"""
|
||||
All authentication classes should extend BaseAuthentication.
|
||||
"""
|
||||
|
||||
def authenticate(self, request):
|
||||
"""
|
||||
Authenticate the request and return a two-tuple of (user, token).
|
||||
"""
|
||||
raise NotImplementedError(".authenticate() must be overridden.")
|
||||
|
||||
def authenticate_header(self, request):
|
||||
"""
|
||||
Return a string to be used as the value of the `WWW-Authenticate`
|
||||
header in a `401 Unauthenticated` response, or `None` if the
|
||||
authentication scheme should return `403 Permission Denied` responses.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class BasicAuthentication(BaseAuthentication):
|
||||
"""
|
||||
HTTP Basic authentication against username/password.
|
||||
"""
|
||||
www_authenticate_realm = 'api'
|
||||
|
||||
def authenticate(self, request):
|
||||
"""
|
||||
Returns a `User` if a correct username and password have been supplied
|
||||
using HTTP Basic authentication. Otherwise returns `None`.
|
||||
"""
|
||||
auth = get_authorization_header(request).split()
|
||||
|
||||
if not auth or auth[0].lower() != b'basic':
|
||||
return None
|
||||
|
||||
if len(auth) == 1:
|
||||
msg = 'Invalid basic header. No credentials provided.'
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
elif len(auth) > 2:
|
||||
msg = 'Invalid basic header. Credentials string should not contain spaces.'
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
|
||||
try:
|
||||
auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
|
||||
except (TypeError, UnicodeDecodeError):
|
||||
msg = 'Invalid basic header. Credentials not correctly base64 encoded'
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
|
||||
userid, password = auth_parts[0], auth_parts[2]
|
||||
return self.authenticate_credentials(userid, password)
|
||||
|
||||
def authenticate_credentials(self, userid, password):
|
||||
"""
|
||||
Authenticate the userid and password against username and password.
|
||||
"""
|
||||
user = authenticate(username=userid, password=password)
|
||||
if user is None or not user.is_active:
|
||||
raise exceptions.AuthenticationFailed('Invalid username/password')
|
||||
return (user, None)
|
||||
|
||||
def authenticate_header(self, request):
|
||||
return 'Basic realm="%s"' % self.www_authenticate_realm
|
||||
|
||||
|
||||
class SessionAuthentication(BaseAuthentication):
|
||||
"""
|
||||
Use Django's session framework for authentication.
|
||||
"""
|
||||
|
||||
def authenticate(self, request):
|
||||
"""
|
||||
Returns a `User` if the request session currently has a logged in user.
|
||||
Otherwise returns `None`.
|
||||
"""
|
||||
|
||||
# Get the underlying HttpRequest object
|
||||
request = request._request
|
||||
user = getattr(request, 'user', None)
|
||||
|
||||
# Unauthenticated, CSRF validation not required
|
||||
if not user or not user.is_active:
|
||||
return None
|
||||
|
||||
self.enforce_csrf(request)
|
||||
|
||||
# CSRF passed with authenticated user
|
||||
return (user, None)
|
||||
|
||||
def enforce_csrf(self, request):
|
||||
"""
|
||||
Enforce CSRF validation for session based authentication.
|
||||
"""
|
||||
reason = CSRFCheck().process_view(request, None, (), {})
|
||||
if reason:
|
||||
# CSRF failed, bail with explicit error message
|
||||
raise exceptions.AuthenticationFailed('CSRF Failed: %s' % reason)
|
File diff suppressed because it is too large
Load Diff
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,44 +14,49 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# This code is partially taken from django-rest-framework:
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
import warnings
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
|
||||
from django.core.paginator import Paginator, InvalidPage
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404 as _get_object_or_404
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from rest_framework import exceptions
|
||||
from rest_framework.request import clone_request
|
||||
from rest_framework.settings import api_settings
|
||||
|
||||
from . import views
|
||||
from . import mixins
|
||||
from . import pagination
|
||||
from .settings import api_settings
|
||||
from .utils import get_object_or_404
|
||||
|
||||
|
||||
class GenericAPIView(pagination.PaginationMixin,
|
||||
views.APIView):
|
||||
def strict_positive_int(integer_string, cutoff=None):
|
||||
"""
|
||||
Cast a string to a strictly positive integer.
|
||||
"""
|
||||
ret = int(integer_string)
|
||||
if ret <= 0:
|
||||
raise ValueError()
|
||||
if cutoff:
|
||||
ret = min(ret, cutoff)
|
||||
return ret
|
||||
|
||||
|
||||
def get_object_or_404(queryset, *filter_args, **filter_kwargs):
|
||||
"""
|
||||
Same as Django's standard shortcut, but make sure to raise 404
|
||||
if the filter_kwargs don't match the required types.
|
||||
"""
|
||||
try:
|
||||
return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
|
||||
except (TypeError, ValueError):
|
||||
raise Http404
|
||||
|
||||
|
||||
class GenericAPIView(views.APIView):
|
||||
"""
|
||||
Base class for all other generic views.
|
||||
"""
|
||||
|
@ -62,7 +65,6 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
# or override `get_queryset()`/`get_serializer_class()`.
|
||||
queryset = None
|
||||
serializer_class = None
|
||||
validator_class = None
|
||||
|
||||
# This shortcut may be used instead of setting either or both
|
||||
# of the `queryset`/`serializer_class` attributes, although using
|
||||
|
@ -74,13 +76,20 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
lookup_field = 'pk'
|
||||
lookup_url_kwarg = None
|
||||
|
||||
# Pagination settings
|
||||
paginate_by = api_settings.PAGINATE_BY
|
||||
paginate_by_param = api_settings.PAGINATE_BY_PARAM
|
||||
max_paginate_by = api_settings.MAX_PAGINATE_BY
|
||||
pagination_serializer_class = api_settings.DEFAULT_PAGINATION_SERIALIZER_CLASS
|
||||
page_kwarg = 'page'
|
||||
|
||||
# The filter backend classes to use for queryset filtering
|
||||
filter_backends = api_settings.DEFAULT_FILTER_BACKENDS
|
||||
|
||||
# The following attributes may be subject to change,
|
||||
# and should be considered private API.
|
||||
model_serializer_class = api_settings.DEFAULT_MODEL_SERIALIZER_CLASS
|
||||
model_validator_class = api_settings.DEFAULT_MODEL_VALIDATOR_CLASS
|
||||
paginator_class = Paginator
|
||||
|
||||
######################################
|
||||
# These are pending deprecation...
|
||||
|
@ -90,7 +99,7 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
slug_field = 'slug'
|
||||
allow_empty = True
|
||||
|
||||
def get_extra_context(self):
|
||||
def get_serializer_context(self):
|
||||
"""
|
||||
Extra context provided to the serializer class.
|
||||
"""
|
||||
|
@ -103,26 +112,80 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
def get_serializer(self, instance=None, data=None,
|
||||
files=None, many=False, partial=False):
|
||||
"""
|
||||
Return the serializer instance that should be used for deserializing
|
||||
input, and for serializing output.
|
||||
Return the serializer instance that should be used for validating and
|
||||
deserializing input, and for serializing output.
|
||||
"""
|
||||
serializer_class = self.get_serializer_class()
|
||||
context = self.get_extra_context()
|
||||
context = self.get_serializer_context()
|
||||
return serializer_class(instance, data=data, files=files,
|
||||
many=many, partial=partial, context=context)
|
||||
|
||||
def get_validator(self, instance=None, data=None,
|
||||
files=None, many=False, partial=False):
|
||||
def get_pagination_serializer(self, page):
|
||||
"""
|
||||
Return the validator instance that should be used for validating the
|
||||
input, and for serializing output.
|
||||
Return a serializer instance to use with paginated data.
|
||||
"""
|
||||
validator_class = self.get_validator_class()
|
||||
context = self.get_extra_context()
|
||||
return validator_class(instance, data=data, files=files,
|
||||
many=many, partial=partial, context=context)
|
||||
class SerializerClass(self.pagination_serializer_class):
|
||||
class Meta:
|
||||
object_serializer_class = self.get_serializer_class()
|
||||
|
||||
def filter_queryset(self, queryset, filter_backends=None):
|
||||
pagination_serializer_class = SerializerClass
|
||||
context = self.get_serializer_context()
|
||||
return pagination_serializer_class(instance=page, context=context)
|
||||
|
||||
def paginate_queryset(self, queryset, page_size=None):
|
||||
"""
|
||||
Paginate a queryset if required, either returning a page object,
|
||||
or `None` if pagination is not configured for this view.
|
||||
"""
|
||||
deprecated_style = False
|
||||
if page_size is not None:
|
||||
warnings.warn('The `page_size` parameter to `paginate_queryset()` '
|
||||
'is due to be deprecated. '
|
||||
'Note that the return style of this method is also '
|
||||
'changed, and will simply return a page object '
|
||||
'when called without a `page_size` argument.',
|
||||
PendingDeprecationWarning, stacklevel=2)
|
||||
deprecated_style = True
|
||||
else:
|
||||
# Determine the required page size.
|
||||
# If pagination is not configured, simply return None.
|
||||
page_size = self.get_paginate_by()
|
||||
if not page_size:
|
||||
return None
|
||||
|
||||
if not self.allow_empty:
|
||||
warnings.warn(
|
||||
'The `allow_empty` parameter is due to be deprecated. '
|
||||
'To use `allow_empty=False` style behavior, You should override '
|
||||
'`get_queryset()` and explicitly raise a 404 on empty querysets.',
|
||||
PendingDeprecationWarning, stacklevel=2
|
||||
)
|
||||
|
||||
paginator = self.paginator_class(queryset, page_size,
|
||||
allow_empty_first_page=self.allow_empty)
|
||||
page_kwarg = self.kwargs.get(self.page_kwarg)
|
||||
page_query_param = self.request.QUERY_PARAMS.get(self.page_kwarg)
|
||||
page = page_kwarg or page_query_param or 1
|
||||
try:
|
||||
page_number = paginator.validate_number(page)
|
||||
except InvalidPage:
|
||||
if page == 'last':
|
||||
page_number = paginator.num_pages
|
||||
else:
|
||||
raise Http404(_("Page is not 'last', nor can it be converted to an int."))
|
||||
try:
|
||||
page = paginator.page(page_number)
|
||||
except InvalidPage as e:
|
||||
raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
|
||||
'page_number': page_number,
|
||||
'message': str(e)
|
||||
})
|
||||
|
||||
if deprecated_style:
|
||||
return (paginator, page, page.object_list, page.has_other_pages())
|
||||
return page
|
||||
|
||||
def filter_queryset(self, queryset):
|
||||
"""
|
||||
Given a queryset, filter it with whichever filter backend is in use.
|
||||
|
||||
|
@ -131,10 +194,7 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
method if you want to apply the configured filtering backend to the
|
||||
default queryset.
|
||||
"""
|
||||
# NOTE TAIGA: Added filter_backends to overwrite the default behavior.
|
||||
|
||||
backends = filter_backends or self.get_filter_backends()
|
||||
for backend in backends:
|
||||
for backend in self.get_filter_backends():
|
||||
queryset = backend().filter_queryset(self.request, queryset, self)
|
||||
return queryset
|
||||
|
||||
|
@ -144,16 +204,39 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
"""
|
||||
filter_backends = self.filter_backends or []
|
||||
if not filter_backends and hasattr(self, 'filter_backend'):
|
||||
raise RuntimeError('The `filter_backend` attribute and `FILTER_BACKEND` setting '
|
||||
raise RuntimeException('The `filter_backend` attribute and `FILTER_BACKEND` setting '
|
||||
'are due to be deprecated in favor of a `filter_backends` '
|
||||
'attribute and `DEFAULT_FILTER_BACKENDS` setting, that take '
|
||||
'a *list* of filter backend classes.')
|
||||
return filter_backends
|
||||
|
||||
###########################################################
|
||||
# The following methods provide default implementations #
|
||||
# that you may want to override for more complex cases. #
|
||||
###########################################################
|
||||
|
||||
########################
|
||||
### The following methods provide default implementations
|
||||
### that you may want to override for more complex cases.
|
||||
|
||||
def get_paginate_by(self, queryset=None):
|
||||
"""
|
||||
Return the size of pages to use with pagination.
|
||||
|
||||
If `PAGINATE_BY_PARAM` is set it will attempt to get the page size
|
||||
from a named query parameter in the url, eg. ?page_size=100
|
||||
|
||||
Otherwise defaults to using `self.paginate_by`.
|
||||
"""
|
||||
if queryset is not None:
|
||||
raise RuntimeException('The `queryset` parameter to `get_paginate_by()` '
|
||||
'is due to be deprecated.')
|
||||
if self.paginate_by_param:
|
||||
try:
|
||||
return strict_positive_int(
|
||||
self.request.QUERY_PARAMS[self.paginate_by_param],
|
||||
cutoff=self.max_paginate_by
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.paginate_by
|
||||
|
||||
def get_serializer_class(self):
|
||||
if self.action == "list" and hasattr(self, "list_serializer_class"):
|
||||
|
@ -163,31 +246,17 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
if serializer_class is not None:
|
||||
return serializer_class
|
||||
|
||||
assert self.model is not None, ("'%s' should either include a 'serializer_class' attribute, "
|
||||
"or use the 'model' attribute as a shortcut for "
|
||||
"automatically generating a serializer class." % self.__class__.__name__)
|
||||
assert self.model is not None, \
|
||||
"'%s' should either include a 'serializer_class' attribute, " \
|
||||
"or use the 'model' attribute as a shortcut for " \
|
||||
"automatically generating a serializer class." \
|
||||
% self.__class__.__name__
|
||||
|
||||
class DefaultSerializer(self.model_serializer_class):
|
||||
class Meta:
|
||||
model = self.model
|
||||
return DefaultSerializer
|
||||
|
||||
def get_validator_class(self):
|
||||
validator_class = self.validator_class
|
||||
serializer_class = self.get_serializer_class()
|
||||
|
||||
# Situations where the validator is the rest framework serializer
|
||||
if validator_class is None and serializer_class is not None:
|
||||
return serializer_class
|
||||
|
||||
if validator_class is not None:
|
||||
return validator_class
|
||||
|
||||
class DefaultValidator(self.model_validator_class):
|
||||
class Meta:
|
||||
model = self.model
|
||||
return DefaultValidator
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Get the list of items for this view.
|
||||
|
@ -205,7 +274,8 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
if self.model is not None:
|
||||
return self.model._default_manager.all()
|
||||
|
||||
raise ImproperlyConfigured(("'%s' must define 'queryset' or 'model'" % self.__class__.__name__))
|
||||
raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
|
||||
% self.__class__.__name__)
|
||||
|
||||
def get_object(self, queryset=None):
|
||||
"""
|
||||
|
@ -221,7 +291,7 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
else:
|
||||
# NOTE: explicit exception for avoid and fix
|
||||
# usage of deprecated way of get_object
|
||||
raise RuntimeError("DEPRECATED")
|
||||
raise RuntimeException("DEPRECATED")
|
||||
|
||||
# Perform the lookup filtering.
|
||||
# Note that `pk` and `slug` are deprecated styles of lookup filtering.
|
||||
|
@ -233,16 +303,18 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
if lookup is not None:
|
||||
filter_kwargs = {self.lookup_field: lookup}
|
||||
elif pk is not None and self.lookup_field == 'pk':
|
||||
raise RuntimeError(('The `pk_url_kwarg` attribute is due to be deprecated. '
|
||||
'Use the `lookup_field` attribute instead'))
|
||||
raise RuntimeException('The `pk_url_kwarg` attribute is due to be deprecated. '
|
||||
'Use the `lookup_field` attribute instead')
|
||||
elif slug is not None and self.lookup_field == 'pk':
|
||||
raise RuntimeError(('The `slug_url_kwarg` attribute is due to be deprecated. '
|
||||
'Use the `lookup_field` attribute instead'))
|
||||
raise RuntimeException('The `slug_url_kwarg` attribute is due to be deprecated. '
|
||||
'Use the `lookup_field` attribute instead')
|
||||
else:
|
||||
raise ImproperlyConfigured(('Expected view %s to be called with a URL keyword argument '
|
||||
raise ImproperlyConfigured(
|
||||
'Expected view %s to be called with a URL keyword argument '
|
||||
'named "%s". Fix your URL conf, or set the `.lookup_field` '
|
||||
'attribute on the view correctly.' %
|
||||
(self.__class__.__name__, self.lookup_field)))
|
||||
(self.__class__.__name__, self.lookup_field)
|
||||
)
|
||||
|
||||
obj = get_object_or_404(queryset, **filter_kwargs)
|
||||
return obj
|
||||
|
@ -253,13 +325,12 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
except Http404:
|
||||
return None
|
||||
|
||||
###################################################
|
||||
# The following are placeholder methods, #
|
||||
# and are intended to be overridden. #
|
||||
# #
|
||||
# The are not called by GenericAPIView directly, #
|
||||
# but are used by the mixin methods. #
|
||||
###################################################
|
||||
########################
|
||||
### The following are placeholder methods,
|
||||
### and are intended to be overridden.
|
||||
###
|
||||
### The are not called by GenericAPIView directly,
|
||||
### but are used by the mixin methods.
|
||||
|
||||
def pre_conditions_on_save(self, obj):
|
||||
"""
|
||||
|
@ -303,11 +374,11 @@ class GenericAPIView(pagination.PaginationMixin,
|
|||
pass
|
||||
|
||||
|
||||
######################################################
|
||||
# Concrete view classes that provide method handlers #
|
||||
# by composing the mixin classes with the base view. #
|
||||
# NOTE: not used by taiga. #
|
||||
######################################################
|
||||
##########################################################
|
||||
### Concrete view classes that provide method handlers ###
|
||||
### by composing the mixin classes with the base view. ###
|
||||
### NOTE: not used by taiga. ###
|
||||
##########################################################
|
||||
|
||||
class CreateAPIView(mixins.CreateModelMixin,
|
||||
GenericAPIView):
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,46 +14,20 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# This code is partially taken from django-rest-framework:
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
import warnings
|
||||
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.http import Http404
|
||||
from django.db import transaction as tx
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from taiga.base import response
|
||||
from taiga.base.exceptions import ValidationError
|
||||
|
||||
from .settings import api_settings
|
||||
from .utils import get_object_or_404
|
||||
|
||||
from .. import exceptions as exc
|
||||
from ..decorators import model_pk_lock
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.request import clone_request
|
||||
from rest_framework.settings import api_settings
|
||||
|
||||
|
||||
def _get_validation_exclusions(obj, pk=None, slug_field=None, lookup_field=None):
|
||||
|
@ -85,26 +57,25 @@ def _get_validation_exclusions(obj, pk=None, slug_field=None, lookup_field=None)
|
|||
return [field.name for field in obj._meta.fields if field.name not in include]
|
||||
|
||||
|
||||
class CreateModelMixin:
|
||||
class CreateModelMixin(object):
|
||||
"""
|
||||
Create a model instance.
|
||||
"""
|
||||
def create(self, request, *args, **kwargs):
|
||||
validator = self.get_validator(data=request.DATA, files=request.FILES)
|
||||
serializer = self.get_serializer(data=request.DATA, files=request.FILES)
|
||||
|
||||
if validator.is_valid():
|
||||
self.check_permissions(request, 'create', validator.object)
|
||||
if serializer.is_valid():
|
||||
self.check_permissions(request, 'create', serializer.object)
|
||||
|
||||
self.pre_save(validator.object)
|
||||
self.pre_conditions_on_save(validator.object)
|
||||
self.object = validator.save(force_insert=True)
|
||||
self.pre_save(serializer.object)
|
||||
self.pre_conditions_on_save(serializer.object)
|
||||
self.object = serializer.save(force_insert=True)
|
||||
self.post_save(self.object, created=True)
|
||||
instance = self.get_queryset().get(id=self.object.id)
|
||||
serializer = self.get_serializer(instance)
|
||||
headers = self.get_success_headers(serializer.data)
|
||||
return response.Created(serializer.data, headers=headers)
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED,
|
||||
headers=headers)
|
||||
|
||||
return response.BadRequest(validator.errors)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def get_success_headers(self, data):
|
||||
try:
|
||||
|
@ -113,7 +84,7 @@ class CreateModelMixin:
|
|||
return {}
|
||||
|
||||
|
||||
class ListModelMixin:
|
||||
class ListModelMixin(object):
|
||||
"""
|
||||
List a queryset.
|
||||
"""
|
||||
|
@ -125,10 +96,12 @@ class ListModelMixin:
|
|||
# Default is to allow empty querysets. This can be altered by setting
|
||||
# `.allow_empty = False`, to raise 404 errors on empty querysets.
|
||||
if not self.allow_empty and not self.object_list:
|
||||
warnings.warn('The `allow_empty` parameter is due to be deprecated. '
|
||||
warnings.warn(
|
||||
'The `allow_empty` parameter is due to be deprecated. '
|
||||
'To use `allow_empty=False` style behavior, You should override '
|
||||
'`get_queryset()` and explicitly raise a 404 on empty querysets.',
|
||||
PendingDeprecationWarning)
|
||||
PendingDeprecationWarning
|
||||
)
|
||||
class_name = self.__class__.__name__
|
||||
error_msg = self.empty_error % {'class_name': class_name}
|
||||
raise Http404(error_msg)
|
||||
|
@ -140,10 +113,10 @@ class ListModelMixin:
|
|||
else:
|
||||
serializer = self.get_serializer(self.object_list, many=True)
|
||||
|
||||
return response.Ok(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class RetrieveModelMixin:
|
||||
class RetrieveModelMixin(object):
|
||||
"""
|
||||
Retrieve a model instance.
|
||||
"""
|
||||
|
@ -156,51 +129,44 @@ class RetrieveModelMixin:
|
|||
raise Http404
|
||||
|
||||
serializer = self.get_serializer(self.object)
|
||||
return response.Ok(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
|
||||
class UpdateModelMixin:
|
||||
class UpdateModelMixin(object):
|
||||
"""
|
||||
Update a model instance.
|
||||
"""
|
||||
|
||||
@tx.atomic
|
||||
@model_pk_lock
|
||||
def update(self, request, *args, **kwargs):
|
||||
partial = kwargs.pop('partial', False)
|
||||
self.object = self.get_object_or_none()
|
||||
|
||||
self.check_permissions(request, 'update', self.object)
|
||||
|
||||
if self.object is None:
|
||||
raise Http404
|
||||
|
||||
validator = self.get_validator(self.object, data=request.DATA,
|
||||
serializer = self.get_serializer(self.object, data=request.DATA,
|
||||
files=request.FILES, partial=partial)
|
||||
|
||||
if not validator.is_valid():
|
||||
return response.BadRequest(validator.errors)
|
||||
if not serializer.is_valid():
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# Hooks
|
||||
try:
|
||||
self.pre_save(validator.object)
|
||||
self.pre_conditions_on_save(validator.object)
|
||||
self.pre_save(serializer.object)
|
||||
self.pre_conditions_on_save(serializer.object)
|
||||
except ValidationError as err:
|
||||
# full_clean on model instance may be called in pre_save,
|
||||
# so we have to handle eventual errors.
|
||||
return response.BadRequest(err.message_dict)
|
||||
return Response(err.message_dict, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
if self.object is None:
|
||||
self.object = validator.save(force_insert=True)
|
||||
self.object = serializer.save(force_insert=True)
|
||||
self.post_save(self.object, created=True)
|
||||
instance = self.get_queryset().get(id=self.object.id)
|
||||
serializer = self.get_serializer(instance)
|
||||
return response.Created(serializer.data)
|
||||
return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
|
||||
self.object = validator.save(force_update=True)
|
||||
self.object = serializer.save(force_update=True)
|
||||
self.post_save(self.object, created=False)
|
||||
instance = self.get_queryset().get(id=self.object.id)
|
||||
serializer = self.get_serializer(instance)
|
||||
return response.Ok(serializer.data)
|
||||
return Response(serializer.data, status=status.HTTP_200_OK)
|
||||
|
||||
def partial_update(self, request, *args, **kwargs):
|
||||
kwargs['partial'] = True
|
||||
|
@ -211,14 +177,14 @@ class UpdateModelMixin:
|
|||
Set any attributes on the object that are implicit in the request.
|
||||
"""
|
||||
# pk and/or slug attributes are implicit in the URL.
|
||||
##lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
|
||||
##lookup = self.kwargs.get(lookup_url_kwarg, None)
|
||||
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
|
||||
lookup = self.kwargs.get(lookup_url_kwarg, None)
|
||||
pk = self.kwargs.get(self.pk_url_kwarg, None)
|
||||
slug = self.kwargs.get(self.slug_url_kwarg, None)
|
||||
slug_field = slug and self.slug_field or None
|
||||
|
||||
##if lookup:
|
||||
## setattr(obj, self.lookup_field, lookup)
|
||||
if lookup:
|
||||
setattr(obj, self.lookup_field, lookup)
|
||||
|
||||
if pk:
|
||||
setattr(obj, 'pk', pk)
|
||||
|
@ -233,12 +199,11 @@ class UpdateModelMixin:
|
|||
obj.full_clean(exclude)
|
||||
|
||||
|
||||
class DestroyModelMixin:
|
||||
class DestroyModelMixin(object):
|
||||
"""
|
||||
Destroy a model instance.
|
||||
"""
|
||||
@tx.atomic
|
||||
@model_pk_lock
|
||||
def destroy(self, request, *args, **kwargs):
|
||||
obj = self.get_object_or_none()
|
||||
self.check_permissions(request, 'destroy', obj)
|
||||
|
@ -250,54 +215,4 @@ class DestroyModelMixin:
|
|||
self.pre_conditions_on_delete(obj)
|
||||
obj.delete()
|
||||
self.post_delete(obj)
|
||||
return response.NoContent()
|
||||
|
||||
|
||||
class NestedViewSetMixin(object):
|
||||
def get_queryset(self):
|
||||
return self._filter_queryset_by_parents_lookups(super().get_queryset())
|
||||
|
||||
def _filter_queryset_by_parents_lookups(self, queryset):
|
||||
parents_query_dict = self._get_parents_query_dict()
|
||||
if parents_query_dict:
|
||||
return queryset.filter(**parents_query_dict)
|
||||
else:
|
||||
return queryset
|
||||
|
||||
def _get_parents_query_dict(self):
|
||||
result = {}
|
||||
for kwarg_name in self.kwargs:
|
||||
query_value = self.kwargs.get(kwarg_name)
|
||||
result[kwarg_name] = query_value
|
||||
return result
|
||||
|
||||
|
||||
## TODO: Move blocked mixind out of the base module because is related to project
|
||||
|
||||
class BlockeableModelMixin:
|
||||
def is_blocked(self, obj):
|
||||
raise NotImplementedError("is_blocked must be overridden")
|
||||
|
||||
def pre_conditions_blocked(self, obj):
|
||||
# Raises permission exception
|
||||
if obj is not None and self.is_blocked(obj):
|
||||
raise exc.Blocked(_("Blocked element"))
|
||||
|
||||
|
||||
class BlockeableSaveMixin(BlockeableModelMixin):
|
||||
def pre_conditions_on_save(self, obj):
|
||||
# Called on create and update calls
|
||||
self.pre_conditions_blocked(obj)
|
||||
super().pre_conditions_on_save(obj)
|
||||
|
||||
|
||||
class BlockeableDeleteMixin():
|
||||
def pre_conditions_on_delete(self, obj):
|
||||
# Called on destroy call
|
||||
self.pre_conditions_blocked(obj)
|
||||
super().pre_conditions_on_delete(obj)
|
||||
|
||||
|
||||
class BlockedByProjectMixin(BlockeableSaveMixin, BlockeableDeleteMixin):
|
||||
def is_blocked(self, obj):
|
||||
return obj.project is not None and obj.project.blocked_code is not None
|
||||
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||
|
|
|
@ -1,136 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Content negotiation deals with selecting an appropriate renderer given the
|
||||
incoming request. Typically this will be based on the request's Accept header.
|
||||
"""
|
||||
|
||||
from django.http import Http404
|
||||
|
||||
from taiga.base import exceptions
|
||||
from .settings import api_settings
|
||||
|
||||
from .utils.mediatypes import order_by_precedence
|
||||
from .utils.mediatypes import media_type_matches
|
||||
from .utils.mediatypes import _MediaType
|
||||
|
||||
|
||||
class BaseContentNegotiation(object):
|
||||
def select_parser(self, request, parsers):
|
||||
raise NotImplementedError(".select_parser() must be implemented")
|
||||
|
||||
def select_renderer(self, request, renderers, format_suffix=None):
|
||||
raise NotImplementedError(".select_renderer() must be implemented")
|
||||
|
||||
|
||||
class DefaultContentNegotiation(BaseContentNegotiation):
|
||||
settings = api_settings
|
||||
|
||||
def select_parser(self, request, parsers):
|
||||
"""
|
||||
Given a list of parsers and a media type, return the appropriate
|
||||
parser to handle the incoming request.
|
||||
"""
|
||||
for parser in parsers:
|
||||
if media_type_matches(parser.media_type, request.content_type):
|
||||
return parser
|
||||
return None
|
||||
|
||||
def select_renderer(self, request, renderers, format_suffix=None):
|
||||
"""
|
||||
Given a request and a list of renderers, return a two-tuple of:
|
||||
(renderer, media type).
|
||||
"""
|
||||
# Allow URL style format override. eg. "?format=json
|
||||
format_query_param = self.settings.URL_FORMAT_OVERRIDE
|
||||
format = format_suffix or request.QUERY_PARAMS.get(format_query_param)
|
||||
|
||||
if format:
|
||||
renderers = self.filter_renderers(renderers, format)
|
||||
|
||||
accepts = self.get_accept_list(request)
|
||||
|
||||
# Check the acceptable media types against each renderer,
|
||||
# attempting more specific media types first
|
||||
# NB. The inner loop here isni't as bad as it first looks :)
|
||||
# Worst case is we"re looping over len(accept_list) * len(self.renderers)
|
||||
for media_type_set in order_by_precedence(accepts):
|
||||
for renderer in renderers:
|
||||
for media_type in media_type_set:
|
||||
if media_type_matches(renderer.media_type, media_type):
|
||||
# Return the most specific media type as accepted.
|
||||
if (_MediaType(renderer.media_type).precedence >
|
||||
_MediaType(media_type).precedence):
|
||||
# Eg client requests "*/*"
|
||||
# Accepted media type is "application/json"
|
||||
return renderer, renderer.media_type
|
||||
else:
|
||||
# Eg client requests "application/json; indent=8"
|
||||
# Accepted media type is "application/json; indent=8"
|
||||
return renderer, media_type
|
||||
|
||||
raise exceptions.NotAcceptable(available_renderers=renderers)
|
||||
|
||||
def filter_renderers(self, renderers, format):
|
||||
"""
|
||||
If there is a ".json" style format suffix, filter the renderers
|
||||
so that we only negotiation against those that accept that format.
|
||||
"""
|
||||
renderers = [renderer for renderer in renderers
|
||||
if renderer.format == format]
|
||||
if not renderers:
|
||||
raise Http404
|
||||
return renderers
|
||||
|
||||
def get_accept_list(self, request):
|
||||
"""
|
||||
Given the incoming request, return a tokenised list of media
|
||||
type strings.
|
||||
|
||||
Allows URL style accept override. eg. "?accept=application/json"
|
||||
"""
|
||||
header = request.META.get("HTTP_ACCEPT", "*/*")
|
||||
header = request.QUERY_PARAMS.get(self.settings.URL_ACCEPT_OVERRIDE, header)
|
||||
return [token.strip() for token in header.split(",")]
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,230 +14,24 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from django.core.paginator import (
|
||||
EmptyPage,
|
||||
Page,
|
||||
PageNotAnInteger,
|
||||
Paginator,
|
||||
InvalidPage,
|
||||
)
|
||||
from django.http import Http404
|
||||
from django.http import QueryDict
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from .settings import api_settings
|
||||
|
||||
from urllib import parse as urlparse
|
||||
|
||||
import warnings
|
||||
from rest_framework.templatetags.rest_framework import replace_query_param
|
||||
|
||||
|
||||
def replace_query_param(url, key, val):
|
||||
"""
|
||||
Given a URL and a key/val pair, set or replace an item in the query
|
||||
parameters of the URL, and return the new URL.
|
||||
"""
|
||||
(scheme, netloc, path, query, fragment) = urlparse.urlsplit(url)
|
||||
query_dict = QueryDict(query).copy()
|
||||
query_dict[key] = val
|
||||
query = query_dict.urlencode()
|
||||
return urlparse.urlunsplit((scheme, netloc, path, query, fragment))
|
||||
|
||||
|
||||
def strict_positive_int(integer_string, cutoff=None):
|
||||
"""
|
||||
Cast a string to a strictly positive integer.
|
||||
"""
|
||||
ret = int(integer_string)
|
||||
if ret <= 0:
|
||||
raise ValueError()
|
||||
if cutoff:
|
||||
ret = min(ret, cutoff)
|
||||
return ret
|
||||
|
||||
|
||||
class CustomPage(Page):
|
||||
"""Handle different number of items on the first page."""
|
||||
|
||||
def start_index(self):
|
||||
"""Return the 1-based index of the first item on this page."""
|
||||
paginator = self.paginator
|
||||
# Special case, return zero if no items.
|
||||
if paginator.count == 0:
|
||||
return 0
|
||||
elif self.number == 1:
|
||||
return 1
|
||||
return (
|
||||
(self.number - 2) * paginator.per_page + paginator.first_page + 1)
|
||||
|
||||
def end_index(self):
|
||||
"""Return the 1-based index of the last item on this page."""
|
||||
paginator = self.paginator
|
||||
# Special case for the last page because there can be orphans.
|
||||
if self.number == paginator.num_pages:
|
||||
return paginator.count
|
||||
return (self.number - 1) * paginator.per_page + paginator.first_page
|
||||
|
||||
|
||||
class LazyPaginator(Paginator):
|
||||
"""Implement lazy pagination."""
|
||||
|
||||
def __init__(self, object_list, per_page, **kwargs):
|
||||
if 'first_page' in kwargs:
|
||||
self.first_page = kwargs.pop('first_page')
|
||||
else:
|
||||
self.first_page = per_page
|
||||
super(LazyPaginator, self).__init__(object_list, per_page, **kwargs)
|
||||
|
||||
def get_current_per_page(self, number):
|
||||
return self.first_page if number == 1 else self.per_page
|
||||
|
||||
def validate_number(self, number):
|
||||
try:
|
||||
number = int(number)
|
||||
except ValueError:
|
||||
raise PageNotAnInteger('That page number is not an integer')
|
||||
if number < 1:
|
||||
raise EmptyPage('That page number is less than 1')
|
||||
return number
|
||||
|
||||
def page(self, number):
|
||||
number = self.validate_number(number)
|
||||
current_per_page = self.get_current_per_page(number)
|
||||
if number == 1:
|
||||
bottom = 0
|
||||
else:
|
||||
bottom = ((number - 2) * self.per_page + self.first_page)
|
||||
top = bottom + current_per_page
|
||||
# Retrieve more objects to check if there is a next page.
|
||||
objects = list(self.object_list[bottom:top + self.orphans + 1])
|
||||
objects_count = len(objects)
|
||||
if objects_count > (current_per_page + self.orphans):
|
||||
# If another page is found, increase the total number of pages.
|
||||
self._num_pages = number + 1
|
||||
# In any case, return only objects for this page.
|
||||
objects = objects[:current_per_page]
|
||||
elif (number != 1) and (objects_count <= self.orphans):
|
||||
raise EmptyPage('That page contains no results')
|
||||
else:
|
||||
# This is the last page.
|
||||
self._num_pages = number
|
||||
return Page(objects, number, self)
|
||||
|
||||
def _get_count(self):
|
||||
raise NotImplementedError
|
||||
|
||||
count = property(_get_count)
|
||||
|
||||
def _get_num_pages(self):
|
||||
return self._num_pages
|
||||
|
||||
num_pages = property(_get_num_pages)
|
||||
|
||||
def _get_page_range(self):
|
||||
raise NotImplementedError
|
||||
|
||||
page_range = property(_get_page_range)
|
||||
|
||||
|
||||
class PaginationMixin(object):
|
||||
# Pagination settings
|
||||
paginate_by = api_settings.PAGINATE_BY
|
||||
paginate_by_param = api_settings.PAGINATE_BY_PARAM
|
||||
max_paginate_by = api_settings.MAX_PAGINATE_BY
|
||||
page_kwarg = 'page'
|
||||
paginator_class = Paginator
|
||||
|
||||
def get_paginate_by(self, queryset=None, **kwargs):
|
||||
"""
|
||||
Return the size of pages to use with pagination.
|
||||
|
||||
If `PAGINATE_BY_PARAM` is set it will attempt to get the page size
|
||||
from a named query parameter in the url, eg. ?page_size=100
|
||||
|
||||
Otherwise defaults to using `self.paginate_by`.
|
||||
"""
|
||||
class ConditionalPaginationMixin(object):
|
||||
def get_paginate_by(self, *args, **kwargs):
|
||||
if "HTTP_X_DISABLE_PAGINATION" in self.request.META:
|
||||
return None
|
||||
return super().get_paginate_by(*args, **kwargs)
|
||||
|
||||
if queryset is not None:
|
||||
warnings.warn('The `queryset` parameter to `get_paginate_by()` '
|
||||
'is due to be deprecated.',
|
||||
PendingDeprecationWarning, stacklevel=2)
|
||||
|
||||
if self.paginate_by_param:
|
||||
try:
|
||||
return strict_positive_int(
|
||||
self.request.QUERY_PARAMS[self.paginate_by_param],
|
||||
cutoff=self.max_paginate_by
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.paginate_by
|
||||
|
||||
class HeadersPaginationMixin(object):
|
||||
def paginate_queryset(self, queryset, page_size=None):
|
||||
"""
|
||||
Paginate a queryset if required, either returning a page object,
|
||||
or `None` if pagination is not configured for this view.
|
||||
"""
|
||||
if "HTTP_X_DISABLE_PAGINATION" in self.request.META:
|
||||
return None
|
||||
|
||||
if "HTTP_X_LAZY_PAGINATION" in self.request.META:
|
||||
self.paginator_class = LazyPaginator
|
||||
|
||||
deprecated_style = False
|
||||
if page_size is not None:
|
||||
warnings.warn('The `page_size` parameter to `paginate_queryset()` '
|
||||
'is due to be deprecated. '
|
||||
'Note that the return style of this method is also '
|
||||
'changed, and will simply return a page object '
|
||||
'when called without a `page_size` argument.',
|
||||
PendingDeprecationWarning, stacklevel=2)
|
||||
deprecated_style = True
|
||||
else:
|
||||
# Determine the required page size.
|
||||
# If pagination is not configured, simply return None.
|
||||
page_size = self.get_paginate_by()
|
||||
if not page_size:
|
||||
return None
|
||||
|
||||
if not self.allow_empty:
|
||||
warnings.warn(
|
||||
'The `allow_empty` parameter is due to be deprecated. '
|
||||
'To use `allow_empty=False` style behavior, You should override '
|
||||
'`get_queryset()` and explicitly raise a 404 on empty querysets.',
|
||||
PendingDeprecationWarning, stacklevel=2
|
||||
)
|
||||
|
||||
paginator = self.paginator_class(queryset, page_size,
|
||||
allow_empty_first_page=self.allow_empty)
|
||||
|
||||
page_kwarg = self.kwargs.get(self.page_kwarg)
|
||||
page_query_param = self.request.QUERY_PARAMS.get(self.page_kwarg)
|
||||
page = page_kwarg or page_query_param or 1
|
||||
try:
|
||||
page_number = paginator.validate_number(page)
|
||||
except InvalidPage:
|
||||
if page == 'last':
|
||||
page_number = paginator.num_pages
|
||||
else:
|
||||
raise Http404(_("Page is not 'last', nor can it be converted to an int."))
|
||||
try:
|
||||
page = paginator.page(page_number)
|
||||
except InvalidPage as e:
|
||||
raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
|
||||
'page_number': page_number,
|
||||
'message': str(e)
|
||||
})
|
||||
page = super().paginate_queryset(queryset=queryset, page_size=page_size)
|
||||
|
||||
if page is None:
|
||||
return page
|
||||
|
||||
if not "HTTP_X_LAZY_PAGINATION" in self.request.META:
|
||||
self.headers["x-pagination-count"] = page.paginator.count
|
||||
|
||||
self.headers["x-paginated"] = "true"
|
||||
self.headers["x-paginated-by"] = page.paginator.per_page
|
||||
self.headers["x-pagination-current"] = page.number
|
||||
|
|
|
@ -1,245 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Parsers are used to parse the content of incoming HTTP requests.
|
||||
|
||||
They give us a generic way of being able to handle various media types
|
||||
on the request, such as form content or json encoded data.
|
||||
"""
|
||||
from django.conf import settings
|
||||
from django.core.files.uploadhandler import StopFutureHandlers
|
||||
from django.http import QueryDict
|
||||
from django.http.multipartparser import MultiPartParser as DjangoMultiPartParser
|
||||
from django.http.multipartparser import MultiPartParserError, parse_header, ChunkIter
|
||||
|
||||
from django.utils import six
|
||||
|
||||
from taiga.base.exceptions import ParseError
|
||||
from taiga.base.api import renderers
|
||||
|
||||
import json
|
||||
import datetime
|
||||
import decimal
|
||||
|
||||
|
||||
class DataAndFiles(object):
|
||||
def __init__(self, data, files):
|
||||
self.data = data
|
||||
self.files = files
|
||||
|
||||
|
||||
class BaseParser(object):
|
||||
"""
|
||||
All parsers should extend `BaseParser`, specifying a `media_type`
|
||||
attribute, and overriding the `.parse()` method.
|
||||
"""
|
||||
|
||||
media_type = None
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Given a stream to read from, return the parsed representation.
|
||||
Should return parsed data, or a `DataAndFiles` object consisting of the
|
||||
parsed data and files.
|
||||
"""
|
||||
raise NotImplementedError(".parse() must be overridden.")
|
||||
|
||||
|
||||
class JSONParser(BaseParser):
|
||||
"""
|
||||
Parses JSON-serialized data.
|
||||
"""
|
||||
|
||||
media_type = "application/json"
|
||||
renderer_class = renderers.UnicodeJSONRenderer
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Parses the incoming bytestream as JSON and returns the resulting data.
|
||||
"""
|
||||
parser_context = parser_context or {}
|
||||
encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
|
||||
|
||||
try:
|
||||
data = stream.read().decode(encoding)
|
||||
return json.loads(data)
|
||||
except ValueError as exc:
|
||||
raise ParseError("JSON parse error - %s" % six.text_type(exc))
|
||||
|
||||
|
||||
class FormParser(BaseParser):
|
||||
"""
|
||||
Parser for form data.
|
||||
"""
|
||||
|
||||
media_type = "application/x-www-form-urlencoded"
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Parses the incoming bytestream as a URL encoded form,
|
||||
and returns the resulting QueryDict.
|
||||
"""
|
||||
parser_context = parser_context or {}
|
||||
encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
|
||||
data = QueryDict(stream.read(), encoding=encoding)
|
||||
return data
|
||||
|
||||
|
||||
class MultiPartParser(BaseParser):
|
||||
"""
|
||||
Parser for multipart form data, which may include file data.
|
||||
"""
|
||||
|
||||
media_type = "multipart/form-data"
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Parses the incoming bytestream as a multipart encoded form,
|
||||
and returns a DataAndFiles object.
|
||||
|
||||
`.data` will be a `QueryDict` containing all the form parameters.
|
||||
`.files` will be a `QueryDict` containing all the form files.
|
||||
"""
|
||||
parser_context = parser_context or {}
|
||||
request = parser_context["request"]
|
||||
encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
|
||||
meta = request.META.copy()
|
||||
meta["CONTENT_TYPE"] = media_type
|
||||
upload_handlers = request.upload_handlers
|
||||
|
||||
try:
|
||||
parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding)
|
||||
data, files = parser.parse()
|
||||
return DataAndFiles(data, files)
|
||||
except MultiPartParserError as exc:
|
||||
raise ParseError("Multipart form parse error - %s" % str(exc))
|
||||
|
||||
|
||||
class FileUploadParser(BaseParser):
|
||||
"""
|
||||
Parser for file upload data.
|
||||
"""
|
||||
media_type = "*/*"
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Treats the incoming bytestream as a raw file upload and returns
|
||||
a `DateAndFiles` object.
|
||||
|
||||
`.data` will be None (we expect request body to be a file content).
|
||||
`.files` will be a `QueryDict` containing one "file" element.
|
||||
"""
|
||||
|
||||
parser_context = parser_context or {}
|
||||
request = parser_context["request"]
|
||||
encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
|
||||
meta = request.META
|
||||
upload_handlers = request.upload_handlers
|
||||
filename = self.get_filename(stream, media_type, parser_context)
|
||||
|
||||
# Note that this code is extracted from Django's handling of
|
||||
# file uploads in MultiPartParser.
|
||||
content_type = meta.get("HTTP_CONTENT_TYPE",
|
||||
meta.get("CONTENT_TYPE", ""))
|
||||
try:
|
||||
content_length = int(meta.get("HTTP_CONTENT_LENGTH",
|
||||
meta.get("CONTENT_LENGTH", 0)))
|
||||
except (ValueError, TypeError):
|
||||
content_length = None
|
||||
|
||||
# See if the handler will want to take care of the parsing.
|
||||
for handler in upload_handlers:
|
||||
result = handler.handle_raw_input(None,
|
||||
meta,
|
||||
content_length,
|
||||
None,
|
||||
encoding)
|
||||
if result is not None:
|
||||
return DataAndFiles(None, {"file": result[1]})
|
||||
|
||||
# This is the standard case.
|
||||
possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
|
||||
chunk_size = min([2 ** 31 - 4] + possible_sizes)
|
||||
chunks = ChunkIter(stream, chunk_size)
|
||||
counters = [0] * len(upload_handlers)
|
||||
|
||||
for handler in upload_handlers:
|
||||
try:
|
||||
handler.new_file(None, filename, content_type,
|
||||
content_length, encoding)
|
||||
except StopFutureHandlers:
|
||||
break
|
||||
|
||||
for chunk in chunks:
|
||||
for i, handler in enumerate(upload_handlers):
|
||||
chunk_length = len(chunk)
|
||||
chunk = handler.receive_data_chunk(chunk, counters[i])
|
||||
counters[i] += chunk_length
|
||||
if chunk is None:
|
||||
break
|
||||
|
||||
for i, handler in enumerate(upload_handlers):
|
||||
file_obj = handler.file_complete(counters[i])
|
||||
if file_obj:
|
||||
return DataAndFiles(None, {"file": file_obj})
|
||||
raise ParseError("FileUpload parse error - "
|
||||
"none of upload handlers can handle the stream")
|
||||
|
||||
def get_filename(self, stream, media_type, parser_context):
|
||||
"""
|
||||
Detects the uploaded file name. First searches a "filename" url kwarg.
|
||||
Then tries to parse Content-Disposition header.
|
||||
"""
|
||||
try:
|
||||
return parser_context["kwargs"]["filename"]
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
try:
|
||||
meta = parser_context["request"].META
|
||||
disposition = parse_header(meta["HTTP_CONTENT_DISPOSITION"])
|
||||
return disposition[1]["filename"]
|
||||
except (AttributeError, KeyError):
|
||||
pass
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -18,12 +16,9 @@
|
|||
|
||||
import abc
|
||||
|
||||
from functools import reduce
|
||||
|
||||
from taiga.permissions.services import user_has_perm, is_project_admin
|
||||
from django.apps import apps
|
||||
|
||||
from django.utils.translation import ugettext as _
|
||||
from taiga.base.utils import sequence as sq
|
||||
from taiga.permissions.service import user_has_perm, is_project_owner
|
||||
from django.db.models.loading import get_model
|
||||
|
||||
|
||||
######################################################################
|
||||
|
@ -62,7 +57,7 @@ class ResourcePermission(object):
|
|||
elif inspect.isclass(permset) and issubclass(permset, PermissionComponent):
|
||||
permset = permset()
|
||||
else:
|
||||
raise RuntimeError(_("Invalid permission definition."))
|
||||
raise RuntimeError("Invalid permission definition.")
|
||||
|
||||
if self.global_perms:
|
||||
permset = (self.global_perms & permset)
|
||||
|
@ -111,7 +106,7 @@ class Not(PermissionOperator):
|
|||
super().__init__(component)
|
||||
|
||||
def check_permissions(self, *args, **kwargs):
|
||||
component = self.components[0]
|
||||
component = sq.first(self.components)
|
||||
return (not component.check_permissions(*args, **kwargs))
|
||||
|
||||
|
||||
|
@ -180,17 +175,36 @@ class HasProjectPerm(PermissionComponent):
|
|||
return user_has_perm(request.user, self.project_perm, obj)
|
||||
|
||||
|
||||
class IsProjectAdmin(PermissionComponent):
|
||||
class HasProjectParamAndPerm(PermissionComponent):
|
||||
def __init__(self, perm, *components):
|
||||
self.project_perm = perm
|
||||
super().__init__(*components)
|
||||
|
||||
def check_permissions(self, request, view, obj=None):
|
||||
return is_project_admin(request.user, obj)
|
||||
Project = get_model('projects', 'Project')
|
||||
project_id = request.QUERY_PARAMS.get("project", None)
|
||||
try:
|
||||
project = Project.objects.get(pk=project_id)
|
||||
except Project.DoesNotExist:
|
||||
return False
|
||||
return user_has_perm(request.user, self.project_perm, project)
|
||||
|
||||
|
||||
class IsObjectOwner(PermissionComponent):
|
||||
class HasMandatoryParam(PermissionComponent):
|
||||
def __init__(self, param, *components):
|
||||
self.mandatory_param = param
|
||||
super().__init__(*components)
|
||||
|
||||
def check_permissions(self, request, view, obj=None):
|
||||
if obj.owner is None:
|
||||
param = request.GET.get(self.mandatory_param, None)
|
||||
if param:
|
||||
return True
|
||||
return False
|
||||
|
||||
return obj.owner == request.user
|
||||
|
||||
class IsProjectOwner(PermissionComponent):
|
||||
def check_permissions(self, request, view, obj=None):
|
||||
return is_project_owner(request.user, obj)
|
||||
|
||||
|
||||
######################################################################
|
||||
|
@ -200,10 +214,8 @@ class IsObjectOwner(PermissionComponent):
|
|||
class AllowAnyPermission(ResourcePermission):
|
||||
enought_perms = AllowAny()
|
||||
|
||||
|
||||
class IsAuthenticatedPermission(ResourcePermission):
|
||||
enought_perms = IsAuthenticated()
|
||||
|
||||
|
||||
class TaigaResourcePermission(ResourcePermission):
|
||||
enought_perms = IsSuperUser()
|
||||
|
|
|
@ -1,654 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Serializer fields that deal with relationships.
|
||||
|
||||
These fields allow you to specify the style that should be used to represent
|
||||
model relationships, including hyperlinks, primary keys, or slugs.
|
||||
"""
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch
|
||||
from django import forms
|
||||
from django.db.models.fields import BLANK_CHOICE_DASH
|
||||
from django.forms import widgets
|
||||
from django.forms.models import ModelChoiceIterator
|
||||
from django.utils.encoding import smart_text
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
from .fields import Field, WritableField, get_component, is_simple_callable
|
||||
from .reverse import reverse
|
||||
from taiga.base.exceptions import ValidationError
|
||||
|
||||
import warnings
|
||||
from urllib import parse as urlparse
|
||||
|
||||
|
||||
|
||||
|
||||
##### Relational fields #####
|
||||
|
||||
|
||||
# Not actually Writable, but subclasses may need to be.
|
||||
class RelatedField(WritableField):
|
||||
"""
|
||||
Base class for related model fields.
|
||||
|
||||
This represents a relationship using the unicode representation of the target.
|
||||
"""
|
||||
widget = widgets.Select
|
||||
many_widget = widgets.SelectMultiple
|
||||
form_field_class = forms.ChoiceField
|
||||
many_form_field_class = forms.MultipleChoiceField
|
||||
null_values = (None, "", "None")
|
||||
|
||||
cache_choices = False
|
||||
empty_label = None
|
||||
read_only = True
|
||||
many = False
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
|
||||
# "null" is to be deprecated in favor of "required"
|
||||
if "null" in kwargs:
|
||||
warnings.warn("The `null` keyword argument is deprecated. "
|
||||
"Use the `required` keyword argument instead.",
|
||||
DeprecationWarning, stacklevel=2)
|
||||
kwargs["required"] = not kwargs.pop("null")
|
||||
|
||||
queryset = kwargs.pop("queryset", None)
|
||||
self.many = kwargs.pop("many", self.many)
|
||||
if self.many:
|
||||
self.widget = self.many_widget
|
||||
self.form_field_class = self.many_form_field_class
|
||||
|
||||
kwargs["read_only"] = kwargs.pop("read_only", self.read_only)
|
||||
super(RelatedField, self).__init__(*args, **kwargs)
|
||||
|
||||
if not self.required:
|
||||
self.empty_label = BLANK_CHOICE_DASH[0][1]
|
||||
|
||||
self.queryset = queryset
|
||||
|
||||
def initialize(self, parent, field_name):
|
||||
super(RelatedField, self).initialize(parent, field_name)
|
||||
if self.queryset is None and not self.read_only:
|
||||
manager = getattr(self.parent.opts.model, self.source or field_name)
|
||||
if hasattr(manager, "related"): # Forward
|
||||
self.queryset = manager.related.model._default_manager.all()
|
||||
else: # Reverse
|
||||
self.queryset = manager.field.rel.to._default_manager.all()
|
||||
|
||||
### We need this stuff to make form choices work...
|
||||
|
||||
def prepare_value(self, obj):
|
||||
return self.to_native(obj)
|
||||
|
||||
def label_from_instance(self, obj):
|
||||
"""
|
||||
Return a readable representation for use with eg. select widgets.
|
||||
"""
|
||||
desc = smart_text(obj)
|
||||
ident = smart_text(self.to_native(obj))
|
||||
if desc == ident:
|
||||
return desc
|
||||
return "%s - %s" % (desc, ident)
|
||||
|
||||
def _get_queryset(self):
|
||||
return self._queryset
|
||||
|
||||
def _set_queryset(self, queryset):
|
||||
self._queryset = queryset
|
||||
self.widget.choices = self.choices
|
||||
|
||||
queryset = property(_get_queryset, _set_queryset)
|
||||
|
||||
def _get_choices(self):
|
||||
# If self._choices is set, then somebody must have manually set
|
||||
# the property self.choices. In this case, just return self._choices.
|
||||
if hasattr(self, "_choices"):
|
||||
return self._choices
|
||||
|
||||
# Otherwise, execute the QuerySet in self.queryset to determine the
|
||||
# choices dynamically. Return a fresh ModelChoiceIterator that has not been
|
||||
# consumed. Note that we"re instantiating a new ModelChoiceIterator *each*
|
||||
# time _get_choices() is called (and, thus, each time self.choices is
|
||||
# accessed) so that we can ensure the QuerySet has not been consumed. This
|
||||
# construct might look complicated but it allows for lazy evaluation of
|
||||
# the queryset.
|
||||
return ModelChoiceIterator(self)
|
||||
|
||||
def _set_choices(self, value):
|
||||
# Setting choices also sets the choices on the widget.
|
||||
# choices can be any iterable, but we call list() on it because
|
||||
# it will be consumed more than once.
|
||||
self._choices = self.widget.choices = list(value)
|
||||
|
||||
choices = property(_get_choices, _set_choices)
|
||||
|
||||
### Default value handling
|
||||
|
||||
def get_default_value(self):
|
||||
default = super(RelatedField, self).get_default_value()
|
||||
if self.many and default is None:
|
||||
return []
|
||||
return default
|
||||
|
||||
### Regular serializer stuff...
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
try:
|
||||
if self.source == "*":
|
||||
return self.to_native(obj)
|
||||
|
||||
source = self.source or field_name
|
||||
value = obj
|
||||
|
||||
for component in source.split("."):
|
||||
if value is None:
|
||||
break
|
||||
value = get_component(value, component)
|
||||
except ObjectDoesNotExist:
|
||||
return None
|
||||
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
if self.many:
|
||||
if is_simple_callable(getattr(value, "all", None)):
|
||||
return [self.to_native(item) for item in value.all()]
|
||||
else:
|
||||
# Also support non-queryset iterables.
|
||||
# This allows us to also support plain lists of related items.
|
||||
return [self.to_native(item) for item in value]
|
||||
return self.to_native(value)
|
||||
|
||||
def field_from_native(self, data, files, field_name, into):
|
||||
if self.read_only:
|
||||
return
|
||||
|
||||
try:
|
||||
if self.many:
|
||||
try:
|
||||
# Form data
|
||||
value = data.getlist(field_name)
|
||||
if value == [""] or value == []:
|
||||
raise KeyError
|
||||
except AttributeError:
|
||||
# Non-form data
|
||||
value = data[field_name]
|
||||
else:
|
||||
value = data[field_name]
|
||||
except KeyError:
|
||||
if self.partial:
|
||||
return
|
||||
value = self.get_default_value()
|
||||
|
||||
if value in self.null_values:
|
||||
if self.required:
|
||||
raise ValidationError(self.error_messages["required"])
|
||||
into[(self.source or field_name)] = None
|
||||
elif self.many:
|
||||
into[(self.source or field_name)] = [self.from_native(item) for item in value]
|
||||
else:
|
||||
into[(self.source or field_name)] = self.from_native(value)
|
||||
|
||||
|
||||
### PrimaryKey relationships
|
||||
|
||||
class PrimaryKeyRelatedField(RelatedField):
|
||||
"""
|
||||
Represents a relationship as a pk value.
|
||||
"""
|
||||
read_only = False
|
||||
|
||||
default_error_messages = {
|
||||
"does_not_exist": _("Invalid pk '%s' - object does not exist."),
|
||||
"incorrect_type": _("Incorrect type. Expected pk value, received %s."),
|
||||
}
|
||||
|
||||
# TODO: Remove these field hacks...
|
||||
def prepare_value(self, obj):
|
||||
return self.to_native(obj.pk)
|
||||
|
||||
def label_from_instance(self, obj):
|
||||
"""
|
||||
Return a readable representation for use with eg. select widgets.
|
||||
"""
|
||||
desc = smart_text(obj)
|
||||
ident = smart_text(self.to_native(obj.pk))
|
||||
if desc == ident:
|
||||
return desc
|
||||
return "%s - %s" % (desc, ident)
|
||||
|
||||
# TODO: Possibly change this to just take `obj`, through prob less performant
|
||||
def to_native(self, pk):
|
||||
return pk
|
||||
|
||||
def from_native(self, data):
|
||||
if self.queryset is None:
|
||||
raise Exception("Writable related fields must include a `queryset` argument")
|
||||
|
||||
try:
|
||||
return self.queryset.get(pk=data)
|
||||
except ObjectDoesNotExist:
|
||||
msg = self.error_messages["does_not_exist"] % smart_text(data)
|
||||
raise ValidationError(msg)
|
||||
except (TypeError, ValueError):
|
||||
received = type(data).__name__
|
||||
msg = self.error_messages["incorrect_type"] % received
|
||||
raise ValidationError(msg)
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
if self.many:
|
||||
# To-many relationship
|
||||
|
||||
queryset = None
|
||||
if not self.source:
|
||||
# Prefer obj.serializable_value for performance reasons
|
||||
try:
|
||||
queryset = obj.serializable_value(field_name)
|
||||
except AttributeError:
|
||||
pass
|
||||
if queryset is None:
|
||||
# RelatedManager (reverse relationship)
|
||||
source = self.source or field_name
|
||||
queryset = obj
|
||||
for component in source.split("."):
|
||||
if queryset is None:
|
||||
return []
|
||||
queryset = get_component(queryset, component)
|
||||
|
||||
# Forward relationship
|
||||
if is_simple_callable(getattr(queryset, "all", None)):
|
||||
return [self.to_native(item.pk) for item in queryset.all()]
|
||||
else:
|
||||
# Also support non-queryset iterables.
|
||||
# This allows us to also support plain lists of related items.
|
||||
return [self.to_native(item.pk) for item in queryset]
|
||||
|
||||
# To-one relationship
|
||||
try:
|
||||
# Prefer obj.serializable_value for performance reasons
|
||||
pk = obj.serializable_value(self.source or field_name)
|
||||
except AttributeError:
|
||||
# RelatedObject (reverse relationship)
|
||||
try:
|
||||
pk = getattr(obj, self.source or field_name).pk
|
||||
except (ObjectDoesNotExist, AttributeError):
|
||||
return None
|
||||
|
||||
# Forward relationship
|
||||
return self.to_native(pk)
|
||||
|
||||
|
||||
### Slug relationships
|
||||
|
||||
|
||||
class SlugRelatedField(RelatedField):
|
||||
"""
|
||||
Represents a relationship using a unique field on the target.
|
||||
"""
|
||||
read_only = False
|
||||
|
||||
default_error_messages = {
|
||||
"does_not_exist": _("Object with %s=%s does not exist."),
|
||||
"invalid": _("Invalid value."),
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.slug_field = kwargs.pop("slug_field", None)
|
||||
assert self.slug_field, "slug_field is required"
|
||||
super(SlugRelatedField, self).__init__(*args, **kwargs)
|
||||
|
||||
def to_native(self, obj):
|
||||
return getattr(obj, self.slug_field)
|
||||
|
||||
def from_native(self, data):
|
||||
if self.queryset is None:
|
||||
raise Exception("Writable related fields must include a `queryset` argument")
|
||||
|
||||
try:
|
||||
return self.queryset.get(**{self.slug_field: data})
|
||||
except ObjectDoesNotExist:
|
||||
raise ValidationError(self.error_messages["does_not_exist"] %
|
||||
(self.slug_field, smart_text(data)))
|
||||
except (TypeError, ValueError):
|
||||
msg = self.error_messages["invalid"]
|
||||
raise ValidationError(msg)
|
||||
|
||||
|
||||
### Hyperlinked relationships
|
||||
|
||||
class HyperlinkedRelatedField(RelatedField):
|
||||
"""
|
||||
Represents a relationship using hyperlinking.
|
||||
"""
|
||||
read_only = False
|
||||
lookup_field = "pk"
|
||||
|
||||
default_error_messages = {
|
||||
"no_match": _("Invalid hyperlink - No URL match"),
|
||||
"incorrect_match": _("Invalid hyperlink - Incorrect URL match"),
|
||||
"configuration_error": _("Invalid hyperlink due to configuration error"),
|
||||
"does_not_exist": _("Invalid hyperlink - object does not exist."),
|
||||
"incorrect_type": _("Incorrect type. Expected url string, received %s."),
|
||||
}
|
||||
|
||||
# These are all pending deprecation
|
||||
pk_url_kwarg = "pk"
|
||||
slug_field = "slug"
|
||||
slug_url_kwarg = None # Defaults to same as `slug_field` unless overridden
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
try:
|
||||
self.view_name = kwargs.pop("view_name")
|
||||
except KeyError:
|
||||
raise ValueError("Hyperlinked field requires \"view_name\" kwarg")
|
||||
|
||||
self.lookup_field = kwargs.pop("lookup_field", self.lookup_field)
|
||||
self.format = kwargs.pop("format", None)
|
||||
|
||||
# These are pending deprecation
|
||||
if "pk_url_kwarg" in kwargs:
|
||||
msg = "pk_url_kwarg is pending deprecation. Use lookup_field instead."
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
if "slug_url_kwarg" in kwargs:
|
||||
msg = "slug_url_kwarg is pending deprecation. Use lookup_field instead."
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
if "slug_field" in kwargs:
|
||||
msg = "slug_field is pending deprecation. Use lookup_field instead."
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
|
||||
self.pk_url_kwarg = kwargs.pop("pk_url_kwarg", self.pk_url_kwarg)
|
||||
self.slug_field = kwargs.pop("slug_field", self.slug_field)
|
||||
default_slug_kwarg = self.slug_url_kwarg or self.slug_field
|
||||
self.slug_url_kwarg = kwargs.pop("slug_url_kwarg", default_slug_kwarg)
|
||||
|
||||
super(HyperlinkedRelatedField, self).__init__(*args, **kwargs)
|
||||
|
||||
def get_url(self, obj, view_name, request, format):
|
||||
"""
|
||||
Given an object, return the URL that hyperlinks to the object.
|
||||
|
||||
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
|
||||
attributes are not configured to correctly match the URL conf.
|
||||
"""
|
||||
lookup_field = getattr(obj, self.lookup_field)
|
||||
kwargs = {self.lookup_field: lookup_field}
|
||||
try:
|
||||
return reverse(view_name, kwargs=kwargs, request=request, format=format)
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
if self.pk_url_kwarg != "pk":
|
||||
# Only try pk if it has been explicitly set.
|
||||
# Otherwise, the default `lookup_field = "pk"` has us covered.
|
||||
pk = obj.pk
|
||||
kwargs = {self.pk_url_kwarg: pk}
|
||||
try:
|
||||
return reverse(view_name, kwargs=kwargs, request=request, format=format)
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
slug = getattr(obj, self.slug_field, None)
|
||||
if slug is not None:
|
||||
# Only try slug if it corresponds to an attribute on the object.
|
||||
kwargs = {self.slug_url_kwarg: slug}
|
||||
try:
|
||||
ret = reverse(view_name, kwargs=kwargs, request=request, format=format)
|
||||
if self.slug_field == "slug" and self.slug_url_kwarg == "slug":
|
||||
# If the lookup succeeds using the default slug params,
|
||||
# then `slug_field` is being used implicitly, and we
|
||||
# we need to warn about the pending deprecation.
|
||||
msg = "Implicit slug field hyperlinked fields are pending deprecation." \
|
||||
"You should set `lookup_field=slug` on the HyperlinkedRelatedField."
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
return ret
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
raise NoReverseMatch()
|
||||
|
||||
def get_object(self, queryset, view_name, view_args, view_kwargs):
|
||||
"""
|
||||
Return the object corresponding to a matched URL.
|
||||
|
||||
Takes the matched URL conf arguments, and the queryset, and should
|
||||
return an object instance, or raise an `ObjectDoesNotExist` exception.
|
||||
"""
|
||||
lookup = view_kwargs.get(self.lookup_field, None)
|
||||
pk = view_kwargs.get(self.pk_url_kwarg, None)
|
||||
slug = view_kwargs.get(self.slug_url_kwarg, None)
|
||||
|
||||
if lookup is not None:
|
||||
filter_kwargs = {self.lookup_field: lookup}
|
||||
elif pk is not None:
|
||||
filter_kwargs = {"pk": pk}
|
||||
elif slug is not None:
|
||||
filter_kwargs = {self.slug_field: slug}
|
||||
else:
|
||||
raise ObjectDoesNotExist()
|
||||
|
||||
return queryset.get(**filter_kwargs)
|
||||
|
||||
def to_native(self, obj):
|
||||
view_name = self.view_name
|
||||
request = self.context.get("request", None)
|
||||
format = self.format or self.context.get("format", None)
|
||||
|
||||
if request is None:
|
||||
msg = (
|
||||
"Using `HyperlinkedRelatedField` without including the request "
|
||||
"in the serializer context is deprecated. "
|
||||
"Add `context={'request': request}` when instantiating "
|
||||
"the serializer."
|
||||
)
|
||||
warnings.warn(msg, DeprecationWarning, stacklevel=4)
|
||||
|
||||
# If the object has not yet been saved then we cannot hyperlink to it.
|
||||
if getattr(obj, "pk", None) is None:
|
||||
return
|
||||
|
||||
# Return the hyperlink, or error if incorrectly configured.
|
||||
try:
|
||||
return self.get_url(obj, view_name, request, format)
|
||||
except NoReverseMatch:
|
||||
msg = (
|
||||
"Could not resolve URL for hyperlinked relationship using "
|
||||
"view name '%s'. You may have failed to include the related "
|
||||
"model in your API, or incorrectly configured the "
|
||||
"`lookup_field` attribute on this field."
|
||||
)
|
||||
raise Exception(msg % view_name)
|
||||
|
||||
def from_native(self, value):
|
||||
# Convert URL -> model instance pk
|
||||
# TODO: Use values_list
|
||||
queryset = self.queryset
|
||||
if queryset is None:
|
||||
raise Exception("Writable related fields must include a `queryset` argument")
|
||||
|
||||
try:
|
||||
http_prefix = value.startswith(("http:", "https:"))
|
||||
except AttributeError:
|
||||
msg = self.error_messages["incorrect_type"]
|
||||
raise ValidationError(msg % type(value).__name__)
|
||||
|
||||
if http_prefix:
|
||||
# If needed convert absolute URLs to relative path
|
||||
value = urlparse.urlparse(value).path
|
||||
prefix = get_script_prefix()
|
||||
if value.startswith(prefix):
|
||||
value = "/" + value[len(prefix):]
|
||||
|
||||
try:
|
||||
match = resolve(value)
|
||||
except Exception:
|
||||
raise ValidationError(self.error_messages["no_match"])
|
||||
|
||||
if match.view_name != self.view_name:
|
||||
raise ValidationError(self.error_messages["incorrect_match"])
|
||||
|
||||
try:
|
||||
return self.get_object(queryset, match.view_name,
|
||||
match.args, match.kwargs)
|
||||
except (ObjectDoesNotExist, TypeError, ValueError):
|
||||
raise ValidationError(self.error_messages["does_not_exist"])
|
||||
|
||||
|
||||
class HyperlinkedIdentityField(Field):
|
||||
"""
|
||||
Represents the instance, or a property on the instance, using hyperlinking.
|
||||
"""
|
||||
lookup_field = "pk"
|
||||
read_only = True
|
||||
|
||||
# These are all pending deprecation
|
||||
pk_url_kwarg = "pk"
|
||||
slug_field = "slug"
|
||||
slug_url_kwarg = None # Defaults to same as `slug_field` unless overridden
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
try:
|
||||
self.view_name = kwargs.pop("view_name")
|
||||
except KeyError:
|
||||
msg = "HyperlinkedIdentityField requires \"view_name\" argument"
|
||||
raise ValueError(msg)
|
||||
|
||||
self.format = kwargs.pop("format", None)
|
||||
lookup_field = kwargs.pop("lookup_field", None)
|
||||
self.lookup_field = lookup_field or self.lookup_field
|
||||
|
||||
# These are pending deprecation
|
||||
if "pk_url_kwarg" in kwargs:
|
||||
msg = "pk_url_kwarg is pending deprecation. Use lookup_field instead."
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
if "slug_url_kwarg" in kwargs:
|
||||
msg = "slug_url_kwarg is pending deprecation. Use lookup_field instead."
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
if "slug_field" in kwargs:
|
||||
msg = "slug_field is pending deprecation. Use lookup_field instead."
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
|
||||
self.slug_field = kwargs.pop("slug_field", self.slug_field)
|
||||
default_slug_kwarg = self.slug_url_kwarg or self.slug_field
|
||||
self.pk_url_kwarg = kwargs.pop("pk_url_kwarg", self.pk_url_kwarg)
|
||||
self.slug_url_kwarg = kwargs.pop("slug_url_kwarg", default_slug_kwarg)
|
||||
|
||||
super(HyperlinkedIdentityField, self).__init__(*args, **kwargs)
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
request = self.context.get("request", None)
|
||||
format = self.context.get("format", None)
|
||||
view_name = self.view_name
|
||||
|
||||
if request is None:
|
||||
warnings.warn("Using `HyperlinkedIdentityField` without including the "
|
||||
"request in the serializer context is deprecated. "
|
||||
"Add `context={'request': request}` when instantiating the serializer.",
|
||||
DeprecationWarning, stacklevel=4)
|
||||
|
||||
# By default use whatever format is given for the current context
|
||||
# unless the target is a different type to the source.
|
||||
#
|
||||
# Eg. Consider a HyperlinkedIdentityField pointing from a json
|
||||
# representation to an html property of that representation...
|
||||
#
|
||||
# "/snippets/1/" should link to "/snippets/1/highlight/"
|
||||
# ...but...
|
||||
# "/snippets/1/.json" should link to "/snippets/1/highlight/.html"
|
||||
if format and self.format and self.format != format:
|
||||
format = self.format
|
||||
|
||||
# Return the hyperlink, or error if incorrectly configured.
|
||||
try:
|
||||
return self.get_url(obj, view_name, request, format)
|
||||
except NoReverseMatch:
|
||||
msg = (
|
||||
"Could not resolve URL for hyperlinked relationship using "
|
||||
"view name '%s'. You may have failed to include the related "
|
||||
"model in your API, or incorrectly configured the "
|
||||
"`lookup_field` attribute on this field."
|
||||
)
|
||||
raise Exception(msg % view_name)
|
||||
|
||||
def get_url(self, obj, view_name, request, format):
|
||||
"""
|
||||
Given an object, return the URL that hyperlinks to the object.
|
||||
|
||||
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
|
||||
attributes are not configured to correctly match the URL conf.
|
||||
"""
|
||||
lookup_field = getattr(obj, self.lookup_field, None)
|
||||
kwargs = {self.lookup_field: lookup_field}
|
||||
|
||||
# Handle unsaved object case
|
||||
if lookup_field is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
return reverse(view_name, kwargs=kwargs, request=request, format=format)
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
if self.pk_url_kwarg != "pk":
|
||||
# Only try pk lookup if it has been explicitly set.
|
||||
# Otherwise, the default `lookup_field = "pk"` has us covered.
|
||||
kwargs = {self.pk_url_kwarg: obj.pk}
|
||||
try:
|
||||
return reverse(view_name, kwargs=kwargs, request=request, format=format)
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
slug = getattr(obj, self.slug_field, None)
|
||||
if slug:
|
||||
# Only use slug lookup if a slug field exists on the model
|
||||
kwargs = {self.slug_url_kwarg: slug}
|
||||
try:
|
||||
return reverse(view_name, kwargs=kwargs, request=request, format=format)
|
||||
except NoReverseMatch:
|
||||
pass
|
||||
|
||||
raise NoReverseMatch()
|
|
@ -1,311 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Renderers are used to serialize a response into specific media types.
|
||||
|
||||
They give us a generic way of being able to handle various media types
|
||||
on the response, such as JSON encoded data or HTML output.
|
||||
|
||||
REST framework also provides an HTML renderer the renders the browsable API.
|
||||
"""
|
||||
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.http.multipartparser import parse_header
|
||||
from django.template import RequestContext, loader, Template
|
||||
from django.test.client import encode_multipart
|
||||
from django.utils import six
|
||||
|
||||
from .utils import encoders
|
||||
|
||||
import json
|
||||
|
||||
|
||||
class BaseRenderer(object):
|
||||
"""
|
||||
All renderers should extend this class, setting the `media_type`
|
||||
and `format` attributes, and override the `.render()` method.
|
||||
"""
|
||||
|
||||
media_type = None
|
||||
format = None
|
||||
charset = "utf-8"
|
||||
render_style = "text"
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
raise NotImplemented("Renderer class requires .render() to be implemented")
|
||||
|
||||
|
||||
class JSONRenderer(BaseRenderer):
|
||||
"""
|
||||
Renderer which serializes to JSON.
|
||||
Applies JSON's backslash-u character escaping for non-ascii characters.
|
||||
"""
|
||||
|
||||
media_type = "application/json"
|
||||
format = "json"
|
||||
encoder_class = encoders.JSONEncoder
|
||||
ensure_ascii = True
|
||||
charset = None
|
||||
# JSON is a binary encoding, that can be encoded as utf-8, utf-16 or utf-32.
|
||||
# See: http://www.ietf.org/rfc/rfc4627.txt
|
||||
# Also: http://lucumr.pocoo.org/2013/7/19/application-mimetypes-and-encodings/
|
||||
|
||||
def _get_indent(self, accepted_media_type, renderer_context):
|
||||
# If "indent" is provided in the context, then pretty print the result.
|
||||
# E.g. If we"re being called by the BrowsableAPIRenderer.
|
||||
renderer_context = renderer_context or {}
|
||||
indent = renderer_context.get("indent", None)
|
||||
|
||||
if accepted_media_type:
|
||||
# If the media type looks like "application/json; indent=4",
|
||||
# then pretty print the result.
|
||||
base_media_type, params = parse_header(accepted_media_type.encode("ascii"))
|
||||
indent = params.get("indent", indent)
|
||||
try:
|
||||
indent = max(min(int(indent), 8), 0)
|
||||
except (ValueError, TypeError):
|
||||
indent = None
|
||||
|
||||
return indent
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
"""
|
||||
Render `data` into JSON.
|
||||
"""
|
||||
if data is None:
|
||||
return bytes()
|
||||
|
||||
indent = self._get_indent(accepted_media_type, renderer_context)
|
||||
|
||||
ret = json.dumps(data, cls=self.encoder_class,
|
||||
indent=indent, ensure_ascii=self.ensure_ascii)
|
||||
|
||||
# On python 2.x json.dumps() returns bytestrings if ensure_ascii=True,
|
||||
# but if ensure_ascii=False, the return type is underspecified,
|
||||
# and may (or may not) be unicode.
|
||||
# On python 3.x json.dumps() returns unicode strings.
|
||||
if isinstance(ret, six.text_type):
|
||||
return bytes(ret.encode("utf-8"))
|
||||
return ret
|
||||
|
||||
def render_to_file(self, data, outputfile, accepted_media_type=None, renderer_context=None):
|
||||
"""
|
||||
Render `data` into a file with JSON format.
|
||||
"""
|
||||
if data is None:
|
||||
return bytes()
|
||||
|
||||
indent = self._get_indent(accepted_media_type, renderer_context)
|
||||
|
||||
ret = json.dump(data, outputfile, cls=self.encoder_class,
|
||||
indent=indent, ensure_ascii=self.ensure_ascii)
|
||||
|
||||
|
||||
class UnicodeJSONRenderer(JSONRenderer):
|
||||
ensure_ascii = False
|
||||
"""
|
||||
Renderer which serializes to JSON.
|
||||
Does *not* apply JSON's character escaping for non-ascii characters.
|
||||
"""
|
||||
|
||||
|
||||
class JSONPRenderer(JSONRenderer):
|
||||
"""
|
||||
Renderer which serializes to json,
|
||||
wrapping the json output in a callback function.
|
||||
"""
|
||||
|
||||
media_type = "application/javascript"
|
||||
format = "jsonp"
|
||||
callback_parameter = "callback"
|
||||
default_callback = "callback"
|
||||
charset = "utf-8"
|
||||
|
||||
def get_callback(self, renderer_context):
|
||||
"""
|
||||
Determine the name of the callback to wrap around the json output.
|
||||
"""
|
||||
request = renderer_context.get("request", None)
|
||||
params = request and request.QUERY_PARAMS or {}
|
||||
return params.get(self.callback_parameter, self.default_callback)
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
"""
|
||||
Renders into jsonp, wrapping the json output in a callback function.
|
||||
|
||||
Clients may set the callback function name using a query parameter
|
||||
on the URL, for example: ?callback=exampleCallbackName
|
||||
"""
|
||||
renderer_context = renderer_context or {}
|
||||
callback = self.get_callback(renderer_context)
|
||||
json = super(JSONPRenderer, self).render(data, accepted_media_type,
|
||||
renderer_context)
|
||||
return callback.encode(self.charset) + b"(" + json + b");"
|
||||
|
||||
|
||||
class TemplateHTMLRenderer(BaseRenderer):
|
||||
"""
|
||||
An HTML renderer for use with templates.
|
||||
|
||||
The data supplied to the Response object should be a dictionary that will
|
||||
be used as context for the template.
|
||||
|
||||
The template name is determined by (in order of preference):
|
||||
|
||||
1. An explicit `.template_name` attribute set on the response.
|
||||
2. An explicit `.template_name` attribute set on this class.
|
||||
3. The return result of calling `view.get_template_names()`.
|
||||
|
||||
For example:
|
||||
data = {"users": User.objects.all()}
|
||||
return Response(data, template_name="users.html")
|
||||
|
||||
For pre-rendered HTML, see StaticHTMLRenderer.
|
||||
"""
|
||||
|
||||
media_type = "text/html"
|
||||
format = "html"
|
||||
template_name = None
|
||||
exception_template_names = [
|
||||
"%(status_code)s.html",
|
||||
"api_exception.html"
|
||||
]
|
||||
charset = "utf-8"
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
"""
|
||||
Renders data to HTML, using Django's standard template rendering.
|
||||
|
||||
The template name is determined by (in order of preference):
|
||||
|
||||
1. An explicit .template_name set on the response.
|
||||
2. An explicit .template_name set on this class.
|
||||
3. The return result of calling view.get_template_names().
|
||||
"""
|
||||
renderer_context = renderer_context or {}
|
||||
view = renderer_context["view"]
|
||||
request = renderer_context["request"]
|
||||
response = renderer_context["response"]
|
||||
|
||||
if response.exception:
|
||||
template = self.get_exception_template(response)
|
||||
else:
|
||||
template_names = self.get_template_names(response, view)
|
||||
template = self.resolve_template(template_names)
|
||||
|
||||
context = self.resolve_context(data, request, response)
|
||||
return template.render(context)
|
||||
|
||||
def resolve_template(self, template_names):
|
||||
return loader.select_template(template_names)
|
||||
|
||||
def resolve_context(self, data, request, response):
|
||||
if response.exception:
|
||||
data["status_code"] = response.status_code
|
||||
return RequestContext(request, data)
|
||||
|
||||
def get_template_names(self, response, view):
|
||||
if response.template_name:
|
||||
return [response.template_name]
|
||||
elif self.template_name:
|
||||
return [self.template_name]
|
||||
elif hasattr(view, "get_template_names"):
|
||||
return view.get_template_names()
|
||||
elif hasattr(view, "template_name"):
|
||||
return [view.template_name]
|
||||
raise ImproperlyConfigured("Returned a template response with no `template_name` attribute set on either the view or response")
|
||||
|
||||
def get_exception_template(self, response):
|
||||
template_names = [name % {"status_code": response.status_code}
|
||||
for name in self.exception_template_names]
|
||||
|
||||
try:
|
||||
# Try to find an appropriate error template
|
||||
return self.resolve_template(template_names)
|
||||
except Exception:
|
||||
# Fall back to using eg "404 Not Found"
|
||||
return Template("%d %s" % (response.status_code,
|
||||
response.status_text.title()))
|
||||
|
||||
|
||||
# Note, subclass TemplateHTMLRenderer simply for the exception behavior
|
||||
class StaticHTMLRenderer(TemplateHTMLRenderer):
|
||||
"""
|
||||
An HTML renderer class that simply returns pre-rendered HTML.
|
||||
|
||||
The data supplied to the Response object should be a string representing
|
||||
the pre-rendered HTML content.
|
||||
|
||||
For example:
|
||||
data = "<html><body>example</body></html>"
|
||||
return Response(data)
|
||||
|
||||
For template rendered HTML, see TemplateHTMLRenderer.
|
||||
"""
|
||||
media_type = "text/html"
|
||||
format = "html"
|
||||
charset = "utf-8"
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
renderer_context = renderer_context or {}
|
||||
response = renderer_context["response"]
|
||||
|
||||
if response and response.exception:
|
||||
request = renderer_context["request"]
|
||||
template = self.get_exception_template(response)
|
||||
context = self.resolve_context(data, request, response)
|
||||
return template.render(context)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
class MultiPartRenderer(BaseRenderer):
|
||||
media_type = "multipart/form-data; boundary=BoUnDaRyStRiNg"
|
||||
format = "multipart"
|
||||
charset = "utf-8"
|
||||
BOUNDARY = "BoUnDaRyStRiNg"
|
||||
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return encode_multipart(self.BOUNDARY, data)
|
|
@ -1,465 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
The Request class is used as a wrapper around the standard request object.
|
||||
|
||||
The wrapped request then offers a richer API, in particular :
|
||||
|
||||
- content automatically parsed according to `Content-Type` header,
|
||||
and available as `request.DATA`
|
||||
- full support of PUT method, including support for file uploads
|
||||
- form overloading of HTTP method, content type and content
|
||||
"""
|
||||
from django.conf import settings
|
||||
from django.http import QueryDict
|
||||
from django.http.multipartparser import parse_header
|
||||
from django.utils.datastructures import MultiValueDict
|
||||
from django.utils.six import BytesIO
|
||||
|
||||
from taiga.base import exceptions
|
||||
|
||||
from . import HTTP_HEADER_ENCODING
|
||||
from .settings import api_settings
|
||||
|
||||
|
||||
def is_form_media_type(media_type):
|
||||
"""
|
||||
Return True if the media type is a valid form media type.
|
||||
"""
|
||||
base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING))
|
||||
return (base_media_type == "application/x-www-form-urlencoded" or
|
||||
base_media_type == "multipart/form-data")
|
||||
|
||||
|
||||
class override_method(object):
|
||||
"""
|
||||
A context manager that temporarily overrides the method on a request,
|
||||
additionally setting the `view.request` attribute.
|
||||
|
||||
Usage:
|
||||
|
||||
with override_method(view, request, "POST") as request:
|
||||
... # Do stuff with `view` and `request`
|
||||
"""
|
||||
def __init__(self, view, request, method):
|
||||
self.view = view
|
||||
self.request = request
|
||||
self.method = method
|
||||
|
||||
def __enter__(self):
|
||||
self.view.request = clone_request(self.request, self.method)
|
||||
return self.view.request
|
||||
|
||||
def __exit__(self, *args, **kwarg):
|
||||
self.view.request = self.request
|
||||
|
||||
|
||||
class Empty(object):
|
||||
"""
|
||||
Placeholder for unset attributes.
|
||||
Cannot use `None`, as that may be a valid value.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
def _hasattr(obj, name):
|
||||
return not getattr(obj, name) is Empty
|
||||
|
||||
|
||||
def clone_request(request, method):
|
||||
"""
|
||||
Internal helper method to clone a request, replacing with a different
|
||||
HTTP method. Used for checking permissions against other methods.
|
||||
"""
|
||||
ret = Request(request=request._request,
|
||||
parsers=request.parsers,
|
||||
authenticators=request.authenticators,
|
||||
negotiator=request.negotiator,
|
||||
parser_context=request.parser_context)
|
||||
ret._data = request._data
|
||||
ret._files = request._files
|
||||
ret._content_type = request._content_type
|
||||
ret._stream = request._stream
|
||||
ret._method = method
|
||||
if hasattr(request, "_user"):
|
||||
ret._user = request._user
|
||||
if hasattr(request, "_auth"):
|
||||
ret._auth = request._auth
|
||||
if hasattr(request, "_authenticator"):
|
||||
ret._authenticator = request._authenticator
|
||||
return ret
|
||||
|
||||
|
||||
class ForcedAuthentication(object):
|
||||
"""
|
||||
This authentication class is used if the test client or request factory
|
||||
forcibly authenticated the request.
|
||||
"""
|
||||
|
||||
def __init__(self, force_user, force_token):
|
||||
self.force_user = force_user
|
||||
self.force_token = force_token
|
||||
|
||||
def authenticate(self, request):
|
||||
return (self.force_user, self.force_token)
|
||||
|
||||
|
||||
class Request(object):
|
||||
"""
|
||||
Wrapper allowing to enhance a standard `HttpRequest` instance.
|
||||
|
||||
Kwargs:
|
||||
- request(HttpRequest). The original request instance.
|
||||
- parsers_classes(list/tuple). The parsers to use for parsing the
|
||||
request content.
|
||||
- authentication_classes(list/tuple). The authentications used to try
|
||||
authenticating the request's user.
|
||||
"""
|
||||
|
||||
_METHOD_PARAM = api_settings.FORM_METHOD_OVERRIDE
|
||||
_CONTENT_PARAM = api_settings.FORM_CONTENT_OVERRIDE
|
||||
_CONTENTTYPE_PARAM = api_settings.FORM_CONTENTTYPE_OVERRIDE
|
||||
|
||||
def __init__(self, request, parsers=None, authenticators=None,
|
||||
negotiator=None, parser_context=None):
|
||||
self._request = request
|
||||
self.parsers = parsers or ()
|
||||
self.authenticators = authenticators or ()
|
||||
self.negotiator = negotiator or self._default_negotiator()
|
||||
self.parser_context = parser_context
|
||||
self._data = Empty
|
||||
self._files = Empty
|
||||
self._method = Empty
|
||||
self._content_type = Empty
|
||||
self._stream = Empty
|
||||
|
||||
if self.parser_context is None:
|
||||
self.parser_context = {}
|
||||
self.parser_context["request"] = self
|
||||
self.parser_context["encoding"] = request.encoding or settings.DEFAULT_CHARSET
|
||||
|
||||
force_user = getattr(request, "_force_auth_user", None)
|
||||
force_token = getattr(request, "_force_auth_token", None)
|
||||
if (force_user is not None or force_token is not None):
|
||||
forced_auth = ForcedAuthentication(force_user, force_token)
|
||||
self.authenticators = (forced_auth,)
|
||||
|
||||
def _default_negotiator(self):
|
||||
return api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS()
|
||||
|
||||
@property
|
||||
def method(self):
|
||||
"""
|
||||
Returns the HTTP method.
|
||||
|
||||
This allows the `method` to be overridden by using a hidden `form`
|
||||
field on a form POST request.
|
||||
"""
|
||||
if not _hasattr(self, "_method"):
|
||||
self._load_method_and_content_type()
|
||||
return self._method
|
||||
|
||||
@property
|
||||
def content_type(self):
|
||||
"""
|
||||
Returns the content type header.
|
||||
|
||||
This should be used instead of `request.META.get("HTTP_CONTENT_TYPE")`,
|
||||
as it allows the content type to be overridden by using a hidden form
|
||||
field on a form POST request.
|
||||
"""
|
||||
if not _hasattr(self, "_content_type"):
|
||||
self._load_method_and_content_type()
|
||||
return self._content_type
|
||||
|
||||
@property
|
||||
def stream(self):
|
||||
"""
|
||||
Returns an object that may be used to stream the request content.
|
||||
"""
|
||||
if not _hasattr(self, "_stream"):
|
||||
self._load_stream()
|
||||
return self._stream
|
||||
|
||||
@property
|
||||
def QUERY_PARAMS(self):
|
||||
"""
|
||||
More semantically correct name for request.GET.
|
||||
"""
|
||||
return self._request.GET
|
||||
|
||||
@property
|
||||
def DATA(self):
|
||||
"""
|
||||
Parses the request body and returns the data.
|
||||
|
||||
Similar to usual behaviour of `request.POST`, except that it handles
|
||||
arbitrary parsers, and also works on methods other than POST (eg PUT).
|
||||
"""
|
||||
if not _hasattr(self, "_data"):
|
||||
self._load_data_and_files()
|
||||
return self._data
|
||||
|
||||
@property
|
||||
def FILES(self):
|
||||
"""
|
||||
Parses the request body and returns any files uploaded in the request.
|
||||
|
||||
Similar to usual behaviour of `request.FILES`, except that it handles
|
||||
arbitrary parsers, and also works on methods other than POST (eg PUT).
|
||||
"""
|
||||
if not _hasattr(self, "_files"):
|
||||
self._load_data_and_files()
|
||||
return self._files
|
||||
|
||||
@property
|
||||
def user(self):
|
||||
"""
|
||||
Returns the user associated with the current request, as authenticated
|
||||
by the authentication classes provided to the request.
|
||||
"""
|
||||
if not hasattr(self, "_user"):
|
||||
self._authenticate()
|
||||
return self._user
|
||||
|
||||
@user.setter
|
||||
def user(self, value):
|
||||
"""
|
||||
Sets the user on the current request. This is necessary to maintain
|
||||
compatibility with django.contrib.auth where the user property is
|
||||
set in the login and logout functions.
|
||||
"""
|
||||
self._user = value
|
||||
|
||||
@property
|
||||
def auth(self):
|
||||
"""
|
||||
Returns any non-user authentication information associated with the
|
||||
request, such as an authentication token.
|
||||
"""
|
||||
if not hasattr(self, "_auth"):
|
||||
self._authenticate()
|
||||
return self._auth
|
||||
|
||||
@auth.setter
|
||||
def auth(self, value):
|
||||
"""
|
||||
Sets any non-user authentication information associated with the
|
||||
request, such as an authentication token.
|
||||
"""
|
||||
self._auth = value
|
||||
|
||||
@property
|
||||
def successful_authenticator(self):
|
||||
"""
|
||||
Return the instance of the authentication instance class that was used
|
||||
to authenticate the request, or `None`.
|
||||
"""
|
||||
if not hasattr(self, "_authenticator"):
|
||||
self._authenticate()
|
||||
return self._authenticator
|
||||
|
||||
def _load_data_and_files(self):
|
||||
"""
|
||||
Parses the request content into self.DATA and self.FILES.
|
||||
"""
|
||||
if not _hasattr(self, "_content_type"):
|
||||
self._load_method_and_content_type()
|
||||
|
||||
if not _hasattr(self, "_data"):
|
||||
self._data, self._files = self._parse()
|
||||
|
||||
def _load_method_and_content_type(self):
|
||||
"""
|
||||
Sets the method and content_type, and then check if they"ve
|
||||
been overridden.
|
||||
"""
|
||||
self._content_type = self.META.get("HTTP_CONTENT_TYPE",
|
||||
self.META.get("CONTENT_TYPE", ""))
|
||||
|
||||
self._perform_form_overloading()
|
||||
|
||||
if not _hasattr(self, "_method"):
|
||||
self._method = self._request.method
|
||||
|
||||
# Allow X-HTTP-METHOD-OVERRIDE header
|
||||
self._method = self.META.get("HTTP_X_HTTP_METHOD_OVERRIDE",
|
||||
self._method)
|
||||
|
||||
def _load_stream(self):
|
||||
"""
|
||||
Return the content body of the request, as a stream.
|
||||
"""
|
||||
try:
|
||||
content_length = int(self.META.get("CONTENT_LENGTH",
|
||||
self.META.get("HTTP_CONTENT_LENGTH")))
|
||||
except (ValueError, TypeError):
|
||||
content_length = 0
|
||||
|
||||
if content_length == 0:
|
||||
self._stream = None
|
||||
elif hasattr(self._request, "read"):
|
||||
self._stream = self._request
|
||||
else:
|
||||
self._stream = BytesIO(self.raw_post_data)
|
||||
|
||||
def _perform_form_overloading(self):
|
||||
"""
|
||||
If this is a form POST request, then we need to check if the method and
|
||||
content/content_type have been overridden by setting them in hidden
|
||||
form fields or not.
|
||||
"""
|
||||
|
||||
USE_FORM_OVERLOADING = (
|
||||
self._METHOD_PARAM or
|
||||
(self._CONTENT_PARAM and self._CONTENTTYPE_PARAM)
|
||||
)
|
||||
|
||||
# We only need to use form overloading on form POST requests.
|
||||
if (not USE_FORM_OVERLOADING
|
||||
or self._request.method != "POST"
|
||||
or not is_form_media_type(self._content_type)):
|
||||
return
|
||||
|
||||
# At this point we"re committed to parsing the request as form data.
|
||||
self._data = self._request.POST
|
||||
self._files = self._request.FILES
|
||||
|
||||
# Method overloading - change the method and remove the param from the content.
|
||||
if (self._METHOD_PARAM and
|
||||
self._METHOD_PARAM in self._data):
|
||||
self._method = self._data[self._METHOD_PARAM].upper()
|
||||
|
||||
# Content overloading - modify the content type, and force re-parse.
|
||||
if (self._CONTENT_PARAM and
|
||||
self._CONTENTTYPE_PARAM and
|
||||
self._CONTENT_PARAM in self._data and
|
||||
self._CONTENTTYPE_PARAM in self._data):
|
||||
self._content_type = self._data[self._CONTENTTYPE_PARAM]
|
||||
self._stream = BytesIO(self._data[self._CONTENT_PARAM].encode(self.parser_context["encoding"]))
|
||||
self._data, self._files = (Empty, Empty)
|
||||
|
||||
def _parse(self):
|
||||
"""
|
||||
Parse the request content, returning a two-tuple of (data, files)
|
||||
|
||||
May raise an `UnsupportedMediaType`, or `ParseError` exception.
|
||||
"""
|
||||
stream = self.stream
|
||||
media_type = self.content_type
|
||||
|
||||
if stream is None or media_type is None:
|
||||
empty_data = QueryDict("", self._request._encoding)
|
||||
empty_files = MultiValueDict()
|
||||
return (empty_data, empty_files)
|
||||
|
||||
parser = self.negotiator.select_parser(self, self.parsers)
|
||||
|
||||
if not parser:
|
||||
raise exceptions.UnsupportedMediaType(media_type)
|
||||
|
||||
try:
|
||||
parsed = parser.parse(stream, media_type, self.parser_context)
|
||||
except:
|
||||
# If we get an exception during parsing, fill in empty data and
|
||||
# re-raise. Ensures we don't simply repeat the error when
|
||||
# attempting to render the browsable renderer response, or when
|
||||
# logging the request or similar.
|
||||
self._data = QueryDict("", self._request._encoding)
|
||||
self._files = MultiValueDict()
|
||||
raise
|
||||
|
||||
# Parser classes may return the raw data, or a
|
||||
# DataAndFiles object. Unpack the result as required.
|
||||
try:
|
||||
return (parsed.data, parsed.files)
|
||||
except AttributeError:
|
||||
empty_files = MultiValueDict()
|
||||
return (parsed, empty_files)
|
||||
|
||||
def _authenticate(self):
|
||||
"""
|
||||
Attempt to authenticate the request using each authentication instance
|
||||
in turn.
|
||||
Returns a three-tuple of (authenticator, user, authtoken).
|
||||
"""
|
||||
for authenticator in self.authenticators:
|
||||
try:
|
||||
user_auth_tuple = authenticator.authenticate(self)
|
||||
except exceptions.APIException:
|
||||
self._not_authenticated()
|
||||
raise
|
||||
|
||||
if not user_auth_tuple is None:
|
||||
self._authenticator = authenticator
|
||||
self._user, self._auth = user_auth_tuple
|
||||
return
|
||||
|
||||
self._not_authenticated()
|
||||
|
||||
def _not_authenticated(self):
|
||||
"""
|
||||
Return a three-tuple of (authenticator, user, authtoken), representing
|
||||
an unauthenticated request.
|
||||
|
||||
By default this will be (None, AnonymousUser, None).
|
||||
"""
|
||||
self._authenticator = None
|
||||
|
||||
if api_settings.UNAUTHENTICATED_USER:
|
||||
self._user = api_settings.UNAUTHENTICATED_USER()
|
||||
else:
|
||||
self._user = None
|
||||
|
||||
if api_settings.UNAUTHENTICATED_TOKEN:
|
||||
self._auth = api_settings.UNAUTHENTICATED_TOKEN()
|
||||
else:
|
||||
self._auth = None
|
||||
|
||||
def __getattr__(self, attr):
|
||||
"""
|
||||
Proxy other attributes to the underlying HttpRequest object.
|
||||
"""
|
||||
return getattr(self._request, attr)
|
|
@ -1,66 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Provide reverse functions that return fully qualified URLs
|
||||
"""
|
||||
from django.core.urlresolvers import reverse as django_reverse
|
||||
from django.utils.functional import lazy
|
||||
|
||||
|
||||
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
|
||||
"""
|
||||
Same as `django.core.urlresolvers.reverse`, but optionally takes a request
|
||||
and returns a fully qualified URL, using the request to get the base URL.
|
||||
"""
|
||||
if format is not None:
|
||||
kwargs = kwargs or {}
|
||||
kwargs["format"] = format
|
||||
url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
|
||||
if request:
|
||||
return request.build_absolute_uri(url)
|
||||
return url
|
||||
|
||||
|
||||
reverse_lazy = lazy(reverse, str)
|
File diff suppressed because it is too large
Load Diff
|
@ -1,254 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
"""
|
||||
Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
|
||||
For example your project's `settings.py` file might look like this:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
"DEFAULT_RENDERER_CLASSES": (
|
||||
"taiga.base.api.renderers.JSONRenderer",
|
||||
)
|
||||
"DEFAULT_PARSER_CLASSES": (
|
||||
"taiga.base.api.parsers.JSONParser",
|
||||
)
|
||||
}
|
||||
|
||||
This module provides the `api_setting` object, that is used to access
|
||||
REST framework settings, checking for user settings first, then falling
|
||||
back to the defaults.
|
||||
"""
|
||||
from __future__ import unicode_literals
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils import six
|
||||
|
||||
import importlib
|
||||
|
||||
from . import ISO_8601
|
||||
|
||||
|
||||
USER_SETTINGS = getattr(settings, "REST_FRAMEWORK", None)
|
||||
|
||||
DEFAULTS = {
|
||||
# Base API policies
|
||||
"DEFAULT_RENDERER_CLASSES": (
|
||||
"taiga.base.api.renderers.JSONRenderer",
|
||||
),
|
||||
"DEFAULT_PARSER_CLASSES": (
|
||||
"taiga.base.api.parsers.JSONParser",
|
||||
"taiga.base.api.parsers.FormParser",
|
||||
"taiga.base.api.parsers.MultiPartParser"
|
||||
),
|
||||
"DEFAULT_AUTHENTICATION_CLASSES": (
|
||||
"taiga.base.api.authentication.SessionAuthentication",
|
||||
"taiga.base.api.authentication.BasicAuthentication"
|
||||
),
|
||||
"DEFAULT_PERMISSION_CLASSES": (
|
||||
"taiga.base.api.permissions.AllowAny",
|
||||
),
|
||||
"DEFAULT_THROTTLE_CLASSES": (
|
||||
),
|
||||
"DEFAULT_CONTENT_NEGOTIATION_CLASS":
|
||||
"taiga.base.api.negotiation.DefaultContentNegotiation",
|
||||
|
||||
# Genric view behavior
|
||||
"DEFAULT_MODEL_SERIALIZER_CLASS":
|
||||
"taiga.base.api.serializers.ModelSerializer",
|
||||
"DEFAULT_MODEL_VALIDATOR_CLASS":
|
||||
"taiga.base.api.validators.ModelValidator",
|
||||
"DEFAULT_FILTER_BACKENDS": (),
|
||||
|
||||
# Throttling
|
||||
"DEFAULT_THROTTLE_RATES": {
|
||||
"user": None,
|
||||
"anon": None,
|
||||
},
|
||||
"DEFAULT_THROTTLE_WHITELIST": [],
|
||||
|
||||
# Pagination
|
||||
"PAGINATE_BY": None,
|
||||
"PAGINATE_BY_PARAM": None,
|
||||
"MAX_PAGINATE_BY": None,
|
||||
|
||||
# Authentication
|
||||
"UNAUTHENTICATED_USER": "django.contrib.auth.models.AnonymousUser",
|
||||
"UNAUTHENTICATED_TOKEN": None,
|
||||
|
||||
# View configuration
|
||||
"VIEW_NAME_FUNCTION": "taiga.base.api.views.get_view_name",
|
||||
"VIEW_DESCRIPTION_FUNCTION": "taiga.base.api.views.get_view_description",
|
||||
|
||||
# Exception handling
|
||||
"EXCEPTION_HANDLER": "taiga.base.api.views.exception_handler",
|
||||
|
||||
# Testing
|
||||
"TEST_REQUEST_RENDERER_CLASSES": (
|
||||
"taiga.base.api.renderers.MultiPartRenderer",
|
||||
"taiga.base.api.renderers.JSONRenderer"
|
||||
),
|
||||
"TEST_REQUEST_DEFAULT_FORMAT": "multipart",
|
||||
|
||||
# Browser enhancements
|
||||
"FORM_METHOD_OVERRIDE": "_method",
|
||||
"FORM_CONTENT_OVERRIDE": "_content",
|
||||
"FORM_CONTENTTYPE_OVERRIDE": "_content_type",
|
||||
"URL_ACCEPT_OVERRIDE": "accept",
|
||||
"URL_FORMAT_OVERRIDE": "format",
|
||||
|
||||
"FORMAT_SUFFIX_KWARG": "format",
|
||||
"URL_FIELD_NAME": "url",
|
||||
|
||||
# Input and output formats
|
||||
"DATE_INPUT_FORMATS": (
|
||||
ISO_8601,
|
||||
),
|
||||
"DATE_FORMAT": ISO_8601,
|
||||
|
||||
"DATETIME_INPUT_FORMATS": (
|
||||
ISO_8601,
|
||||
),
|
||||
"DATETIME_FORMAT": None,
|
||||
|
||||
"TIME_INPUT_FORMATS": (
|
||||
ISO_8601,
|
||||
),
|
||||
"TIME_FORMAT": None,
|
||||
|
||||
# Pending deprecation
|
||||
"FILTER_BACKEND": None,
|
||||
}
|
||||
|
||||
|
||||
# List of settings that may be in string import notation.
|
||||
IMPORT_STRINGS = (
|
||||
"DEFAULT_RENDERER_CLASSES",
|
||||
"DEFAULT_PARSER_CLASSES",
|
||||
"DEFAULT_AUTHENTICATION_CLASSES",
|
||||
"DEFAULT_PERMISSION_CLASSES",
|
||||
"DEFAULT_THROTTLE_CLASSES",
|
||||
"DEFAULT_CONTENT_NEGOTIATION_CLASS",
|
||||
"DEFAULT_MODEL_SERIALIZER_CLASS",
|
||||
"DEFAULT_FILTER_BACKENDS",
|
||||
"EXCEPTION_HANDLER",
|
||||
"FILTER_BACKEND",
|
||||
"TEST_REQUEST_RENDERER_CLASSES",
|
||||
"UNAUTHENTICATED_USER",
|
||||
"UNAUTHENTICATED_TOKEN",
|
||||
"VIEW_NAME_FUNCTION",
|
||||
"VIEW_DESCRIPTION_FUNCTION"
|
||||
)
|
||||
|
||||
|
||||
def perform_import(val, setting_name):
|
||||
"""
|
||||
If the given setting is a string import notation,
|
||||
then perform the necessary import or imports.
|
||||
"""
|
||||
if isinstance(val, six.string_types):
|
||||
return import_from_string(val, setting_name)
|
||||
elif isinstance(val, (list, tuple)):
|
||||
return [import_from_string(item, setting_name) for item in val]
|
||||
return val
|
||||
|
||||
|
||||
def import_from_string(val, setting_name):
|
||||
"""
|
||||
Attempt to import a class from a string representation.
|
||||
"""
|
||||
try:
|
||||
# Nod to tastypie's use of importlib.
|
||||
parts = val.split('.')
|
||||
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
|
||||
module = importlib.import_module(module_path)
|
||||
return getattr(module, class_name)
|
||||
except ImportError as e:
|
||||
msg = "Could not import '%s' for API setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
|
||||
raise ImportError(msg)
|
||||
|
||||
|
||||
class APISettings(object):
|
||||
"""
|
||||
A settings object, that allows API settings to be accessed as properties.
|
||||
For example:
|
||||
|
||||
from taiga.base.api.settings import api_settings
|
||||
print api_settings.DEFAULT_RENDERER_CLASSES
|
||||
|
||||
Any setting with string import paths will be automatically resolved
|
||||
and return the class, rather than the string literal.
|
||||
"""
|
||||
def __init__(self, user_settings=None, defaults=None, import_strings=None):
|
||||
self.user_settings = user_settings or {}
|
||||
self.defaults = defaults or {}
|
||||
self.import_strings = import_strings or ()
|
||||
|
||||
def __getattr__(self, attr):
|
||||
if attr not in self.defaults.keys():
|
||||
raise AttributeError("Invalid API setting: '%s'" % attr)
|
||||
|
||||
try:
|
||||
# Check if present in user settings
|
||||
val = self.user_settings[attr]
|
||||
except KeyError:
|
||||
# Fall back to defaults
|
||||
val = self.defaults[attr]
|
||||
|
||||
# Coerce import strings into classes
|
||||
if val and attr in self.import_strings:
|
||||
val = perform_import(val, attr)
|
||||
|
||||
self.validate_setting(attr, val)
|
||||
|
||||
# Cache the result
|
||||
setattr(self, attr, val)
|
||||
return val
|
||||
|
||||
def validate_setting(self, attr, val):
|
||||
if attr == "FILTER_BACKEND" and val is not None:
|
||||
# Make sure we can initialize the class
|
||||
val()
|
||||
|
||||
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
|
|
@ -1,296 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Provides various throttling policies.
|
||||
"""
|
||||
|
||||
from django.core.cache import cache as default_cache
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
|
||||
from .settings import api_settings
|
||||
|
||||
import time
|
||||
|
||||
|
||||
class BaseThrottle(object):
|
||||
"""
|
||||
Rate throttling of requests.
|
||||
"""
|
||||
def allow_request(self, request, view):
|
||||
"""
|
||||
Return `True` if the request should be allowed, `False` otherwise.
|
||||
"""
|
||||
raise NotImplementedError(".allow_request() must be overridden")
|
||||
|
||||
def finalize(self, request, response, view):
|
||||
"""
|
||||
Optionally, update the Trottling information based on de response.
|
||||
"""
|
||||
return None
|
||||
|
||||
def wait(self):
|
||||
"""
|
||||
Optionally, return a recommended number of seconds to wait before
|
||||
the next request.
|
||||
"""
|
||||
return None
|
||||
|
||||
|
||||
class SimpleRateThrottle(BaseThrottle):
|
||||
"""
|
||||
A simple cache implementation, that only requires `.get_cache_key()`
|
||||
to be overridden.
|
||||
|
||||
The rate (requests / seconds) is set by a `throttle` attribute on the View
|
||||
class. The attribute is a string of the form "number_of_requests/period".
|
||||
|
||||
Period should be one of: ("s", "sec", "m", "min", "h", "hour", "d", "day")
|
||||
|
||||
Previous request information used for throttling is stored in the cache.
|
||||
"""
|
||||
|
||||
cache = default_cache
|
||||
timer = time.time
|
||||
cache_format = "throtte_%(scope)s_%(ident)s"
|
||||
scope = None
|
||||
THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES
|
||||
|
||||
def __init__(self):
|
||||
if not getattr(self, "rate", None):
|
||||
self.rate = self.get_rate()
|
||||
self.num_requests, self.duration = self.parse_rate(self.rate)
|
||||
|
||||
def get_cache_key(self, request, view):
|
||||
"""
|
||||
Should return a unique cache-key which can be used for throttling.
|
||||
Must be overridden.
|
||||
|
||||
May return `None` if the request should not be throttled.
|
||||
"""
|
||||
raise NotImplementedError(".get_cache_key() must be overridden")
|
||||
|
||||
def has_to_finalize(self, request, response, view):
|
||||
"""
|
||||
Determine if the finalize method must be executed.
|
||||
"""
|
||||
return self.rate is not None
|
||||
|
||||
def get_rate(self):
|
||||
"""
|
||||
Determine the string representation of the allowed request rate.
|
||||
"""
|
||||
if not getattr(self, "scope", None):
|
||||
msg = ("You must set either `.scope` or `.rate` for \"%s\" throttle" %
|
||||
self.__class__.__name__)
|
||||
raise ImproperlyConfigured(msg)
|
||||
|
||||
try:
|
||||
return self.THROTTLE_RATES[self.scope]
|
||||
except KeyError:
|
||||
msg = "No default throttle rate set for \"%s\" scope" % self.scope
|
||||
raise ImproperlyConfigured(msg)
|
||||
|
||||
def parse_rate(self, rate):
|
||||
"""
|
||||
Given the request rate string, return a two tuple of:
|
||||
<allowed number of requests>, <period of time in seconds>
|
||||
"""
|
||||
if rate is None:
|
||||
return (None, None)
|
||||
num, period = rate.split("/")
|
||||
num_requests = int(num)
|
||||
duration = {"s": 1, "m": 60, "h": 3600, "d": 86400}[period[0]]
|
||||
return (num_requests, duration)
|
||||
|
||||
def allow_request(self, request, view):
|
||||
"""
|
||||
Implement the check to see if the request should be throttled.
|
||||
|
||||
On success calls `throttle_success`.
|
||||
On failure calls `throttle_failure`.
|
||||
"""
|
||||
if self.rate is None:
|
||||
return True
|
||||
|
||||
self.key = self.get_cache_key(request, view)
|
||||
if self.key is None:
|
||||
return True
|
||||
|
||||
self.history = self.cache.get(self.key, [])
|
||||
self.now = self.timer()
|
||||
|
||||
# Drop any requests from the history which have now passed the
|
||||
# throttle duration
|
||||
while self.history and self.history[-1] <= self.now - self.duration:
|
||||
self.history.pop()
|
||||
|
||||
if self.exceeded_throttling_restriction(request, view):
|
||||
return self.throttle_failure()
|
||||
return self.throttle_success(request, view)
|
||||
|
||||
def exceeded_throttling_restriction(self, request, view):
|
||||
return len(self.history) >= self.num_requests
|
||||
|
||||
def throttle_success(self, request, view):
|
||||
"""
|
||||
Inserts the current request's timestamp along with the key
|
||||
into the cache.
|
||||
"""
|
||||
self.history.insert(0, self.now)
|
||||
self.cache.set(self.key, self.history, self.duration)
|
||||
return True
|
||||
|
||||
def throttle_failure(self):
|
||||
"""
|
||||
Called when a request to the API has failed due to throttling.
|
||||
"""
|
||||
return False
|
||||
|
||||
def wait(self):
|
||||
"""
|
||||
Returns the recommended next request time in seconds.
|
||||
"""
|
||||
if self.history:
|
||||
remaining_duration = self.duration - (self.now - self.history[-1])
|
||||
else:
|
||||
remaining_duration = self.duration
|
||||
|
||||
available_requests = self.num_requests - len(self.history) + 1
|
||||
if available_requests <= 0:
|
||||
return None
|
||||
|
||||
return remaining_duration / float(available_requests)
|
||||
|
||||
|
||||
class AnonRateThrottle(SimpleRateThrottle):
|
||||
"""
|
||||
Limits the rate of API calls that may be made by a anonymous users.
|
||||
|
||||
The IP address of the request will be used as the unique cache key.
|
||||
"""
|
||||
scope = "anon"
|
||||
|
||||
def get_cache_key(self, request, view):
|
||||
if request.user.is_authenticated():
|
||||
return None # Only throttle unauthenticated requests.
|
||||
|
||||
ident = request.META.get("HTTP_X_FORWARDED_FOR")
|
||||
if ident is None:
|
||||
ident = request.META.get("REMOTE_ADDR")
|
||||
|
||||
return self.cache_format % {
|
||||
"scope": self.scope,
|
||||
"ident": ident
|
||||
}
|
||||
|
||||
|
||||
class UserRateThrottle(SimpleRateThrottle):
|
||||
"""
|
||||
Limits the rate of API calls that may be made by a given user.
|
||||
|
||||
The user id will be used as a unique cache key if the user is
|
||||
authenticated. For anonymous requests, the IP address of the request will
|
||||
be used.
|
||||
"""
|
||||
scope = "user"
|
||||
|
||||
def get_cache_key(self, request, view):
|
||||
if request.user.is_authenticated():
|
||||
ident = request.user.id
|
||||
else:
|
||||
ident = request.META.get("REMOTE_ADDR", None)
|
||||
|
||||
return self.cache_format % {
|
||||
"scope": self.scope,
|
||||
"ident": ident
|
||||
}
|
||||
|
||||
|
||||
class ScopedRateThrottle(SimpleRateThrottle):
|
||||
"""
|
||||
Limits the rate of API calls by different amounts for various parts of
|
||||
the API. Any view that has the `throttle_scope` property set will be
|
||||
throttled. The unique cache key will be generated by concatenating the
|
||||
user id of the request, and the scope of the view being accessed.
|
||||
"""
|
||||
scope_attr = "throttle_scope"
|
||||
|
||||
def __init__(self):
|
||||
# Override the usual SimpleRateThrottle, because we can't determine
|
||||
# the rate until called by the view.
|
||||
pass
|
||||
|
||||
def allow_request(self, request, view):
|
||||
# We can only determine the scope once we"re called by the view.
|
||||
self.scope = getattr(view, self.scope_attr, None)
|
||||
|
||||
# If a view does not have a `throttle_scope` always allow the request
|
||||
if not self.scope:
|
||||
return True
|
||||
|
||||
# Determine the allowed request rate as we normally would during
|
||||
# the `__init__` call.
|
||||
self.rate = self.get_rate()
|
||||
self.num_requests, self.duration = self.parse_rate(self.rate)
|
||||
|
||||
# We can now proceed as normal.
|
||||
return super(ScopedRateThrottle, self).allow_request(request, view)
|
||||
|
||||
def get_cache_key(self, request, view):
|
||||
"""
|
||||
If `view.throttle_scope` is not set, don't apply this throttle.
|
||||
|
||||
Otherwise generate the unique cache key by concatenating the user id
|
||||
with the ".throttle_scope` property of the view.
|
||||
"""
|
||||
if request.user.is_authenticated():
|
||||
ident = request.user.id
|
||||
else:
|
||||
ident = request.META.get("REMOTE_ADDR", None)
|
||||
|
||||
return self.cache_format % {
|
||||
"scope": self.scope,
|
||||
"ident": ident
|
||||
}
|
|
@ -1,107 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
from django.core.urlresolvers import RegexURLResolver
|
||||
from django.conf.urls import url, include
|
||||
|
||||
from .settings import api_settings
|
||||
|
||||
|
||||
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
|
||||
ret = []
|
||||
for urlpattern in urlpatterns:
|
||||
if isinstance(urlpattern, RegexURLResolver):
|
||||
# Set of included URL patterns
|
||||
regex = urlpattern.regex.pattern
|
||||
namespace = urlpattern.namespace
|
||||
app_name = urlpattern.app_name
|
||||
kwargs = urlpattern.default_kwargs
|
||||
# Add in the included patterns, after applying the suffixes
|
||||
patterns = apply_suffix_patterns(urlpattern.url_patterns,
|
||||
suffix_pattern,
|
||||
suffix_required)
|
||||
ret.append(url(regex, include(patterns, namespace, app_name), kwargs))
|
||||
|
||||
else:
|
||||
# Regular URL pattern
|
||||
regex = urlpattern.regex.pattern.rstrip("$") + suffix_pattern
|
||||
view = urlpattern.callback
|
||||
kwargs = urlpattern.default_args
|
||||
name = urlpattern.name
|
||||
# Add in both the existing and the new urlpattern
|
||||
if not suffix_required:
|
||||
ret.append(urlpattern)
|
||||
ret.append(url(regex, view, kwargs, name))
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
|
||||
"""
|
||||
Supplement existing urlpatterns with corresponding patterns that also
|
||||
include a ".format" suffix. Retains urlpattern ordering.
|
||||
|
||||
urlpatterns:
|
||||
A list of URL patterns.
|
||||
|
||||
suffix_required:
|
||||
If `True`, only suffixed URLs will be generated, and non-suffixed
|
||||
URLs will not be used. Defaults to `False`.
|
||||
|
||||
allowed:
|
||||
An optional tuple/list of allowed suffixes. eg ["json", "api"]
|
||||
Defaults to `None`, which allows any suffix.
|
||||
"""
|
||||
suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG
|
||||
if allowed:
|
||||
if len(allowed) == 1:
|
||||
allowed_pattern = allowed[0]
|
||||
else:
|
||||
allowed_pattern = "(%s)" % "|".join(allowed)
|
||||
suffix_pattern = r"\.(?P<%s>%s)$" % (suffix_kwarg, allowed_pattern)
|
||||
else:
|
||||
suffix_pattern = r"\.(?P<%s>[a-z0-9]+)$" % suffix_kwarg
|
||||
|
||||
return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)
|
|
@ -1,57 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404 as _get_object_or_404
|
||||
|
||||
|
||||
def get_object_or_404(queryset, *filter_args, **filter_kwargs):
|
||||
"""
|
||||
Same as Django's standard shortcut, but make sure to raise 404
|
||||
if the filter_kwargs don't match the required types.
|
||||
"""
|
||||
try:
|
||||
return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
|
||||
except (TypeError, ValueError):
|
||||
raise Http404
|
|
@ -1,58 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
from django.http import Http404
|
||||
from django.shortcuts import get_object_or_404 as _get_object_or_404
|
||||
|
||||
|
||||
def get_object_or_404(queryset, *filter_args, **filter_kwargs):
|
||||
"""
|
||||
Same as Django's standard shortcut, but make sure to raise 404
|
||||
if the filter_kwargs don't match the required types.
|
||||
"""
|
||||
try:
|
||||
return _get_object_or_404(queryset, *filter_args, **filter_kwargs)
|
||||
except (TypeError, ValueError):
|
||||
raise Http404
|
||||
|
|
@ -1,103 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Helper classes for parsers.
|
||||
"""
|
||||
from django.db.models.query import QuerySet
|
||||
from django.utils.functional import Promise
|
||||
from django.utils import timezone
|
||||
from django.utils.encoding import force_text
|
||||
|
||||
import datetime
|
||||
import decimal
|
||||
import types
|
||||
import json
|
||||
|
||||
|
||||
class JSONEncoder(json.JSONEncoder):
|
||||
"""
|
||||
JSONEncoder subclass that knows how to encode date/time/timedelta,
|
||||
decimal types, and generators.
|
||||
"""
|
||||
def default(self, o):
|
||||
# For Date Time string spec, see ECMA 262
|
||||
# http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
|
||||
if isinstance(o, Promise):
|
||||
return force_text(o)
|
||||
elif isinstance(o, datetime.datetime):
|
||||
r = o.isoformat()
|
||||
if o.microsecond:
|
||||
r = r[:23] + r[26:]
|
||||
if r.endswith("+00:00"):
|
||||
r = r[:-6] + "Z"
|
||||
return r
|
||||
elif isinstance(o, datetime.date):
|
||||
return o.isoformat()
|
||||
elif isinstance(o, datetime.time):
|
||||
if timezone and timezone.is_aware(o):
|
||||
raise ValueError("JSON can't represent timezone-aware times.")
|
||||
r = o.isoformat()
|
||||
if o.microsecond:
|
||||
r = r[:12]
|
||||
return r
|
||||
elif isinstance(o, datetime.timedelta):
|
||||
return str(o.total_seconds())
|
||||
elif isinstance(o, decimal.Decimal):
|
||||
return str(o)
|
||||
elif isinstance(o, QuerySet):
|
||||
return list(o)
|
||||
elif hasattr(o, "tolist"):
|
||||
return o.tolist()
|
||||
elif hasattr(o, "__getitem__"):
|
||||
try:
|
||||
return dict(o)
|
||||
except:
|
||||
pass
|
||||
elif hasattr(o, "__iter__"):
|
||||
return [i for i in o]
|
||||
return super(JSONEncoder, self).default(o)
|
||||
|
||||
|
||||
SafeDumper = None
|
|
@ -1,120 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Utility functions to return a formatted name and description for a given view.
|
||||
"""
|
||||
from django.utils.html import escape
|
||||
from django.utils.safestring import mark_safe
|
||||
|
||||
from taiga.base.api.settings import api_settings
|
||||
|
||||
from textwrap import dedent
|
||||
import re
|
||||
|
||||
# Markdown is optional
|
||||
try:
|
||||
import markdown
|
||||
|
||||
def apply_markdown(text):
|
||||
"""
|
||||
Simple wrapper around :func:`markdown.markdown` to set the base level
|
||||
of '#' style headers to <h2>.
|
||||
"""
|
||||
extensions = ["headerid(level=2)"]
|
||||
safe_mode = False
|
||||
md = markdown.Markdown(extensions=extensions, safe_mode=safe_mode)
|
||||
return md.convert(text)
|
||||
|
||||
except ImportError:
|
||||
apply_markdown = None
|
||||
|
||||
|
||||
def remove_trailing_string(content, trailing):
|
||||
"""
|
||||
Strip trailing component `trailing` from `content` if it exists.
|
||||
Used when generating names from view classes.
|
||||
"""
|
||||
if content.endswith(trailing) and content != trailing:
|
||||
return content[:-len(trailing)]
|
||||
return content
|
||||
|
||||
|
||||
def dedent(content):
|
||||
"""
|
||||
Remove leading indent from a block of text.
|
||||
Used when generating descriptions from docstrings.
|
||||
|
||||
Note that python's `textwrap.dedent` doesn't quite cut it,
|
||||
as it fails to dedent multiline docstrings that include
|
||||
unindented text on the initial line.
|
||||
"""
|
||||
whitespace_counts = [len(line) - len(line.lstrip(" "))
|
||||
for line in content.splitlines()[1:] if line.lstrip()]
|
||||
|
||||
# unindent the content if needed
|
||||
if whitespace_counts:
|
||||
whitespace_pattern = "^" + (" " * min(whitespace_counts))
|
||||
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), "", content)
|
||||
|
||||
return content.strip()
|
||||
|
||||
def camelcase_to_spaces(content):
|
||||
"""
|
||||
Translate 'CamelCaseNames' to 'Camel Case Names'.
|
||||
Used when generating names from view classes.
|
||||
"""
|
||||
camelcase_boundry = "(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))"
|
||||
content = re.sub(camelcase_boundry, " \\1", content).strip()
|
||||
return " ".join(content.split("_")).title()
|
||||
|
||||
def markup_description(description):
|
||||
"""
|
||||
Apply HTML markup to the given description.
|
||||
"""
|
||||
if apply_markdown:
|
||||
description = apply_markdown(description)
|
||||
else:
|
||||
description = escape(description).replace("\n", "<br />")
|
||||
return mark_safe(description)
|
|
@ -1,132 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""
|
||||
Handling of media types, as found in HTTP Content-Type and Accept headers.
|
||||
|
||||
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
|
||||
"""
|
||||
from django.http.multipartparser import parse_header
|
||||
|
||||
from taiga.base.api import HTTP_HEADER_ENCODING
|
||||
|
||||
|
||||
def media_type_matches(lhs, rhs):
|
||||
"""
|
||||
Returns ``True`` if the media type in the first argument <= the
|
||||
media type in the second argument. The media types are strings
|
||||
as described by the HTTP spec.
|
||||
|
||||
Valid media type strings include:
|
||||
|
||||
'application/json; indent=4'
|
||||
'application/json'
|
||||
'text/*'
|
||||
'*/*'
|
||||
"""
|
||||
lhs = _MediaType(lhs)
|
||||
rhs = _MediaType(rhs)
|
||||
return lhs.match(rhs)
|
||||
|
||||
|
||||
def order_by_precedence(media_type_lst):
|
||||
"""
|
||||
Returns a list of sets of media type strings, ordered by precedence.
|
||||
Precedence is determined by how specific a media type is:
|
||||
|
||||
3. 'type/subtype; param=val'
|
||||
2. 'type/subtype'
|
||||
1. 'type/*'
|
||||
0. '*/*'
|
||||
"""
|
||||
ret = [set(), set(), set(), set()]
|
||||
for media_type in media_type_lst:
|
||||
precedence = _MediaType(media_type).precedence
|
||||
ret[3 - precedence].add(media_type)
|
||||
return [media_types for media_types in ret if media_types]
|
||||
|
||||
|
||||
class _MediaType(object):
|
||||
def __init__(self, media_type_str):
|
||||
if media_type_str is None:
|
||||
media_type_str = ''
|
||||
self.orig = media_type_str
|
||||
self.full_type, self.params = parse_header(media_type_str.encode(HTTP_HEADER_ENCODING))
|
||||
self.main_type, sep, self.sub_type = self.full_type.partition("/")
|
||||
|
||||
def match(self, other):
|
||||
"""Return true if this MediaType satisfies the given MediaType."""
|
||||
for key in self.params.keys():
|
||||
if key != "q" and other.params.get(key, None) != self.params.get(key, None):
|
||||
return False
|
||||
|
||||
if self.sub_type != "*" and other.sub_type != "*" and other.sub_type != self.sub_type:
|
||||
return False
|
||||
|
||||
if self.main_type != "*" and other.main_type != "*" and other.main_type != self.main_type:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@property
|
||||
def precedence(self):
|
||||
"""
|
||||
Return a precedence level from 0-3 for the media type given how specific it is.
|
||||
"""
|
||||
if self.main_type == "*":
|
||||
return 0
|
||||
elif self.sub_type == "*":
|
||||
return 1
|
||||
elif not self.params or self.params.keys() == ["q"]:
|
||||
return 2
|
||||
return 3
|
||||
|
||||
def __str__(self):
|
||||
return unicode(self).encode("utf-8")
|
||||
|
||||
def __unicode__(self):
|
||||
ret = "%s/%s" % (self.main_type, self.sub_type)
|
||||
for key, val in self.params.items():
|
||||
ret += "; %s=%s" % (key, val)
|
||||
return ret
|
|
@ -1,27 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from . import serializers
|
||||
|
||||
|
||||
class Validator(serializers.Serializer):
|
||||
pass
|
||||
|
||||
|
||||
class ModelValidator(serializers.ModelSerializer):
|
||||
pass
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,58 +14,27 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# This code is partially taken from django-rest-framework:
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
import json
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.http import Http404, HttpResponse
|
||||
from django.http.response import HttpResponseBase
|
||||
from django.utils.datastructures import SortedDict
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.defaults import server_error
|
||||
from django.views.generic import View
|
||||
from django.utils.encoding import smart_text
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from .request import Request
|
||||
from .settings import api_settings
|
||||
from .utils import formatting
|
||||
from rest_framework import status, exceptions
|
||||
from rest_framework.compat import smart_text, HttpResponseBase, View
|
||||
from rest_framework.request import Request
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.utils import formatting
|
||||
|
||||
from taiga.base import status
|
||||
from taiga.base import exceptions
|
||||
from taiga.base.response import Response
|
||||
from taiga.base.response import Ok
|
||||
from taiga.base.response import NotFound
|
||||
from taiga.base.response import Forbidden
|
||||
from taiga.base.utils.iterators import as_tuple
|
||||
|
||||
from django.conf import settings
|
||||
from django.views.defaults import server_error
|
||||
|
||||
|
||||
def get_view_name(view_cls, suffix=None):
|
||||
|
@ -86,7 +53,6 @@ def get_view_name(view_cls, suffix=None):
|
|||
|
||||
return name
|
||||
|
||||
|
||||
def get_view_description(view_cls, html=False):
|
||||
"""
|
||||
Given a view class, return a textual description to represent the view.
|
||||
|
@ -123,10 +89,12 @@ def exception_handler(exc):
|
|||
headers=headers)
|
||||
|
||||
elif isinstance(exc, Http404):
|
||||
return NotFound({'detail': _('Not found')})
|
||||
return Response({'detail': 'Not found'},
|
||||
status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
elif isinstance(exc, PermissionDenied):
|
||||
return Forbidden({'detail': _('Permission denied')})
|
||||
return Response({'detail': 'Permission denied'},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
# Note: Unhandled exceptions will raise a 500 error.
|
||||
return None
|
||||
|
@ -144,8 +112,6 @@ class APIView(View):
|
|||
# Allow dependancy injection of other settings to make testing easier.
|
||||
settings = api_settings
|
||||
|
||||
_trottle_instances = None
|
||||
|
||||
@classmethod
|
||||
def as_view(cls, **initkwargs):
|
||||
"""
|
||||
|
@ -174,6 +140,7 @@ class APIView(View):
|
|||
headers['Vary'] = 'Accept'
|
||||
return headers
|
||||
|
||||
|
||||
def http_method_not_allowed(self, request, *args, **kwargs):
|
||||
"""
|
||||
If `request.method` does not correspond to a handler method,
|
||||
|
@ -288,9 +255,7 @@ class APIView(View):
|
|||
"""
|
||||
Instantiates and returns the list of throttles that this view uses.
|
||||
"""
|
||||
if self._trottle_instances is None:
|
||||
self._trottle_instances = [throttle() for throttle in self.throttle_classes]
|
||||
return self._trottle_instances
|
||||
return [throttle() for throttle in self.throttle_classes]
|
||||
|
||||
def get_content_negotiator(self):
|
||||
"""
|
||||
|
@ -326,7 +291,7 @@ class APIView(View):
|
|||
"""
|
||||
request.user
|
||||
|
||||
def check_permissions(self, request, action:str=None, obj=None):
|
||||
def check_permissions(self, request, action, obj=None):
|
||||
if action is None:
|
||||
self.permission_denied(request)
|
||||
|
||||
|
@ -346,15 +311,6 @@ class APIView(View):
|
|||
if not throttle.allow_request(request, self):
|
||||
self.throttled(request, throttle.wait())
|
||||
|
||||
def finalize_throttles(self, request, response):
|
||||
"""
|
||||
Check if request should be throttled.
|
||||
Raises an appropriate exception if the request is throttled.
|
||||
"""
|
||||
for throttle in self.get_throttles():
|
||||
if throttle.has_to_finalize(request, response, self):
|
||||
throttle.finalize(request, response, self)
|
||||
|
||||
# Dispatch methods
|
||||
|
||||
def initialize_request(self, request, *args, **kwargs):
|
||||
|
@ -388,9 +344,11 @@ class APIView(View):
|
|||
Returns the final response object.
|
||||
"""
|
||||
# Make the error obvious if a proper response is not returned
|
||||
assert isinstance(response, HttpResponseBase), ('Expected a `Response`, `HttpResponse` or '
|
||||
'`HttpStreamingResponse` to be returned from the view, '
|
||||
'but received a `%s`' % type(response))
|
||||
assert isinstance(response, HttpResponseBase), (
|
||||
'Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` '
|
||||
'to be returned from the view, but received a `%s`'
|
||||
% type(response)
|
||||
)
|
||||
|
||||
if isinstance(response, Response):
|
||||
if not getattr(request, 'accepted_renderer', None):
|
||||
|
@ -404,8 +362,6 @@ class APIView(View):
|
|||
for key, value in self.headers.items():
|
||||
response[key] = value
|
||||
|
||||
self.finalize_throttles(request, response)
|
||||
|
||||
return response
|
||||
|
||||
def handle_exception(self, exc):
|
||||
|
@ -456,6 +412,7 @@ class APIView(View):
|
|||
handler = self.http_method_not_allowed
|
||||
|
||||
response = handler(request, *args, **kwargs)
|
||||
|
||||
except Exception as exc:
|
||||
response = self.handle_exception(exc)
|
||||
|
||||
|
@ -468,7 +425,7 @@ class APIView(View):
|
|||
We may as well implement this as Django will otherwise provide
|
||||
a less useful default implementation.
|
||||
"""
|
||||
return Ok(self.metadata(request))
|
||||
return Response(self.metadata(request), status=status.HTTP_200_OK)
|
||||
|
||||
def metadata(self, request):
|
||||
"""
|
||||
|
@ -478,7 +435,7 @@ class APIView(View):
|
|||
# By default we can't provide any form-like information, however the
|
||||
# generic views override this implementation and add additional
|
||||
# information for POST and PUT methods, based on the serializer.
|
||||
ret = OrderedDict()
|
||||
ret = SortedDict()
|
||||
ret['name'] = self.get_view_name()
|
||||
ret['description'] = self.get_view_description()
|
||||
ret['renders'] = [renderer.media_type for renderer in self.renderer_classes]
|
||||
|
@ -487,7 +444,7 @@ class APIView(View):
|
|||
|
||||
|
||||
def api_server_error(request, *args, **kwargs):
|
||||
if settings.DEBUG is False and request.META.get('CONTENT_TYPE', None) == "application/json":
|
||||
return HttpResponse(json.dumps({"error": _("Server application error")}),
|
||||
if settings.DEBUG == False and request.META['CONTENT_TYPE'] == "application/json":
|
||||
return HttpResponse(json.dumps({"error": "Server application error"}),
|
||||
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||
return server_error(request, *args, **kwargs)
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,39 +14,16 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# This code is partially taken from django-rest-framework:
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
from functools import update_wrapper
|
||||
from django.utils.decorators import classonlymethod
|
||||
from django.utils.translation import ugettext as _
|
||||
|
||||
from . import views
|
||||
from . import mixins
|
||||
from . import generics
|
||||
from . import pagination
|
||||
|
||||
|
||||
class ViewSetMixin(object):
|
||||
|
@ -82,8 +57,8 @@ class ViewSetMixin(object):
|
|||
"keyword argument to %s(). Don't do that."
|
||||
% (key, cls.__name__))
|
||||
if not hasattr(cls, key):
|
||||
raise TypeError("%s() received an invalid keyword %r"
|
||||
% (cls.__name__, key))
|
||||
raise TypeError("%s() received an invalid keyword %r" % (
|
||||
cls.__name__, key))
|
||||
|
||||
def view(request, *args, **kwargs):
|
||||
self = cls(**initkwargs)
|
||||
|
@ -134,25 +109,6 @@ class ViewSetMixin(object):
|
|||
return super().check_permissions(request, action=action, obj=obj)
|
||||
|
||||
|
||||
class NestedViewSetMixin(object):
|
||||
def get_queryset(self):
|
||||
return self._filter_queryset_by_parents_lookups(super().get_queryset())
|
||||
|
||||
def _filter_queryset_by_parents_lookups(self, queryset):
|
||||
parents_query_dict = self._get_parents_query_dict()
|
||||
if parents_query_dict:
|
||||
return queryset.filter(**parents_query_dict)
|
||||
else:
|
||||
return queryset
|
||||
|
||||
def _get_parents_query_dict(self):
|
||||
result = {}
|
||||
for kwarg_name in self.kwargs:
|
||||
query_value = self.kwargs.get(kwarg_name)
|
||||
result[kwarg_name] = query_value
|
||||
return result
|
||||
|
||||
|
||||
class ViewSet(ViewSetMixin, views.APIView):
|
||||
"""
|
||||
The base ViewSet class does not provide any actions by default.
|
||||
|
@ -168,14 +124,14 @@ class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
|
|||
"""
|
||||
pass
|
||||
|
||||
|
||||
class ReadOnlyListViewSet(GenericViewSet):
|
||||
class ReadOnlyListViewSet(pagination.HeadersPaginationMixin,
|
||||
pagination.ConditionalPaginationMixin,
|
||||
GenericViewSet):
|
||||
"""
|
||||
A viewset that provides default `list()` action.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class ReadOnlyModelViewSet(mixins.RetrieveModelMixin,
|
||||
mixins.ListModelMixin,
|
||||
GenericViewSet):
|
||||
|
@ -198,22 +154,15 @@ class ModelViewSet(mixins.CreateModelMixin,
|
|||
pass
|
||||
|
||||
|
||||
class ModelCrudViewSet(ModelViewSet):
|
||||
class ModelCrudViewSet(pagination.HeadersPaginationMixin,
|
||||
pagination.ConditionalPaginationMixin,
|
||||
ModelViewSet):
|
||||
pass
|
||||
|
||||
|
||||
class ModelListViewSet(mixins.RetrieveModelMixin,
|
||||
class ModelListViewSet(pagination.HeadersPaginationMixin,
|
||||
pagination.ConditionalPaginationMixin,
|
||||
mixins.RetrieveModelMixin,
|
||||
mixins.ListModelMixin,
|
||||
GenericViewSet):
|
||||
pass
|
||||
|
||||
|
||||
class ModelUpdateRetrieveViewSet(mixins.UpdateModelMixin,
|
||||
mixins.RetrieveModelMixin,
|
||||
GenericViewSet):
|
||||
pass
|
||||
|
||||
|
||||
class ModelRetrieveViewSet(mixins.RetrieveModelMixin,
|
||||
GenericViewSet):
|
||||
pass
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -15,17 +13,19 @@
|
|||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
import sys
|
||||
|
||||
# Patch api view for correctly return 401 responses on
|
||||
# request is authenticated instead of 403
|
||||
from django.apps import AppConfig
|
||||
|
||||
from . import monkey
|
||||
|
||||
class BaseAppConfig(AppConfig):
|
||||
name = "taiga.base"
|
||||
verbose_name = "Base App Config"
|
||||
|
||||
def ready(self):
|
||||
from .signals.thumbnails import connect_thumbnail_signals
|
||||
from .signals.cleanup_files import connect_cleanup_files_signals
|
||||
print("Monkey patching...", file=sys.stderr)
|
||||
monkey.patch_restframework()
|
||||
monkey.patch_serializer()
|
||||
|
||||
connect_thumbnail_signals()
|
||||
connect_cleanup_files_signals()
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -20,7 +18,10 @@ from taiga.base.exceptions import BaseException
|
|||
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
|
||||
|
||||
class ConnectorBaseException(BaseException):
|
||||
status_code = 400
|
||||
default_detail = _("Connection error.")
|
||||
|
||||
|
||||
class GitHubApiError(ConnectorBaseException):
|
||||
pass
|
||||
|
|
|
@ -0,0 +1,160 @@
|
|||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import requests
|
||||
import json
|
||||
|
||||
from collections import namedtuple
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from . import exceptions as exc
|
||||
|
||||
|
||||
######################################################
|
||||
## Data
|
||||
######################################################
|
||||
|
||||
CLIENT_ID = getattr(settings, "GITHUB_API_CLIENT_ID", None)
|
||||
CLIENT_SECRET = getattr(settings, "GITHUB_API_CLIENT_SECRET", None)
|
||||
|
||||
URL = getattr(settings, "GITHUB_URL", "https://github.com/")
|
||||
API_URL = getattr(settings, "GITHUB_API_URL", "https://api.github.com/")
|
||||
API_RESOURCES_URLS = {
|
||||
"login": {
|
||||
"authorize": "login/oauth/authorize",
|
||||
"access-token": "login/oauth/access_token"
|
||||
},
|
||||
"user": {
|
||||
"profile": "user",
|
||||
"emails": "user/emails"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
HEADERS = {"Accept": "application/json",}
|
||||
|
||||
AuthInfo = namedtuple("AuthInfo", ["access_token"])
|
||||
User = namedtuple("User", ["id", "username", "full_name", "bio"])
|
||||
Email = namedtuple("Email", ["email", "is_primary"])
|
||||
|
||||
|
||||
######################################################
|
||||
## utils
|
||||
######################################################
|
||||
|
||||
def _build_url(*args, **kwargs) -> str:
|
||||
"""
|
||||
Return a valid url.
|
||||
"""
|
||||
resource_url = API_RESOURCES_URLS
|
||||
for key in args:
|
||||
resource_url = resource_url[key]
|
||||
|
||||
if kwargs:
|
||||
resource_url = resource_url.format(**kwargs)
|
||||
|
||||
return urljoin(API_URL, resource_url)
|
||||
|
||||
|
||||
def _get(url:str, headers:dict) -> dict:
|
||||
"""
|
||||
Make a GET call.
|
||||
"""
|
||||
response = requests.get(url, headers=headers)
|
||||
|
||||
data = response.json()
|
||||
if response.status_code != 200:
|
||||
raise exc.GitHubApiError({"status_code": response.status_code,
|
||||
"error": data.get("error", "")})
|
||||
return data
|
||||
|
||||
|
||||
def _post(url:str, params:dict, headers:dict) -> dict:
|
||||
"""
|
||||
Make a POST call.
|
||||
"""
|
||||
response = requests.post(url, params=params, headers=headers)
|
||||
|
||||
data = response.json()
|
||||
if response.status_code != 200 or "error" in data:
|
||||
raise exc.GitHubApiError({"status_code": response.status_code,
|
||||
"error": data.get("error", "")})
|
||||
return data
|
||||
|
||||
|
||||
######################################################
|
||||
## Simple calls
|
||||
######################################################
|
||||
|
||||
def login(access_code:str, client_id:str=CLIENT_ID, client_secret:str=CLIENT_SECRET,
|
||||
headers:dict=HEADERS):
|
||||
"""
|
||||
Get access_token fron an user authorized code, the client id and the client secret key.
|
||||
(See https://developer.github.com/v3/oauth/#web-application-flow).
|
||||
"""
|
||||
url = urljoin(URL, "login/oauth/access_token")
|
||||
params={"code": access_code,
|
||||
"client_id": client_id,
|
||||
"client_secret": client_secret,
|
||||
"scope": "user:emails"}
|
||||
data = _post(url, params=params, headers=headers)
|
||||
return AuthInfo(access_token=data.get("access_token", None))
|
||||
|
||||
|
||||
def get_user_profile(headers:dict=HEADERS):
|
||||
"""
|
||||
Get authenticated user info.
|
||||
(See https://developer.github.com/v3/users/#get-the-authenticated-user).
|
||||
"""
|
||||
url = _build_url("user", "profile")
|
||||
data = _get(url, headers=headers)
|
||||
return User(id=data.get("id", None),
|
||||
username=data.get("login", None),
|
||||
full_name=(data.get("name", None) or ""),
|
||||
bio=(data.get("bio", None) or ""))
|
||||
|
||||
|
||||
def get_user_emails(headers:dict=HEADERS) -> list:
|
||||
"""
|
||||
Get a list with all emails of the authenticated user.
|
||||
(See https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user).
|
||||
"""
|
||||
url = _build_url("user", "emails")
|
||||
data = _get(url, headers=headers)
|
||||
return [Email(email=e.get("email", None), is_primary=e.get("primary", False))
|
||||
for e in data]
|
||||
|
||||
|
||||
######################################################
|
||||
## Convined calls
|
||||
######################################################
|
||||
|
||||
def me(access_code:str) -> tuple:
|
||||
"""
|
||||
Connect to a github account and get all personal info (profile and the primary email).
|
||||
"""
|
||||
auth_info = login(access_code)
|
||||
|
||||
headers = HEADERS.copy()
|
||||
headers["Authorization"] = "token {}".format(auth_info.access_token)
|
||||
|
||||
user = get_user_profile(headers=headers)
|
||||
emails = get_user_emails(headers=headers)
|
||||
|
||||
primary_email = next(filter(lambda x: x.is_primary, emails))
|
||||
return primary_email.email, user
|
|
@ -1,20 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from .json import JSONField
|
|
@ -1,29 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
|
||||
from django.core.serializers.json import DjangoJSONEncoder
|
||||
from django.contrib.postgres.fields import JSONField as DjangoJSONField
|
||||
|
||||
|
||||
__all__ = ["JSONField"]
|
||||
|
||||
|
||||
class JSONField(DjangoJSONField):
|
||||
def __init__(self, verbose_name=None, name=None, encoder=DjangoJSONEncoder, **kwargs):
|
||||
super().__init__(verbose_name, name, encoder, **kwargs)
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,9 +14,11 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from django_pglocks import advisory_lock
|
||||
import warnings
|
||||
|
||||
|
||||
## Rest Framework 2.4 backport some decorators.
|
||||
|
||||
def detail_route(methods=['get'], **kwargs):
|
||||
"""
|
||||
Used to mark a method on a ViewSet that should be routed for detail requests.
|
||||
|
@ -45,18 +45,31 @@ def list_route(methods=['get'], **kwargs):
|
|||
return decorator
|
||||
|
||||
|
||||
def model_pk_lock(func):
|
||||
def link(**kwargs):
|
||||
"""
|
||||
This decorator is designed to be used in ModelViewsets methods to lock them based
|
||||
on the model and the id of the selected object.
|
||||
Used to mark a method on a ViewSet that should be routed for detail GET requests.
|
||||
"""
|
||||
def decorator(self, *args, **kwargs):
|
||||
from taiga.base.utils.db import get_typename_for_model_class
|
||||
pk = self.kwargs.get(self.pk_url_kwarg, None)
|
||||
tn = get_typename_for_model_class(self.get_queryset().model)
|
||||
key = "{0}:{1}".format(tn, pk)
|
||||
|
||||
with advisory_lock(key):
|
||||
return func(self, *args, **kwargs)
|
||||
|
||||
msg = 'link is pending deprecation. Use detail_route instead.'
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
def decorator(func):
|
||||
func.bind_to_methods = ['get']
|
||||
func.detail = True
|
||||
func.permission_classes = kwargs.get('permission_classes', [])
|
||||
func.kwargs = kwargs
|
||||
return func
|
||||
return decorator
|
||||
|
||||
|
||||
def action(methods=['post'], **kwargs):
|
||||
"""
|
||||
Used to mark a method on a ViewSet that should be routed for detail POST requests.
|
||||
"""
|
||||
msg = 'action is pending deprecation. Use detail_route instead.'
|
||||
warnings.warn(msg, PendingDeprecationWarning, stacklevel=2)
|
||||
def decorator(func):
|
||||
func.bind_to_methods = methods
|
||||
func.detail = True
|
||||
func.permission_classes = kwargs.get('permission_classes', [])
|
||||
func.kwargs = kwargs
|
||||
return func
|
||||
return decorator
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,125 +14,20 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
"""
|
||||
Handled exceptions raised by REST framework.
|
||||
|
||||
In addition Django's built in 403 and 404 exceptions are handled.
|
||||
(`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
|
||||
"""
|
||||
from rest_framework import exceptions
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
|
||||
from django.core.exceptions import PermissionDenied as DjangoPermissionDenied
|
||||
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||
from django.utils.encoding import force_text
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.http import Http404
|
||||
|
||||
from . import response
|
||||
from . import status
|
||||
|
||||
import math
|
||||
from .utils.json import to_json
|
||||
|
||||
|
||||
class APIException(Exception):
|
||||
"""
|
||||
Base class for REST framework exceptions.
|
||||
Subclasses should provide `.status_code` and `.default_detail` properties.
|
||||
"""
|
||||
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
default_detail = ""
|
||||
|
||||
def __init__(self, detail=None):
|
||||
self.detail = detail or self.default_detail
|
||||
|
||||
|
||||
class ParseError(APIException):
|
||||
status_code = status.HTTP_400_BAD_REQUEST
|
||||
default_detail = _("Malformed request.")
|
||||
|
||||
|
||||
class AuthenticationFailed(APIException):
|
||||
status_code = status.HTTP_401_UNAUTHORIZED
|
||||
default_detail = _("Incorrect authentication credentials.")
|
||||
|
||||
|
||||
class NotAuthenticated(APIException):
|
||||
status_code = status.HTTP_401_UNAUTHORIZED
|
||||
default_detail = _("Authentication credentials were not provided.")
|
||||
|
||||
|
||||
class PermissionDenied(APIException):
|
||||
status_code = status.HTTP_403_FORBIDDEN
|
||||
default_detail = _("You do not have permission to perform this action.")
|
||||
|
||||
|
||||
class MethodNotAllowed(APIException):
|
||||
status_code = status.HTTP_405_METHOD_NOT_ALLOWED
|
||||
default_detail = _("Method '%s' not allowed.")
|
||||
|
||||
def __init__(self, method, detail=None):
|
||||
self.detail = (detail or self.default_detail) % method
|
||||
|
||||
|
||||
class NotAcceptable(APIException):
|
||||
status_code = status.HTTP_406_NOT_ACCEPTABLE
|
||||
default_detail = _("Could not satisfy the request's Accept header")
|
||||
|
||||
def __init__(self, detail=None, available_renderers=None):
|
||||
self.detail = detail or self.default_detail
|
||||
self.available_renderers = available_renderers
|
||||
|
||||
|
||||
class UnsupportedMediaType(APIException):
|
||||
status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
||||
default_detail = _("Unsupported media type '%s' in request.")
|
||||
|
||||
def __init__(self, media_type, detail=None):
|
||||
self.detail = (detail or self.default_detail) % media_type
|
||||
|
||||
|
||||
class Throttled(APIException):
|
||||
status_code = status.HTTP_429_TOO_MANY_REQUESTS
|
||||
default_detail = _("Request was throttled.")
|
||||
extra_detail = _("Expected available in %d second%s.")
|
||||
|
||||
def __init__(self, wait=None, detail=None):
|
||||
if wait is None:
|
||||
self.detail = detail or self.default_detail
|
||||
self.wait = None
|
||||
else:
|
||||
format = "%s%s" % ((detail or self.default_detail), self.extra_detail)
|
||||
self.detail = format % (wait, wait != 1 and "s" or "")
|
||||
self.wait = math.ceil(wait)
|
||||
|
||||
|
||||
class BaseException(APIException):
|
||||
class BaseException(exceptions.APIException):
|
||||
status_code = status.HTTP_400_BAD_REQUEST
|
||||
default_detail = _("Unexpected error")
|
||||
|
||||
|
@ -176,7 +69,7 @@ class RequestValidationError(BadRequest):
|
|||
default_detail = _("Data validation error")
|
||||
|
||||
|
||||
class PermissionDenied(PermissionDenied):
|
||||
class PermissionDenied(exceptions.PermissionDenied):
|
||||
"""
|
||||
Compatibility subclass of restframework `PermissionDenied`
|
||||
exception.
|
||||
|
@ -195,7 +88,7 @@ class PreconditionError(BadRequest):
|
|||
default_detail = _("Precondition error")
|
||||
|
||||
|
||||
class NotAuthenticated(NotAuthenticated):
|
||||
class NotAuthenticated(exceptions.NotAuthenticated):
|
||||
"""
|
||||
Compatibility subclass of restframework `NotAuthenticated`
|
||||
exception.
|
||||
|
@ -203,29 +96,6 @@ class NotAuthenticated(NotAuthenticated):
|
|||
pass
|
||||
|
||||
|
||||
class Blocked(APIException):
|
||||
"""
|
||||
Exception used on blocked projects
|
||||
"""
|
||||
status_code = status.HTTP_451_BLOCKED
|
||||
default_detail = _("Blocked element")
|
||||
|
||||
|
||||
class NotEnoughSlotsForProject(BaseException):
|
||||
"""
|
||||
Exception used on import/edition/creation project errors where the user
|
||||
hasn't slots enough
|
||||
"""
|
||||
default_detail = _("No room left for more projects.")
|
||||
|
||||
def __init__(self, is_private, total_memberships, detail=None):
|
||||
self.detail = detail or self.default_detail
|
||||
self.project_data = {
|
||||
"is_private": is_private,
|
||||
"total_memberships": total_memberships
|
||||
}
|
||||
|
||||
|
||||
def format_exception(exc):
|
||||
if isinstance(exc.detail, (dict, list, tuple,)):
|
||||
detail = exc.detail
|
||||
|
@ -251,27 +121,23 @@ def exception_handler(exc):
|
|||
to be raised.
|
||||
"""
|
||||
|
||||
if isinstance(exc, APIException):
|
||||
res = response.Response(format_exception(exc), status=exc.status_code)
|
||||
|
||||
if isinstance(exc, exceptions.APIException):
|
||||
headers = {}
|
||||
if getattr(exc, "auth_header", None):
|
||||
res["WWW-Authenticate"] = exc.auth_header
|
||||
headers["WWW-Authenticate"] = exc.auth_header
|
||||
if getattr(exc, "wait", None):
|
||||
res["X-Throttle-Wait-Seconds"] = "%d" % exc.wait
|
||||
if getattr(exc, "project_data", None):
|
||||
res["Taiga-Info-Project-Memberships"] = exc.project_data["total_memberships"]
|
||||
res["Taiga-Info-Project-Is-Private"] = exc.project_data["is_private"]
|
||||
headers["X-Throttle-Wait-Seconds"] = "%d" % exc.wait
|
||||
|
||||
return res
|
||||
detail = format_exception(exc)
|
||||
return Response(detail, status=exc.status_code, headers=headers)
|
||||
|
||||
elif isinstance(exc, Http404):
|
||||
return response.NotFound({'_error_message': str(exc)})
|
||||
return Response({'_error_message': str(exc)},
|
||||
status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
elif isinstance(exc, DjangoPermissionDenied):
|
||||
return response.Forbidden({"_error_message": str(exc)})
|
||||
return Response({"_error_message": str(exc)},
|
||||
status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
# Note: Unhandled exceptions will raise a 500 error.
|
||||
return None
|
||||
|
||||
|
||||
ValidationError = DjangoValidationError
|
||||
|
|
|
@ -1,149 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from django.forms import widgets
|
||||
from django.utils.translation import ugettext as _
|
||||
from taiga.base.api import serializers, ISO_8601
|
||||
from taiga.base.api.settings import api_settings
|
||||
|
||||
import serpy
|
||||
|
||||
|
||||
####################################################################
|
||||
# DRF Serializer fields (OLD)
|
||||
####################################################################
|
||||
# NOTE: This should be in other place, for example taiga.base.api.serializers
|
||||
|
||||
|
||||
class JSONField(serializers.WritableField):
|
||||
"""
|
||||
Json objects serializer.
|
||||
"""
|
||||
widget = widgets.Textarea
|
||||
|
||||
def to_native(self, obj):
|
||||
return obj
|
||||
|
||||
def from_native(self, data):
|
||||
return data
|
||||
|
||||
|
||||
class PgArrayField(serializers.WritableField):
|
||||
"""
|
||||
PgArray objects serializer.
|
||||
"""
|
||||
widget = widgets.Textarea
|
||||
|
||||
def to_native(self, obj):
|
||||
return obj
|
||||
|
||||
def from_native(self, data):
|
||||
return data
|
||||
|
||||
|
||||
class PickledObjectField(serializers.WritableField):
|
||||
"""
|
||||
PickledObjectField objects serializer.
|
||||
"""
|
||||
widget = widgets.Textarea
|
||||
|
||||
def to_native(self, obj):
|
||||
return obj
|
||||
|
||||
def from_native(self, data):
|
||||
return data
|
||||
|
||||
|
||||
class WatchersField(serializers.WritableField):
|
||||
def to_native(self, obj):
|
||||
return obj
|
||||
|
||||
def from_native(self, data):
|
||||
return data
|
||||
|
||||
|
||||
####################################################################
|
||||
# Serpy fields (NEW)
|
||||
####################################################################
|
||||
|
||||
class Field(serpy.Field):
|
||||
pass
|
||||
|
||||
|
||||
class MethodField(serpy.MethodField):
|
||||
pass
|
||||
|
||||
|
||||
class I18NField(Field):
|
||||
def to_value(self, value):
|
||||
ret = super(I18NField, self).to_value(value)
|
||||
return _(ret)
|
||||
|
||||
|
||||
class I18NJSONField(Field):
|
||||
"""
|
||||
Json objects serializer.
|
||||
"""
|
||||
def __init__(self, i18n_fields=(), *args, **kwargs):
|
||||
super(I18NJSONField, self).__init__(*args, **kwargs)
|
||||
self.i18n_fields = i18n_fields
|
||||
|
||||
def translate_values(self, d):
|
||||
i18n_d = {}
|
||||
if d is None:
|
||||
return d
|
||||
|
||||
for key, value in d.items():
|
||||
if isinstance(value, dict):
|
||||
i18n_d[key] = self.translate_values(value)
|
||||
|
||||
if key in self.i18n_fields:
|
||||
if isinstance(value, list):
|
||||
i18n_d[key] = [e is not None and _(str(e)) or e for e in value]
|
||||
if isinstance(value, str):
|
||||
i18n_d[key] = value is not None and _(value) or value
|
||||
else:
|
||||
i18n_d[key] = value
|
||||
|
||||
return i18n_d
|
||||
|
||||
def to_native(self, obj):
|
||||
i18n_obj = self.translate_values(obj)
|
||||
return i18n_obj
|
||||
|
||||
|
||||
class FileField(Field):
|
||||
def to_value(self, value):
|
||||
if value:
|
||||
return value.name
|
||||
return None
|
||||
|
||||
|
||||
class DateTimeField(Field):
|
||||
format = api_settings.DATETIME_FORMAT
|
||||
|
||||
def to_value(self, value):
|
||||
if value is None or self.format is None:
|
||||
return value
|
||||
|
||||
if self.format.lower() == ISO_8601:
|
||||
ret = value.isoformat()
|
||||
if ret.endswith("+00:00"):
|
||||
ret = ret[:-6] + "Z"
|
||||
return ret
|
||||
return value.strftime(self.format)
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -15,64 +13,20 @@
|
|||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
import operator
|
||||
from functools import reduce
|
||||
|
||||
import logging
|
||||
from django.db.models import Q
|
||||
from django.db.models.sql.where import ExtraWhere, OR, AND
|
||||
|
||||
from dateutil.parser import parse as parse_date
|
||||
from rest_framework import filters
|
||||
|
||||
from django.apps import apps
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.db.models import Q, OuterRef, Subquery
|
||||
from django.utils.translation import ugettext as _
|
||||
from taiga.base import tags
|
||||
|
||||
from taiga.base import exceptions as exc
|
||||
from taiga.base.api.utils import get_object_or_404
|
||||
from taiga.base.utils.db import to_tsquery
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
from taiga.projects.models import Membership
|
||||
|
||||
|
||||
def get_filter_expression_can_view_projects(user, project_id=None):
|
||||
# Filter by user permissions
|
||||
if user.is_authenticated() and user.is_superuser:
|
||||
return Q()
|
||||
elif user.is_authenticated():
|
||||
# authenticated user & project member
|
||||
membership_model = apps.get_model("projects", "Membership")
|
||||
memberships_qs = membership_model.objects.filter(user=user)
|
||||
if project_id:
|
||||
memberships_qs = memberships_qs.filter(project_id=project_id)
|
||||
memberships_qs = memberships_qs.filter(
|
||||
Q(role__permissions__contains=['view_project']) |
|
||||
Q(is_admin=True))
|
||||
|
||||
projects_list = [membership.project_id for membership in
|
||||
memberships_qs]
|
||||
|
||||
return (Q(id__in=projects_list) |
|
||||
Q(public_permissions__contains=["view_project"]))
|
||||
else:
|
||||
# external users / anonymous
|
||||
return Q(anon_permissions__contains=["view_project"])
|
||||
|
||||
|
||||
#####################################################################
|
||||
# Base and Mixins
|
||||
#####################################################################
|
||||
|
||||
class BaseFilterBackend(object):
|
||||
"""
|
||||
A base class from which all filter backend classes should inherit.
|
||||
"""
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
"""
|
||||
Return a filtered queryset.
|
||||
"""
|
||||
raise NotImplementedError(".filter_queryset() must be overridden.")
|
||||
|
||||
|
||||
class QueryParamsFilterMixin(BaseFilterBackend):
|
||||
class QueryParamsFilterMixin(filters.BaseFilterBackend):
|
||||
_special_values_dict = {
|
||||
'true': True,
|
||||
'false': False,
|
||||
|
@ -99,10 +53,7 @@ class QueryParamsFilterMixin(BaseFilterBackend):
|
|||
query_params[field_name] = field_data
|
||||
|
||||
if query_params:
|
||||
try:
|
||||
queryset = queryset.filter(**query_params)
|
||||
except ValueError:
|
||||
raise exc.BadRequest(_("Error in filter params types."))
|
||||
|
||||
return queryset
|
||||
|
||||
|
@ -126,11 +77,7 @@ class OrderByFilterMixin(QueryParamsFilterMixin):
|
|||
if field_name not in order_by_fields:
|
||||
return queryset
|
||||
|
||||
if raw_fieldname in ["owner", "-owner", "assigned_to", "-assigned_to"]:
|
||||
raw_fieldname = "{}__full_name".format(raw_fieldname)
|
||||
|
||||
# We need to add a default order if raw_fieldname gives rows with the same value
|
||||
return super().filter_queryset(request, queryset.order_by(raw_fieldname, "-id"), view)
|
||||
return super().filter_queryset(request, queryset.order_by(raw_fieldname), view)
|
||||
|
||||
|
||||
class FilterBackend(OrderByFilterMixin):
|
||||
|
@ -140,66 +87,52 @@ class FilterBackend(OrderByFilterMixin):
|
|||
pass
|
||||
|
||||
|
||||
class FilterModelAssignedUsers:
|
||||
def get_assigned_users_filter(self, model, value):
|
||||
assigned_users_ids = model.objects.order_by().filter(
|
||||
assigned_users__in=value, id=OuterRef('pk')).values('pk')
|
||||
|
||||
assigned_user_filter = Q(pk__in=Subquery(assigned_users_ids))
|
||||
assigned_to_filter = Q(assigned_to__in=value)
|
||||
|
||||
return Q(assigned_user_filter | assigned_to_filter)
|
||||
|
||||
|
||||
#####################################################################
|
||||
# Permissions filters
|
||||
#####################################################################
|
||||
|
||||
class PermissionBasedFilterBackend(FilterBackend):
|
||||
permission = None
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
project_id = None
|
||||
if (hasattr(view, "filter_fields") and "project" in view.filter_fields and
|
||||
"project" in request.QUERY_PARAMS):
|
||||
try:
|
||||
project_id = int(request.QUERY_PARAMS["project"])
|
||||
except:
|
||||
logger.error("Filtering project diferent value than an integer: {}".format(
|
||||
request.QUERY_PARAMS["project"]
|
||||
))
|
||||
raise exc.BadRequest(_("'project' must be an integer value."))
|
||||
if hasattr(view, "filter_fields") and "project" in view.filter_fields:
|
||||
project_id = request.QUERY_PARAMS.get("project", None)
|
||||
|
||||
qs = queryset
|
||||
|
||||
if request.user.is_authenticated() and request.user.is_superuser:
|
||||
qs = qs
|
||||
elif request.user.is_authenticated():
|
||||
membership_model = apps.get_model('projects', 'Membership')
|
||||
memberships_qs = membership_model.objects.filter(user=request.user)
|
||||
memberships_qs = Membership.objects.filter(user=request.user)
|
||||
if project_id:
|
||||
memberships_qs = memberships_qs.filter(project_id=project_id)
|
||||
memberships_qs = memberships_qs.filter(Q(role__permissions__contains=[self.permission]) |
|
||||
Q(is_admin=True))
|
||||
|
||||
# Force users_role table inclusion
|
||||
memberships_qs = memberships_qs.exclude(role__slug="not valid slug")
|
||||
where_sql = ["users_role.permissions @> ARRAY['{}']".format(self.permission)]
|
||||
memberships_qs = memberships_qs.extra(where=where_sql)
|
||||
|
||||
projects_list = [membership.project_id for membership in memberships_qs]
|
||||
|
||||
qs = qs.filter(Q(project_id__in=projects_list) |
|
||||
Q(project__public_permissions__contains=[self.permission]))
|
||||
if len(projects_list) == 0:
|
||||
qs = qs.filter(Q(project__owner=request.user))
|
||||
elif len(projects_list) == 1:
|
||||
qs = qs.filter(Q(project__owner=request.user) | Q(project=projects_list[0]))
|
||||
else:
|
||||
qs = qs.filter(project__anon_permissions__contains=[self.permission])
|
||||
qs = qs.filter(Q(project__owner=request.user) | Q(project__in=projects_list))
|
||||
extra_where = ExtraWhere(["projects_project.public_permissions @> ARRAY['{}']".format(
|
||||
self.permission)], [])
|
||||
qs.query.where.add(extra_where, OR)
|
||||
else:
|
||||
qs = qs.exclude(project__owner=-1)
|
||||
extra_where = ExtraWhere(["projects_project.anon_permissions @> ARRAY['{}']".format(
|
||||
self.permission)], [])
|
||||
qs.query.where.add(extra_where, AND)
|
||||
|
||||
return super().filter_queryset(request, qs, view)
|
||||
return super().filter_queryset(request, qs.distinct(), view)
|
||||
|
||||
|
||||
class CanViewProjectFilterBackend(PermissionBasedFilterBackend):
|
||||
permission = "view_project"
|
||||
|
||||
|
||||
class CanViewEpicsFilterBackend(PermissionBasedFilterBackend):
|
||||
permission = "view_epics"
|
||||
|
||||
|
||||
class CanViewUsFilterBackend(PermissionBasedFilterBackend):
|
||||
permission = "view_us"
|
||||
|
||||
|
@ -224,10 +157,6 @@ class CanViewMilestonesFilterBackend(PermissionBasedFilterBackend):
|
|||
permission = "view_milestones"
|
||||
|
||||
|
||||
#####################################################################
|
||||
# Attachments filters
|
||||
#####################################################################
|
||||
|
||||
class PermissionBasedAttachmentFilterBackend(PermissionBasedFilterBackend):
|
||||
permission = None
|
||||
|
||||
|
@ -238,10 +167,6 @@ class PermissionBasedAttachmentFilterBackend(PermissionBasedFilterBackend):
|
|||
return qs.filter(content_type=ct)
|
||||
|
||||
|
||||
class CanViewEpicAttachmentFilterBackend(PermissionBasedAttachmentFilterBackend):
|
||||
permission = "view_epics"
|
||||
|
||||
|
||||
class CanViewUserStoryAttachmentFilterBackend(PermissionBasedAttachmentFilterBackend):
|
||||
permission = "view_us"
|
||||
|
||||
|
@ -258,460 +183,71 @@ class CanViewWikiAttachmentFilterBackend(PermissionBasedAttachmentFilterBackend)
|
|||
permission = "view_wiki_pages"
|
||||
|
||||
|
||||
#####################################################################
|
||||
# User filters
|
||||
#####################################################################
|
||||
|
||||
class MembersFilterBackend(PermissionBasedFilterBackend):
|
||||
permission = "view_project"
|
||||
|
||||
class CanViewProjectObjFilterBackend(FilterBackend):
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
project_id = None
|
||||
project = None
|
||||
qs = queryset.filter(is_active=True)
|
||||
if "project" in request.QUERY_PARAMS:
|
||||
try:
|
||||
project_id = int(request.QUERY_PARAMS["project"])
|
||||
except:
|
||||
logger.error("Filtering project diferent value than an integer: {}".format(
|
||||
request.QUERY_PARAMS["project"]))
|
||||
raise exc.BadRequest(_("'project' must be an integer value."))
|
||||
|
||||
if project_id:
|
||||
Project = apps.get_model('projects', 'Project')
|
||||
project = get_object_or_404(Project, pk=project_id)
|
||||
|
||||
if request.user.is_authenticated() and request.user.is_superuser:
|
||||
qs = qs
|
||||
elif request.user.is_authenticated():
|
||||
Membership = apps.get_model('projects', 'Membership')
|
||||
memberships_qs = Membership.objects.filter(user=request.user)
|
||||
if project_id:
|
||||
memberships_qs = memberships_qs.filter(project_id=project_id)
|
||||
memberships_qs = memberships_qs.filter(Q(role__permissions__contains=[self.permission]) |
|
||||
Q(is_admin=True))
|
||||
|
||||
projects_list = [membership.project_id for membership in memberships_qs]
|
||||
|
||||
if project:
|
||||
is_member = project.id in projects_list
|
||||
has_project_public_view_permission = "view_project" in project.public_permissions
|
||||
if not is_member and not has_project_public_view_permission:
|
||||
qs = qs.none()
|
||||
|
||||
q = Q(memberships__project_id__in=projects_list) | Q(id=request.user.id)
|
||||
|
||||
# If there is no selected project we want access to users from public projects
|
||||
if not project:
|
||||
q = q | Q(memberships__project__public_permissions__contains=[self.permission])
|
||||
|
||||
qs = qs.filter(q)
|
||||
|
||||
else:
|
||||
if project and "view_project" not in project.anon_permissions:
|
||||
qs = qs.none()
|
||||
|
||||
qs = qs.filter(memberships__project__anon_permissions__contains=[self.permission])
|
||||
|
||||
return qs.distinct()
|
||||
|
||||
|
||||
#####################################################################
|
||||
# Webhooks filters
|
||||
#####################################################################
|
||||
|
||||
class BaseIsProjectAdminFilterBackend(object):
|
||||
def get_project_ids(self, request, view):
|
||||
project_id = None
|
||||
if hasattr(view, "filter_fields") and "project" in view.filter_fields:
|
||||
project_id = request.QUERY_PARAMS.get("project", None)
|
||||
|
||||
qs = queryset
|
||||
|
||||
if request.user.is_authenticated() and request.user.is_superuser:
|
||||
return None
|
||||
|
||||
if not request.user.is_authenticated():
|
||||
return []
|
||||
|
||||
membership_model = apps.get_model('projects', 'Membership')
|
||||
memberships_qs = membership_model.objects.filter(user=request.user, is_admin=True)
|
||||
qs = qs
|
||||
elif request.user.is_authenticated():
|
||||
memberships_qs = Membership.objects.filter(user=request.user)
|
||||
if project_id:
|
||||
memberships_qs = memberships_qs.filter(project_id=project_id)
|
||||
|
||||
memberships_qs = memberships_qs.exclude(role__slug="not valid slug") # Force users_role table inclusion
|
||||
memberships_qs = memberships_qs.extra(where=["users_role.permissions @> ARRAY['view_project']"])
|
||||
projects_list = [membership.project_id for membership in memberships_qs]
|
||||
|
||||
return projects_list
|
||||
if len(projects_list) == 0:
|
||||
qs = qs.filter(Q(owner=request.user))
|
||||
elif len(projects_list) == 1:
|
||||
qs = qs.filter(Q(owner=request.user) | Q(id=projects_list[0]))
|
||||
else:
|
||||
qs = qs.filter(Q(owner=request.user) | Q(id__in=projects_list))
|
||||
qs.query.where.add(ExtraWhere(["projects_project.public_permissions @> ARRAY['view_project']"], []), OR)
|
||||
else:
|
||||
qs.query.where.add(ExtraWhere(["projects_project.anon_permissions @> ARRAY['view_project']"], []), AND)
|
||||
|
||||
return super().filter_queryset(request, qs.distinct(), view)
|
||||
|
||||
|
||||
class IsProjectAdminFilterBackend(FilterBackend, BaseIsProjectAdminFilterBackend):
|
||||
class IsProjectMemberFilterBackend(FilterBackend):
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
project_ids = self.get_project_ids(request, view)
|
||||
if project_ids is None:
|
||||
if request.user.is_authenticated() and request.user.is_superuser:
|
||||
queryset = queryset
|
||||
elif project_ids == []:
|
||||
elif request.user.is_authenticated():
|
||||
queryset = queryset.filter(Q(project__members=request.user) |
|
||||
Q(project__owner=request.user))
|
||||
else:
|
||||
queryset = queryset.none()
|
||||
else:
|
||||
queryset = queryset.filter(project_id__in=project_ids)
|
||||
|
||||
return super().filter_queryset(request, queryset, view)
|
||||
|
||||
|
||||
class IsProjectAdminFromWebhookLogFilterBackend(FilterBackend, BaseIsProjectAdminFilterBackend):
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
project_ids = self.get_project_ids(request, view)
|
||||
if project_ids is None:
|
||||
queryset = queryset
|
||||
elif project_ids == []:
|
||||
queryset = queryset.none()
|
||||
else:
|
||||
queryset = queryset.filter(webhook__project_id__in=project_ids)
|
||||
|
||||
return super().filter_queryset(request, queryset, view)
|
||||
|
||||
|
||||
#####################################################################
|
||||
# Generic Attributes filters (for User Stories, Tasks and Issues)
|
||||
#####################################################################
|
||||
|
||||
class BaseRelatedFieldsFilter(FilterBackend):
|
||||
filter_name = None
|
||||
param_name = None
|
||||
exclude_param_name = None
|
||||
|
||||
def __init__(self, filter_name=None, param_name=None, exclude_param_name=None):
|
||||
if filter_name:
|
||||
self.filter_name = filter_name
|
||||
|
||||
if param_name:
|
||||
self.param_name = param_name
|
||||
|
||||
if exclude_param_name:
|
||||
self.exclude_param_name
|
||||
|
||||
def _prepare_filter_data(self, query_param_value):
|
||||
def _transform_value(value):
|
||||
try:
|
||||
return int(value)
|
||||
except:
|
||||
if value in self._special_values_dict:
|
||||
return self._special_values_dict[value]
|
||||
raise exc.BadRequest()
|
||||
|
||||
values = set([x.strip() for x in query_param_value.split(",")])
|
||||
values = map(_transform_value, values)
|
||||
return list(values)
|
||||
|
||||
def _get_queryparams(self, params, mode=''):
|
||||
param_name = self.exclude_param_name if mode == 'exclude' else self.param_name or self.filter_name
|
||||
raw_value = params.get(param_name, None)
|
||||
if raw_value:
|
||||
value = self._prepare_filter_data(raw_value)
|
||||
if None in value:
|
||||
qs_in_kwargs = {"{}__in".format(self.filter_name): [v for v in value if v is not None]}
|
||||
qs_isnull_kwargs = {"{}__isnull".format(self.filter_name): True}
|
||||
return Q(**qs_in_kwargs) | Q(**qs_isnull_kwargs)
|
||||
else:
|
||||
return Q(**{"{}__in".format(self.filter_name): value})
|
||||
|
||||
return None
|
||||
|
||||
def _prepare_filter_query(self, query):
|
||||
return query
|
||||
|
||||
def _prepare_exclude_query(self, query):
|
||||
return ~Q(query)
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
operations = {
|
||||
"filter": self._prepare_filter_query,
|
||||
"exclude": self._prepare_exclude_query,
|
||||
}
|
||||
|
||||
for mode, prepare_method in operations.items():
|
||||
query = self._get_queryparams(request.QUERY_PARAMS, mode=mode)
|
||||
if query:
|
||||
queryset = queryset.filter(prepare_method(query))
|
||||
|
||||
return super().filter_queryset(request, queryset, view)
|
||||
|
||||
|
||||
class OwnersFilter(BaseRelatedFieldsFilter):
|
||||
filter_name = 'owner'
|
||||
exclude_param_name = 'exclude_owner'
|
||||
|
||||
|
||||
class AssignedToFilter(BaseRelatedFieldsFilter):
|
||||
filter_name = 'assigned_to'
|
||||
exclude_param_name = 'exclude_assigned_to'
|
||||
|
||||
|
||||
class AssignedUsersFilter(FilterModelAssignedUsers, BaseRelatedFieldsFilter):
|
||||
filter_name = 'assigned_users'
|
||||
exclude_param_name = 'exclude_assigned_users'
|
||||
|
||||
def _get_queryparams(self, params, mode=''):
|
||||
param_name = self.exclude_param_name if mode == 'exclude' else self.param_name or self.filter_name
|
||||
raw_value = params.get(param_name, None)
|
||||
if raw_value:
|
||||
value = self._prepare_filter_data(raw_value)
|
||||
UserStoryModel = apps.get_model("userstories", "UserStory")
|
||||
|
||||
if None in value:
|
||||
value.remove(None)
|
||||
assigned_users_ids = UserStoryModel.objects.order_by().filter(
|
||||
assigned_users__isnull=True,
|
||||
id=OuterRef('pk')).values('pk')
|
||||
|
||||
assigned_user_filter_none = Q(pk__in=Subquery(assigned_users_ids))
|
||||
assigned_to_filter_none = Q(assigned_to__isnull=True)
|
||||
|
||||
return (self.get_assigned_users_filter(UserStoryModel, value)
|
||||
| Q(assigned_user_filter_none, assigned_to_filter_none))
|
||||
else:
|
||||
return self.get_assigned_users_filter(UserStoryModel, value)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class StatusesFilter(BaseRelatedFieldsFilter):
|
||||
filter_name = 'status'
|
||||
exclude_param_name = 'exclude_status'
|
||||
|
||||
|
||||
class IssueTypesFilter(BaseRelatedFieldsFilter):
|
||||
filter_name = 'type'
|
||||
param_name = 'type'
|
||||
exclude_param_name = 'exclude_type'
|
||||
|
||||
|
||||
class PrioritiesFilter(BaseRelatedFieldsFilter):
|
||||
filter_name = 'priority'
|
||||
exclude_param_name = 'exclude_priority'
|
||||
|
||||
|
||||
class SeveritiesFilter(BaseRelatedFieldsFilter):
|
||||
filter_name = 'severity'
|
||||
exclude_param_name = 'exclude_severity'
|
||||
return super().filter_queryset(request, queryset.distinct(), view)
|
||||
|
||||
|
||||
class TagsFilter(FilterBackend):
|
||||
filter_name = 'tags'
|
||||
exclude_param_name = 'exclude_tags'
|
||||
|
||||
def __init__(self, filter_name=None, exclude_param_name=None):
|
||||
if filter_name:
|
||||
def __init__(self, filter_name='tags'):
|
||||
self.filter_name = filter_name
|
||||
|
||||
if exclude_param_name:
|
||||
self.exclude_param_name = exclude_param_name
|
||||
|
||||
def _get_tags_queryparams(self, params, mode=''):
|
||||
param_name = self.exclude_param_name if mode == "exclude" else self.filter_name
|
||||
tags = params.get(param_name, None)
|
||||
if tags:
|
||||
return tags.split(",")
|
||||
|
||||
return None
|
||||
|
||||
def _prepare_filter_query(self, query):
|
||||
return Q(tags__contains=query)
|
||||
|
||||
def _prepare_exclude_query(self, tags):
|
||||
queries = [Q(tags__contains=[tag]) for tag in tags]
|
||||
query = queries.pop()
|
||||
for item in queries:
|
||||
query |= item
|
||||
|
||||
return ~Q(query)
|
||||
def _get_tags_queryparams(self, params):
|
||||
return params.get(self.filter_name, "")
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
operations = {
|
||||
"filter": self._prepare_filter_query,
|
||||
"exclude": self._prepare_exclude_query,
|
||||
}
|
||||
|
||||
for mode, prepare_method in operations.items():
|
||||
query = self._get_tags_queryparams(request.QUERY_PARAMS, mode=mode)
|
||||
if query:
|
||||
queryset = queryset.filter(prepare_method(query))
|
||||
query_tags = self._get_tags_queryparams(request.QUERY_PARAMS)
|
||||
if query_tags:
|
||||
queryset = tags.filter(queryset, contains=query_tags)
|
||||
|
||||
return super().filter_queryset(request, queryset, view)
|
||||
|
||||
|
||||
class WatchersFilter(FilterBackend):
|
||||
filter_name = 'watchers'
|
||||
|
||||
def __init__(self, filter_name=None):
|
||||
if filter_name:
|
||||
self.filter_name = filter_name
|
||||
|
||||
def _get_watchers_queryparams(self, params):
|
||||
watchers = params.get(self.filter_name, None)
|
||||
if watchers:
|
||||
return watchers.split(",")
|
||||
|
||||
return None
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
query_watchers = self._get_watchers_queryparams(request.QUERY_PARAMS)
|
||||
if query_watchers:
|
||||
WatchedModel = apps.get_model("notifications", "Watched")
|
||||
watched_type = ContentType.objects.get_for_model(queryset.model)
|
||||
|
||||
try:
|
||||
watched_ids = (WatchedModel.objects.filter(content_type=watched_type,
|
||||
user__id__in=query_watchers)
|
||||
.values_list("object_id", flat=True))
|
||||
queryset = queryset.filter(id__in=watched_ids)
|
||||
except ValueError:
|
||||
raise exc.BadRequest(_("Error in filter params types."))
|
||||
|
||||
return super().filter_queryset(request, queryset, view)
|
||||
|
||||
|
||||
class BaseCompareFilter(FilterBackend):
|
||||
operators = ["", "lt", "gt", "lte", "gte"]
|
||||
|
||||
def __init__(self, filter_name_base=None, operators=None):
|
||||
if filter_name_base:
|
||||
self.filter_name_base = filter_name_base
|
||||
|
||||
def _get_filter_names(self):
|
||||
return [
|
||||
self._get_filter_name(operator)
|
||||
for operator in self.operators
|
||||
]
|
||||
|
||||
def _get_filter_name(self, operator):
|
||||
if operator and len(operator) > 0:
|
||||
return "{base}__{operator}".format(
|
||||
base=self.filter_name_base, operator=operator
|
||||
)
|
||||
else:
|
||||
return self.filter_name_base
|
||||
|
||||
def _get_constraints(self, params):
|
||||
constraints = {}
|
||||
for filter_name in self._get_filter_names():
|
||||
raw_value = params.get(filter_name, None)
|
||||
if raw_value is not None:
|
||||
constraints[filter_name] = self._get_value(raw_value)
|
||||
return constraints
|
||||
|
||||
def _get_value(self, raw_value):
|
||||
return raw_value
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
constraints = self._get_constraints(request.QUERY_PARAMS)
|
||||
|
||||
if len(constraints) > 0:
|
||||
queryset = queryset.filter(**constraints)
|
||||
|
||||
return super().filter_queryset(request, queryset, view)
|
||||
|
||||
|
||||
class BaseDateFilter(BaseCompareFilter):
|
||||
def _get_value(self, raw_value):
|
||||
return parse_date(raw_value)
|
||||
|
||||
|
||||
class CreatedDateFilter(BaseDateFilter):
|
||||
filter_name_base = "created_date"
|
||||
|
||||
|
||||
class ModifiedDateFilter(BaseDateFilter):
|
||||
filter_name_base = "modified_date"
|
||||
|
||||
|
||||
class FinishedDateFilter(BaseDateFilter):
|
||||
filter_name_base = "finished_date"
|
||||
|
||||
|
||||
class FinishDateFilter(BaseDateFilter):
|
||||
filter_name_base = "finish_date"
|
||||
|
||||
|
||||
class EstimatedStartFilter(BaseDateFilter):
|
||||
filter_name_base = "estimated_start"
|
||||
|
||||
|
||||
class EstimatedFinishFilter(BaseDateFilter):
|
||||
filter_name_base = "estimated_finish"
|
||||
|
||||
|
||||
class MilestoneEstimatedStartFilter(BaseDateFilter):
|
||||
filter_name_base = "milestone__estimated_start"
|
||||
|
||||
|
||||
class MilestoneEstimatedFinishFilter(BaseDateFilter):
|
||||
filter_name_base = "milestone__estimated_finish"
|
||||
|
||||
|
||||
#####################################################################
|
||||
# Text search filters
|
||||
#####################################################################
|
||||
|
||||
class QFilter(FilterBackend):
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
q = request.QUERY_PARAMS.get('q', None)
|
||||
if q:
|
||||
table = queryset.model._meta.db_table
|
||||
where_clause = ("""
|
||||
to_tsvector('simple',
|
||||
coalesce({table}.subject, '') || ' ' ||
|
||||
coalesce(array_to_string({table}.tags, ' '), '') || ' ' ||
|
||||
coalesce({table}.ref) || ' ' ||
|
||||
coalesce({table}.description, '')) @@ to_tsquery('simple', %s)
|
||||
""".format(table=table))
|
||||
|
||||
queryset = queryset.extra(where=[where_clause], params=[to_tsquery(q)])
|
||||
qs_args = [Q(subject__icontains=x) for x in q.split()]
|
||||
qs_args += [Q(ref=x) for x in q.split() if x.isdigit()]
|
||||
queryset = queryset.filter(reduce(operator.or_, qs_args))
|
||||
|
||||
return queryset
|
||||
|
||||
|
||||
class RoleFilter(BaseRelatedFieldsFilter):
|
||||
filter_name = "role_id"
|
||||
param_name = "role"
|
||||
exclude_param_name = "exclude_role"
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
Membership = apps.get_model('projects', 'Membership')
|
||||
|
||||
operations = {
|
||||
"filter": self._prepare_filter_query,
|
||||
"exclude": self._prepare_exclude_query,
|
||||
}
|
||||
|
||||
for mode, qs_method in operations.items():
|
||||
query = self._get_queryparams(request.QUERY_PARAMS, mode=mode)
|
||||
if query:
|
||||
memberships = Membership.objects.filter(query).exclude(user__isnull=True).values_list("user_id", flat=True)
|
||||
if memberships:
|
||||
queryset = queryset.filter(qs_method(Q(assigned_to__in=memberships)))
|
||||
|
||||
return FilterBackend.filter_queryset(self, request, queryset, view)
|
||||
|
||||
|
||||
class UserStoriesRoleFilter(FilterModelAssignedUsers, BaseRelatedFieldsFilter):
|
||||
filter_name = "role_id"
|
||||
param_name = "role"
|
||||
exclude_param_name = 'exclude_role'
|
||||
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
Membership = apps.get_model('projects', 'Membership')
|
||||
|
||||
operations = {
|
||||
"filter": self._prepare_filter_query,
|
||||
"exclude": self._prepare_exclude_query,
|
||||
}
|
||||
|
||||
for mode, qs_method in operations.items():
|
||||
query = self._get_queryparams(request.QUERY_PARAMS, mode=mode)
|
||||
if query:
|
||||
memberships = Membership.objects.filter(query).exclude(user__isnull=True).values_list("user_id", flat=True)
|
||||
if memberships:
|
||||
user_story_model = apps.get_model("userstories", "UserStory")
|
||||
queryset = queryset.filter(
|
||||
qs_method(Q(self.get_assigned_users_filter(user_story_model, memberships)))
|
||||
)
|
||||
|
||||
return FilterBackend.filter_queryset(self, request, queryset, view)
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
|
|
@ -1,44 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from djmail import template_mail
|
||||
import premailer
|
||||
|
||||
import logging
|
||||
|
||||
|
||||
# Hide CSS warnings messages if debug mode is disable
|
||||
if not getattr(settings, "DEBUG", False):
|
||||
premailer.premailer.cssutils.log.setLevel(logging.CRITICAL)
|
||||
|
||||
|
||||
class InlineCSSTemplateMail(template_mail.TemplateMail):
|
||||
def _render_message_body_as_html(self, context):
|
||||
html = super()._render_message_body_as_html(context)
|
||||
|
||||
# Transform CSS into line style attributes
|
||||
return premailer.transform(html)
|
||||
|
||||
|
||||
class MagicMailBuilder(template_mail.MagicMailBuilder):
|
||||
pass
|
||||
|
||||
|
||||
mail_builder = MagicMailBuilder(template_mail_cls=InlineCSSTemplateMail)
|
|
@ -1,283 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import datetime
|
||||
|
||||
from django.apps import apps
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management.base import BaseCommand
|
||||
from django.utils import timezone
|
||||
|
||||
from taiga.base.mails import InlineCSSTemplateMail
|
||||
from taiga.base.mails import mail_builder
|
||||
|
||||
from taiga.projects.models import Project, Membership
|
||||
from taiga.projects.history.models import HistoryEntry
|
||||
from taiga.projects.history.services import get_history_queryset_by_model_instance
|
||||
|
||||
from taiga.users.services import get_user_photo_url
|
||||
from taiga.front.templatetags.functions import resolve as resolve_front_url
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = 'Send an example of all emails'
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument('--locale', '-l',
|
||||
default=None,
|
||||
dest='locale',
|
||||
help='Send emails in an specific language.')
|
||||
parser.add_argument('email',
|
||||
help='Emeil address to send sample emails.')
|
||||
|
||||
|
||||
def handle(self, *args, **options):
|
||||
locale = options.get('locale')
|
||||
email_address = options.get('email')
|
||||
|
||||
# Register email
|
||||
context = {"lang": locale,
|
||||
"user": get_user_model().objects.all().order_by("?").first(),
|
||||
"cancel_token": "cancel-token"}
|
||||
|
||||
email = mail_builder.registered_user(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Membership invitation
|
||||
membership = Membership.objects.order_by("?").filter(user__isnull=True).first()
|
||||
membership.invited_by = get_user_model().objects.all().order_by("?").first()
|
||||
membership.invitation_extra_text = "Text example, Text example,\nText example,\n\nText example"
|
||||
|
||||
context = {"lang": locale, "membership": membership}
|
||||
email = mail_builder.membership_invitation(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Membership notification
|
||||
context = {"lang": locale,
|
||||
"membership": Membership.objects.order_by("?").filter(user__isnull=False).first()}
|
||||
email = mail_builder.membership_notification(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Feedback
|
||||
context = {
|
||||
"lang": locale,
|
||||
"feedback_entry": {
|
||||
"full_name": "Test full name",
|
||||
"email": "test@email.com",
|
||||
"comment": "Test comment",
|
||||
},
|
||||
"extra": {
|
||||
"key1": "value1",
|
||||
"key2": "value2",
|
||||
},
|
||||
}
|
||||
email = mail_builder.feedback_notification(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Password recovery
|
||||
context = {"lang": locale, "user": get_user_model().objects.all().order_by("?").first()}
|
||||
email = mail_builder.password_recovery(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Change email
|
||||
context = {"lang": locale, "user": get_user_model().objects.all().order_by("?").first()}
|
||||
email = mail_builder.change_email(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Export/Import emails
|
||||
context = {
|
||||
"lang": locale,
|
||||
"user": get_user_model().objects.all().order_by("?").first(),
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"error_subject": "Error generating project dump",
|
||||
"error_message": "Error generating project dump",
|
||||
}
|
||||
email = mail_builder.export_error(email_address, context)
|
||||
email.send()
|
||||
context = {
|
||||
"lang": locale,
|
||||
"user": get_user_model().objects.all().order_by("?").first(),
|
||||
"error_subject": "Error importing project dump",
|
||||
"error_message": "Error importing project dump",
|
||||
}
|
||||
email = mail_builder.import_error(email_address, context)
|
||||
email.send()
|
||||
|
||||
deletion_date = timezone.now() + datetime.timedelta(seconds=60*60*24)
|
||||
context = {
|
||||
"lang": locale,
|
||||
"url": "http://dummyurl.com",
|
||||
"user": get_user_model().objects.all().order_by("?").first(),
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"deletion_date": deletion_date,
|
||||
}
|
||||
email = mail_builder.dump_project(email_address, context)
|
||||
email.send()
|
||||
|
||||
context = {
|
||||
"lang": locale,
|
||||
"user": get_user_model().objects.all().order_by("?").first(),
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
}
|
||||
email = mail_builder.load_dump(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Notification emails
|
||||
notification_emails = [
|
||||
("issues.Issue", "issues/issue-change"),
|
||||
("issues.Issue", "issues/issue-create"),
|
||||
("issues.Issue", "issues/issue-delete"),
|
||||
("tasks.Task", "tasks/task-change"),
|
||||
("tasks.Task", "tasks/task-create"),
|
||||
("tasks.Task", "tasks/task-delete"),
|
||||
("userstories.UserStory", "userstories/userstory-change"),
|
||||
("userstories.UserStory", "userstories/userstory-create"),
|
||||
("userstories.UserStory", "userstories/userstory-delete"),
|
||||
("milestones.Milestone", "milestones/milestone-change"),
|
||||
("milestones.Milestone", "milestones/milestone-create"),
|
||||
("milestones.Milestone", "milestones/milestone-delete"),
|
||||
("wiki.WikiPage", "wiki/wikipage-change"),
|
||||
("wiki.WikiPage", "wiki/wikipage-create"),
|
||||
("wiki.WikiPage", "wiki/wikipage-delete"),
|
||||
]
|
||||
|
||||
context = {
|
||||
"lang": locale,
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"changer": get_user_model().objects.all().order_by("?").first(),
|
||||
"history_entries": HistoryEntry.objects.all().order_by("?")[0:5],
|
||||
"user": get_user_model().objects.all().order_by("?").first(),
|
||||
}
|
||||
|
||||
for notification_email in notification_emails:
|
||||
model = apps.get_model(*notification_email[0].split("."))
|
||||
snapshot = {
|
||||
"subject": "Tests subject",
|
||||
"ref": 123123,
|
||||
"name": "Tests name",
|
||||
"slug": "test-slug"
|
||||
}
|
||||
queryset = model.objects.all().order_by("?")
|
||||
for obj in queryset:
|
||||
end = False
|
||||
entries = get_history_queryset_by_model_instance(obj).filter(is_snapshot=True).order_by("?")
|
||||
|
||||
for entry in entries:
|
||||
if entry.snapshot:
|
||||
snapshot = entry.snapshot
|
||||
end = True
|
||||
break
|
||||
if end:
|
||||
break
|
||||
context["snapshot"] = snapshot
|
||||
|
||||
cls = type("InlineCSSTemplateMail", (InlineCSSTemplateMail,), {"name": notification_email[1]})
|
||||
email = cls()
|
||||
email.send(email_address, context)
|
||||
|
||||
# Transfer Emails
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"requester": get_user_model().objects.all().order_by("?").first(),
|
||||
}
|
||||
email = mail_builder.transfer_request(email_address, context)
|
||||
email.send()
|
||||
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"receiver": get_user_model().objects.all().order_by("?").first(),
|
||||
"token": "test-token",
|
||||
"reason": "Test reason"
|
||||
}
|
||||
email = mail_builder.transfer_start(email_address, context)
|
||||
email.send()
|
||||
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"old_owner": get_user_model().objects.all().order_by("?").first(),
|
||||
"new_owner": get_user_model().objects.all().order_by("?").first(),
|
||||
"reason": "Test reason"
|
||||
}
|
||||
email = mail_builder.transfer_accept(email_address, context)
|
||||
email.send()
|
||||
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"rejecter": get_user_model().objects.all().order_by("?").first(),
|
||||
"reason": "Test reason"
|
||||
}
|
||||
email = mail_builder.transfer_reject(email_address, context)
|
||||
email.send()
|
||||
|
||||
|
||||
# Contact with project admins email
|
||||
project = Project.objects.all().order_by("?").first()
|
||||
user = get_user_model().objects.all().order_by("?").first()
|
||||
context = {
|
||||
"full_name": user.get_full_name(),
|
||||
"project_name": project.name,
|
||||
"photo_url": get_user_photo_url(user),
|
||||
"user_profile_url": resolve_front_url("user", user.username),
|
||||
"project_settings_url": resolve_front_url("project-admin", project.slug),
|
||||
"comment": "Test comment notification."
|
||||
}
|
||||
email = mail_builder.contact_notification(email_address, context)
|
||||
email.send()
|
||||
|
||||
# GitHub importer email
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"user": get_user_model().objects.all().order_by("?").first()
|
||||
}
|
||||
email = mail_builder.github_import_success(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Jira importer email
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"user": get_user_model().objects.all().order_by("?").first()
|
||||
}
|
||||
email = mail_builder.jira_import_success(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Trello importer email
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"user": get_user_model().objects.all().order_by("?").first()
|
||||
}
|
||||
email = mail_builder.trello_import_success(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Asana importer email
|
||||
context = {
|
||||
"project": Project.objects.all().order_by("?").first(),
|
||||
"user": get_user_model().objects.all().order_by("?").first()
|
||||
}
|
||||
email = mail_builder.asana_import_success(email_address, context)
|
||||
email.send()
|
||||
|
||||
# Error importer email
|
||||
context = {
|
||||
"user": get_user_model().objects.all().order_by("?").first(),
|
||||
"error_subject": "Error importing GitHub project",
|
||||
"error_message": "Error importing GitHub project",
|
||||
"project": 1234,
|
||||
"exception": "Exception message"
|
||||
}
|
||||
email = mail_builder.importer_import_error(email_address, context)
|
||||
email.send()
|
|
@ -1,8 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -16,22 +14,21 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import json
|
||||
|
||||
from django import http
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
COORS_ALLOWED_ORIGINS = "*"
|
||||
COORS_ALLOWED_METHODS = ["POST", "GET", "OPTIONS", "PUT", "DELETE", "PATCH", "HEAD"]
|
||||
COORS_ALLOWED_HEADERS = ["content-type", "x-requested-with",
|
||||
"authorization", "accept-encoding",
|
||||
"x-disable-pagination", "x-lazy-pagination",
|
||||
"x-host", "x-session-id", "set-orders"]
|
||||
"x-disable-pagination", "x-host",
|
||||
"x-session-id"]
|
||||
COORS_ALLOWED_CREDENTIALS = True
|
||||
COORS_EXPOSE_HEADERS = ["x-pagination-count", "x-paginated", "x-paginated-by",
|
||||
"x-pagination-current", "x-pagination-next", "x-pagination-prev",
|
||||
"x-site-host", "x-site-register"]
|
||||
|
||||
COORS_EXTRA_EXPOSE_HEADERS = getattr(settings, "APP_EXTRA_EXPOSE_HEADERS", [])
|
||||
"x-paginated-by", "x-pagination-current", "x-site-host",
|
||||
"x-site-register"]
|
||||
|
||||
|
||||
class CoorsMiddleware(object):
|
||||
|
@ -39,7 +36,7 @@ class CoorsMiddleware(object):
|
|||
response["Access-Control-Allow-Origin"] = COORS_ALLOWED_ORIGINS
|
||||
response["Access-Control-Allow-Methods"] = ",".join(COORS_ALLOWED_METHODS)
|
||||
response["Access-Control-Allow-Headers"] = ",".join(COORS_ALLOWED_HEADERS)
|
||||
response["Access-Control-Expose-Headers"] = ",".join(COORS_EXPOSE_HEADERS + COORS_EXTRA_EXPOSE_HEADERS)
|
||||
response["Access-Control-Expose-Headers"] = ",".join(COORS_EXPOSE_HEADERS)
|
||||
response["Access-Control-Max-Age"] = "3600"
|
||||
|
||||
if COORS_ALLOWED_CREDENTIALS:
|
||||
|
|
|
@ -0,0 +1,50 @@
|
|||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
# License, or (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Affero General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from __future__ import print_function
|
||||
import sys
|
||||
|
||||
def patch_serializer():
|
||||
from rest_framework import serializers
|
||||
if hasattr(serializers.BaseSerializer, "_patched"):
|
||||
return
|
||||
|
||||
def to_native(self, obj):
|
||||
"""
|
||||
Serialize objects -> primitives.
|
||||
"""
|
||||
ret = self._dict_class()
|
||||
ret.fields = self._dict_class()
|
||||
ret.empty = obj is None
|
||||
|
||||
for field_name, field in self.fields.items():
|
||||
field.initialize(parent=self, field_name=field_name)
|
||||
key = self.get_field_key(field_name)
|
||||
ret.fields[key] = field
|
||||
|
||||
if obj is not None:
|
||||
value = field.field_to_native(obj, field_name)
|
||||
ret[key] = value
|
||||
|
||||
return ret
|
||||
|
||||
serializers.BaseSerializer._patched = True
|
||||
serializers.BaseSerializer.to_native = to_native
|
||||
|
||||
|
||||
def patch_restframework():
|
||||
from rest_framework import fields
|
||||
fields.strip_multiple_choice_msg = lambda x: x
|
|
@ -1,9 +1,7 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014-2017 Anler Hernández <hello@anler.me>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014 Anler Hernández <hello@anler.me>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -17,17 +15,67 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from functools import partial
|
||||
from collections import namedtuple
|
||||
|
||||
from django.db import connection
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.db.models.sql.datastructures import EmptyResultSet
|
||||
from taiga.base.api import serializers
|
||||
from taiga.base.fields import Field, MethodField
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
Neighbor = namedtuple("Neighbor", "left right")
|
||||
|
||||
|
||||
def disjunction_filters(filters):
|
||||
"""From a list of queryset filters, it returns a disjunction (OR) Q object.
|
||||
|
||||
:param filters: List of filters where each item is a dict where the keys are the lookups and
|
||||
the values the values of those lookups.
|
||||
|
||||
:return: :class:`django.db.models.Q` instance representing the disjunction of the filters.
|
||||
"""
|
||||
result = Q()
|
||||
for filter in filters:
|
||||
result |= Q(**{lookup: value for lookup, value in filter.items()})
|
||||
return result
|
||||
|
||||
|
||||
def get_attribute(obj, attr):
|
||||
"""Finds `attr` in obj.
|
||||
|
||||
:param obj: Object where to look for the attribute.
|
||||
:param attr: Attribute name as a string. It can be a Django lookup field such as
|
||||
`project__owner__name`, in which case it will look for `obj.project.owner.name`.
|
||||
|
||||
:return: The attribute value.
|
||||
:raises: `AttributeError` if some attribute doesn't exist.
|
||||
"""
|
||||
chunks = attr.lstrip("-").split("__")
|
||||
attr, chunks = chunks[0], chunks[1:]
|
||||
obj = value = getattr(obj, attr)
|
||||
for path in chunks:
|
||||
value = getattr(obj, path)
|
||||
obj = value
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def transform_field_into_lookup(name, value, operator="", operator_if_desc=""):
|
||||
"""From a field name and value, return a dict that may be used as a queryset filter.
|
||||
|
||||
:param name: Field name as a string.
|
||||
:param value: Field value.
|
||||
:param operator: Operator to use in the lookup.
|
||||
:param operator_if_desc: If the field is reversed (a "-" in front) use this operator
|
||||
instead.
|
||||
|
||||
:return: A dict that may be used as a queryset filter.
|
||||
"""
|
||||
if name.startswith("-"):
|
||||
name = name[1:]
|
||||
operator = operator_if_desc
|
||||
lookup = "{}{}".format(name, operator)
|
||||
return {lookup: value}
|
||||
|
||||
|
||||
def get_neighbors(obj, results_set=None):
|
||||
"""Get the neighbors of a model instance.
|
||||
|
||||
|
@ -41,76 +89,51 @@ def get_neighbors(obj, results_set=None):
|
|||
"""
|
||||
if results_set is None:
|
||||
results_set = type(obj).objects.get_queryset()
|
||||
|
||||
# Neighbors calculation is at least at project level
|
||||
results_set = results_set.filter(project_id=obj.project.id)
|
||||
|
||||
compiler = results_set.query.get_compiler('default')
|
||||
try:
|
||||
base_sql, base_params = compiler.as_sql(with_col_aliases=True)
|
||||
except EmptyResultSet:
|
||||
# Generate a not empty queryset
|
||||
results_set = type(obj).objects.get_queryset().filter(project_id=obj.project.id)
|
||||
compiler = results_set.query.get_compiler('default')
|
||||
base_sql, base_params = compiler.as_sql(with_col_aliases=True)
|
||||
|
||||
query = """
|
||||
SELECT * FROM
|
||||
(SELECT "col1" as id,
|
||||
ROW_NUMBER() OVER(),
|
||||
LAG("col1", 1) OVER() AS prev,
|
||||
LEAD("col1", 1) OVER() AS next
|
||||
FROM (%s) as ID_AND_ROW)
|
||||
AS SELECTED_ID_AND_ROW
|
||||
""" % (base_sql)
|
||||
query += " WHERE id=%s;"
|
||||
params = list(base_params) + [obj.id]
|
||||
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(query, params)
|
||||
row = cursor.fetchone()
|
||||
if row is None:
|
||||
return Neighbor(None, None)
|
||||
|
||||
left_object_id = row[2]
|
||||
right_object_id = row[3]
|
||||
|
||||
try:
|
||||
left = results_set.get(id=left_object_id)
|
||||
except ObjectDoesNotExist:
|
||||
left = _left_candidates(obj, results_set).reverse()[0]
|
||||
except IndexError:
|
||||
left = None
|
||||
|
||||
try:
|
||||
right = results_set.get(id=right_object_id)
|
||||
except ObjectDoesNotExist:
|
||||
right = _right_candidates(obj, results_set)[0]
|
||||
except IndexError:
|
||||
right = None
|
||||
|
||||
return Neighbor(left, right)
|
||||
|
||||
|
||||
class NeighborSerializer(serializers.LightSerializer):
|
||||
id = Field()
|
||||
ref = Field()
|
||||
subject = Field()
|
||||
def _get_candidates(obj, results_set, reverse=False):
|
||||
ordering = (results_set.query.order_by or []) + list(obj._meta.ordering)
|
||||
main_ordering, rest_ordering = ordering[0], ordering[1:]
|
||||
try:
|
||||
filters = obj.get_neighbors_additional_filters(results_set, ordering, reverse)
|
||||
if filters is None:
|
||||
raise AttributeError
|
||||
except AttributeError:
|
||||
filters = [order_field_as_filter(obj, main_ordering, reverse)]
|
||||
filters += [ordering_fields_as_filter(obj, main_ordering, rest_ordering, reverse)]
|
||||
|
||||
return (results_set
|
||||
.filter(~Q(id=obj.id), disjunction_filters(filters))
|
||||
.distinct()
|
||||
.order_by(*ordering))
|
||||
_left_candidates = partial(_get_candidates, reverse=True)
|
||||
_right_candidates = partial(_get_candidates, reverse=False)
|
||||
|
||||
|
||||
class NeighborsSerializerMixin(serializers.LightSerializer):
|
||||
neighbors = MethodField()
|
||||
|
||||
def serialize_neighbor(self, neighbor):
|
||||
if neighbor:
|
||||
return NeighborSerializer(neighbor).data
|
||||
return None
|
||||
|
||||
def get_neighbors(self, obj):
|
||||
view, request = self.context.get("view", None), self.context.get("request", None)
|
||||
if view and request:
|
||||
queryset = view.filter_queryset(view.get_queryset())
|
||||
left, right = get_neighbors(obj, results_set=queryset)
|
||||
def order_field_as_filter(obj, order_field, reverse=None, operator=None):
|
||||
value = get_attribute(obj, order_field)
|
||||
if reverse is not None:
|
||||
if operator is None:
|
||||
operator = ("__gt", "__lt")
|
||||
operator = (operator[1], operator[0]) if reverse else operator
|
||||
else:
|
||||
left = right = None
|
||||
operator = ()
|
||||
return transform_field_into_lookup(order_field, value, *operator)
|
||||
|
||||
return {
|
||||
"previous": self.serialize_neighbor(left),
|
||||
"next": self.serialize_neighbor(right)
|
||||
}
|
||||
|
||||
def ordering_fields_as_filter(obj, main_order_field, ordering_fields, reverse=False):
|
||||
"""Transform a list of ordering fields into a queryset filter."""
|
||||
filter = order_field_as_filter(obj, main_order_field)
|
||||
for field in ordering_fields:
|
||||
filter.update(order_field_as_filter(obj, field, reverse, ("__gte", "__lte")))
|
||||
return filter
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
|
||||
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
|
||||
# Copyright (C) 2014-2017 Anler Hernández <hello@anler.me>
|
||||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
|
||||
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
|
||||
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
|
||||
# Copyright (C) 2014 Anler Hernández <hello@anler.me>
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Affero General Public License as
|
||||
# published by the Free Software Foundation, either version 3 of the
|
||||
|
@ -17,116 +15,17 @@
|
|||
# You should have received a copy of the GNU Affero General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# The code is partially taken (and modified) from django rest framework
|
||||
# that is licensed under the following terms:
|
||||
#
|
||||
# Copyright (c) 2011-2014, Tom Christie
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are met:
|
||||
#
|
||||
# Redistributions of source code must retain the above copyright notice, this
|
||||
# list of conditions and the following disclaimer.
|
||||
# Redistributions in binary form must reproduce the above copyright notice, this
|
||||
# list of conditions and the following disclaimer in the documentation and/or
|
||||
# other materials provided with the distribution.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
"""The various HTTP responses for use in returning proper HTTP codes."""
|
||||
from http.client import responses
|
||||
|
||||
from django import http
|
||||
|
||||
from django.template.response import SimpleTemplateResponse
|
||||
from django.utils import six
|
||||
import rest_framework.response
|
||||
|
||||
|
||||
class Response(SimpleTemplateResponse):
|
||||
"""
|
||||
An HttpResponse that allows its data to be rendered into
|
||||
arbitrary media types.
|
||||
"""
|
||||
def __init__(self, data=None, status=None,
|
||||
template_name=None, headers=None,
|
||||
exception=False, content_type=None):
|
||||
"""
|
||||
Alters the init arguments slightly.
|
||||
For example, drop 'template_name', and instead use 'data'.
|
||||
|
||||
Setting 'renderer' and 'media_type' will typically be deferred,
|
||||
For example being set automatically by the `APIView`.
|
||||
"""
|
||||
super().__init__(None, status=status)
|
||||
self.data = data
|
||||
self.template_name = template_name
|
||||
self.exception = exception
|
||||
self.content_type = content_type
|
||||
|
||||
if headers:
|
||||
for name, value in six.iteritems(headers):
|
||||
self[name] = value
|
||||
|
||||
@property
|
||||
def rendered_content(self):
|
||||
renderer = getattr(self, "accepted_renderer", None)
|
||||
media_type = getattr(self, "accepted_media_type", None)
|
||||
context = getattr(self, "renderer_context", None)
|
||||
|
||||
assert renderer, ".accepted_renderer not set on Response"
|
||||
assert media_type, ".accepted_media_type not set on Response"
|
||||
assert context, ".renderer_context not set on Response"
|
||||
context["response"] = self
|
||||
|
||||
charset = renderer.charset
|
||||
content_type = self.content_type
|
||||
|
||||
if content_type is None and charset is not None:
|
||||
content_type = "{0}; charset={1}".format(media_type, charset)
|
||||
elif content_type is None:
|
||||
content_type = media_type
|
||||
self["Content-Type"] = content_type
|
||||
|
||||
ret = renderer.render(self.data, media_type, context)
|
||||
if isinstance(ret, six.text_type):
|
||||
assert charset, "renderer returned unicode, and did not specify " \
|
||||
"a charset value."
|
||||
return bytes(ret.encode(charset))
|
||||
|
||||
if not ret:
|
||||
del self["Content-Type"]
|
||||
|
||||
return ret
|
||||
|
||||
@property
|
||||
def status_text(self):
|
||||
"""
|
||||
Returns reason text corresponding to our HTTP response status code.
|
||||
Provided for convenience.
|
||||
"""
|
||||
# TODO: Deprecate and use a template tag instead
|
||||
# TODO: Status code text for RFC 6585 status codes
|
||||
return responses.get(self.status_code, '')
|
||||
|
||||
def __getstate__(self):
|
||||
"""
|
||||
Remove attributes from the response that shouldn't be cached
|
||||
"""
|
||||
state = super().__getstate__()
|
||||
for key in ("accepted_renderer", "renderer_context", "data"):
|
||||
if key in state:
|
||||
del state[key]
|
||||
return state
|
||||
class Response(rest_framework.response.Response):
|
||||
def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False,
|
||||
content_type=None):
|
||||
super(Response, self).__init__(data, status, template_name, headers, exception,
|
||||
content_type)
|
||||
|
||||
|
||||
class Ok(Response):
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue