Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c155c8a60d | |||
| dd8d9562ff | |||
| c6a43f0304 | |||
| ca52920690 | |||
| db934494e2 | |||
| 6dbbe74776 | |||
| 04bb9c550b | |||
| 65e398343b | |||
| df1d274a33 | |||
| 9cc771f381 | |||
| 66cd4ab5de | |||
| bd79423ba9 | |||
| 65abb8119f | |||
| f0f3256e01 | |||
| ab00eb9cf7 | |||
| 3ccf20212e | |||
| e008d1865e | |||
| 5506eacaeb | |||
| 29cb1ce14b | |||
| 4e69083284 | |||
| 05a58b1d62 | |||
| cc03b5cc08 | |||
| 385e35b322 | |||
| 9c6097a3d4 | |||
| 204eb1478a | |||
| e64b990dc8 | |||
| e358300085 | |||
| b8cb201652 | |||
| cba141724d | |||
| d64651e655 | |||
| 9d5d835910 | |||
| 9eb5f3466b | |||
| d66e636078 | |||
| a381089497 | |||
| aaa18ee0c6 | |||
| a07280975a | |||
| cb0244652d | |||
| 4a56a43bd5 | |||
| 4a366a1b97 |
+10
-6
@@ -1,10 +1,14 @@
|
||||
sudo: false
|
||||
language: python
|
||||
python:
|
||||
- "2.7"
|
||||
- "2.7"
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
- "pypy"
|
||||
- "pypy3"
|
||||
|
||||
install:
|
||||
- "pip install -r requirements.dev.txt"
|
||||
- "pip install ."
|
||||
install:
|
||||
- "pip install -r requirements.dev.txt"
|
||||
- "pip install ."
|
||||
|
||||
|
||||
script: nosetests
|
||||
script: python setup.py test
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
============
|
||||
Contributing
|
||||
============
|
||||
|
||||
For patches, please ensure that all existing tests pass, that you have adequate
|
||||
tests added as necessary, and that all code is documented! The latter is
|
||||
critical. If you add or update an existing function, class, or module, please
|
||||
ensure you add a docstring or ensure the existing docstring is up-to-date.
|
||||
|
||||
Please use `Google docstring format
|
||||
<http://sphinxcontrib-napoleon.readthedocs.org/en/latest/example_google.html>`_.
|
||||
|
||||
This *will* be enforced.
|
||||
|
||||
Testing
|
||||
=======
|
||||
|
||||
The best way to run the tests is with `tox <http://tox.readthedocs.org/en/latest/>`_::
|
||||
|
||||
pip install tox
|
||||
detox
|
||||
|
||||
Or it's slightly faster cousin `detox
|
||||
<https://pypi.python.org/pypi/detox>`_ which will parallelize test runs::
|
||||
|
||||
pip install detox
|
||||
detox
|
||||
|
||||
Alternatively, you can run the self test with the following commands::
|
||||
|
||||
pip install -r requirements.dev.txt
|
||||
pip install -e .
|
||||
python setup.py test
|
||||
|
||||
Live Testing
|
||||
============
|
||||
|
||||
You can test against a Discourse instance by following the [Official Discourse developement instructions][discoursedev].
|
||||
For the impatient here is the quick and dirty version::
|
||||
|
||||
git clone git@github.com:discourse/discourse.git
|
||||
cd discourse
|
||||
vagrant up
|
||||
vagrant ssh
|
||||
cd /vagrant
|
||||
bundle install
|
||||
bundle exec rake db:migrate
|
||||
bundle exec rails s
|
||||
|
||||
Once running you can access the Discourse install at http://localhost:4000.
|
||||
|
||||
[discoursedev]: https://github.com/discourse/discourse/blob/master/docs/VAGRANT.md "Discourse Vagrant"
|
||||
|
||||
TODO
|
||||
====
|
||||
|
||||
Refer to, https://github.com/discourse/discourse_api/blob/master/routes.txt for
|
||||
a list of all operations available in Discourse.
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
Development
|
||||
------------
|
||||
Refer to, https://github.com/discourse/discourse_api/blob/master/routes.txt for a list of all operations available in Discourse.
|
||||
|
||||
Unit tests
|
||||
--------------
|
||||
You can run the self test with the following commands::
|
||||
|
||||
pip install -r requirements.dev.txt
|
||||
pip install -e .
|
||||
nosetests
|
||||
|
||||
Live Testing
|
||||
-----------------
|
||||
|
||||
You can test against a Discourse instance by following the [Official Discourse developement instructions][discoursedev].
|
||||
For the impatient here is the quick and dirty version::
|
||||
|
||||
git clone git@github.com:discourse/discourse.git
|
||||
cd discourse
|
||||
vagrant up
|
||||
vagrant ssh
|
||||
cd /vagrant
|
||||
bundle install
|
||||
bundle exec rake db:migrate
|
||||
bundle exec rails s
|
||||
|
||||
Once running you can access the Discourse install at http://localhost:4000.
|
||||
|
||||
[discoursedev]: https://github.com/discourse/discourse/blob/master/docs/VAGRANT.md "Discourse Vagrant"
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
=========
|
||||
Changelog
|
||||
=========
|
||||
|
||||
0.2.0
|
||||
=====
|
||||
|
||||
* Inital fork, including gberaudo's changes
|
||||
* Packaging cleanup, dropping Python 2.6 support and adding Python 3.5, PyPy,
|
||||
PyPy3
|
||||
* Packaging on PyPI
|
||||
|
||||
0.1.0.dev
|
||||
=========
|
||||
|
||||
All pre-PyPI development
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
.PHONY: clean-pyc clean-build docs clean
|
||||
|
||||
clean: clean-build clean-pyc clean-test-all
|
||||
|
||||
clean-build:
|
||||
@rm -rf build/
|
||||
@rm -rf dist/
|
||||
@rm -rf *.egg-info
|
||||
|
||||
clean-pyc:
|
||||
-@find . -name '*.pyc' -follow -print0 | xargs -0 rm -f &> /dev/null
|
||||
-@find . -name '*.pyo' -follow -print0 | xargs -0 rm -f &> /dev/null
|
||||
-@find . -name '__pycache__' -type d -follow -print0 | xargs -0 rm -rf &> /dev/null
|
||||
|
||||
clean-test:
|
||||
rm -rf .coverage coverage*
|
||||
rm -rf tests/.coverage test/coverage*
|
||||
rm -rf htmlcov/
|
||||
|
||||
clean-test-all: clean-test
|
||||
rm -rf .tox/
|
||||
|
||||
lint:
|
||||
flake8 pydiscourse
|
||||
|
||||
test: ## Run test suite against current Python path
|
||||
python setup.py test
|
||||
|
||||
test-coverage: clean-test
|
||||
-py.test ${COVER_FLAGS} ${TEST_FLAGS}
|
||||
@exit_code=$?
|
||||
@-coverage html
|
||||
@exit ${exit_code}
|
||||
|
||||
test-all: ## Run all tox test environments, parallelized
|
||||
detox
|
||||
|
||||
check: clean-build clean-pyc clean-test lint test-coverage
|
||||
|
||||
release: clean ## Uploads new source and wheel distributions (cleans first)
|
||||
python setup.py sdist upload
|
||||
python setup.py bdist_wheel upload
|
||||
|
||||
dist: clean ## Creates new source and wheel distributions (cleans first)
|
||||
python setup.py sdist
|
||||
python setup.py bdist_wheel
|
||||
ls -l dist
|
||||
|
||||
docs: ## Builds and open docs
|
||||
$(MAKE) -C docs clean
|
||||
$(MAKE) -C docs html
|
||||
open docs/_build/html/index.html
|
||||
|
||||
help:
|
||||
@perl -nle'print $& if m{^[a-zA-Z_-]+:.*?## .*$$}' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
|
||||
@@ -1,33 +0,0 @@
|
||||
pydiscourse
|
||||
------------
|
||||
A Python library for the Discourse API.
|
||||
Its pretty basic right now but you need to start somewhere.
|
||||
|
||||
Examples
|
||||
-----------
|
||||
Create a client connection to a Discourse server::
|
||||
|
||||
from pydiscourse.client import DiscourseClient
|
||||
client = DiscourseClient('http://example.com', api_username='username', api_key='areallylongstringfromdiscourse')
|
||||
|
||||
Get info about a user::
|
||||
|
||||
user = client.user('eviltrout')
|
||||
print user
|
||||
|
||||
user_topics = client.topics_by('johnsmith')
|
||||
print user_topics
|
||||
|
||||
Create a new user::
|
||||
|
||||
user = client.create_user('The Black Knight', 'blacknight', 'knight@python.org', 'justafleshwound')
|
||||
|
||||
Command line
|
||||
----------------
|
||||
|
||||
To help experiment with the Discourse API, pydiscourse provides a simple command line client::
|
||||
|
||||
export DISCOURSE_API_KEY=your_master_key
|
||||
pydiscoursecli --host=http://yourhost --api-username=system latest_topics
|
||||
pydiscoursecli --host=http://yourhost --api-username=system topics_by johnsmith
|
||||
pydiscoursecli --host=http://yourhost --api-username=system user eviltrout
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
===========
|
||||
pydiscourse
|
||||
===========
|
||||
|
||||
A Python library for working with Discourse.
|
||||
|
||||
This is a fork of the original Tindie version. It was forked to include fixes,
|
||||
additional functionality, and to distribute a package on PyPI.
|
||||
|
||||
Goals
|
||||
=====
|
||||
|
||||
* Provide functional parity with the Discourse API, for the currently supported
|
||||
version of Discourse (something of a moving target)
|
||||
* Support all supported Python versions
|
||||
* Document API
|
||||
|
||||
Examples
|
||||
========
|
||||
|
||||
Create a client connection to a Discourse server::
|
||||
|
||||
from pydiscourse.client import DiscourseClient
|
||||
client = DiscourseClient(
|
||||
'http://example.com',
|
||||
api_username='username',
|
||||
api_key='areallylongstringfromdiscourse')
|
||||
|
||||
Get info about a user::
|
||||
|
||||
user = client.user('eviltrout')
|
||||
print user
|
||||
|
||||
user_topics = client.topics_by('johnsmith')
|
||||
print user_topics
|
||||
|
||||
Create a new user::
|
||||
|
||||
user = client.create_user('The Black Knight', 'blacknight', 'knight@python.org', 'justafleshwound')
|
||||
|
||||
Implement SSO for Discourse with your Python server::
|
||||
|
||||
@login_required
|
||||
def discourse_sso_view(request):
|
||||
payload = request.GET.get('sso')
|
||||
signature = request.GET.get('sig')
|
||||
nonce = sso_validate(payload, signature, SECRET)
|
||||
url = sso_redirect_url(nonce, SECRET, request.user.email, request.user.id, request.user.username)
|
||||
return redirect('http://discuss.example.com' + url)
|
||||
|
||||
Command line
|
||||
============
|
||||
|
||||
To help experiment with the Discourse API, pydiscourse provides a simple command line client::
|
||||
|
||||
export DISCOURSE_API_KEY=your_master_key
|
||||
pydiscoursecli --host-http://yourhost --api-user-system latest_topics
|
||||
pydiscoursecli --host-http://yourhost --api-user-system topics_by johnsmith
|
||||
pydiscoursecli --host-http://yourhost --api-user-system user eviltrout
|
||||
+2
-2
@@ -53,9 +53,9 @@ copyright = u'2014, Marc Sibson'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '0.1'
|
||||
version = '0.2.0'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '0.1'
|
||||
release = '0.2.0'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
Development
|
||||
===============
|
||||
.. include:: ../DEVELOP.md
|
||||
:start-line: 2
|
||||
|
||||
.. include:: ../CONTRIBUTING.rst
|
||||
:start-line: 3
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
Introduction
|
||||
==============
|
||||
.. include:: ../README.md
|
||||
:start-line: 2
|
||||
|
||||
.. include:: ../README.rst
|
||||
:start-line: 3
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = '0.1.0.dev'
|
||||
__version__ = '0.2.0'
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
""" A higher level API wrapper for communicating with a Discourse instance
|
||||
|
||||
EXPERIMENTAL, subject to complete and radical change
|
||||
|
||||
Goal
|
||||
------
|
||||
A pythonic wrapper around the discourse API that minimizes requests by lazy loading of data.
|
||||
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def datetime_from(date):
|
||||
DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
|
||||
# XXX not handling timezone, but we're not using it yet
|
||||
return datetime.strptime(date[:-6], DATE_FORMAT)
|
||||
|
||||
|
||||
class DiscourseUser(object):
|
||||
username = None
|
||||
userid = None
|
||||
avatar_template = None
|
||||
default_avatar_size = 40
|
||||
|
||||
def avatar(self, size=None):
|
||||
if size is None:
|
||||
size = self.default_avatar_size
|
||||
return self.avatar_template.replace(u'{size}', unicode(size))
|
||||
|
||||
def __repr__(self):
|
||||
return '<DiscourseUser {0} {1}>'.format(self.userid, self.username)
|
||||
|
||||
@classmethod
|
||||
def from_summary(cls, summary):
|
||||
instance = cls()
|
||||
instance.username = summary['username']
|
||||
instance.userid = summary['id']
|
||||
instance.avatar_template = summary['avatar_template']
|
||||
|
||||
return instance
|
||||
|
||||
|
||||
class DiscourseUserSet(object):
|
||||
def __init__(self, users):
|
||||
self.users = users
|
||||
|
||||
self.byname = {u.username: u for u in users}
|
||||
self.byid = {u.userid: u for u in users}
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.users)
|
||||
|
||||
def __getitem__(self, item):
|
||||
try:
|
||||
return self.byname[item]
|
||||
except KeyError:
|
||||
return self.byid[item]
|
||||
|
||||
@classmethod
|
||||
def from_response(cls, response):
|
||||
users = [DiscourseUser.from_summary(u) for u in response.get('users', [])]
|
||||
return cls(users)
|
||||
|
||||
|
||||
class DiscoursePost(object):
|
||||
default_avatar_size = 40
|
||||
|
||||
def avatar(self, size=None):
|
||||
if size is None:
|
||||
size = self.default_avatar_size
|
||||
return self.avatar_template.replace(u'{size}', unicode(size))
|
||||
|
||||
def date_created(self):
|
||||
return datetime_from(self.data['created_at'])
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data):
|
||||
instance = cls()
|
||||
instance.data = data
|
||||
|
||||
return instance
|
||||
|
||||
def __getattr__(self, attr):
|
||||
return self.data[attr]
|
||||
|
||||
|
||||
class DiscourseTopic(object):
|
||||
def __init__(self):
|
||||
self.posts = None
|
||||
self.data = None
|
||||
self.raw_response = None
|
||||
|
||||
def created_by(self):
|
||||
return DiscourseUser.from_summary(self.data['details']['created_by'])
|
||||
|
||||
def created_at(self):
|
||||
return datetime_from(self.data['created_at'])
|
||||
|
||||
def last_posted_at(self):
|
||||
return datetime_from(self.data['last_posted_at'])
|
||||
|
||||
def num_unread(self):
|
||||
if self.data['unseen']:
|
||||
return 1
|
||||
|
||||
return self.data['new_posts']
|
||||
|
||||
def participants(self):
|
||||
return [DiscourseUser.from_summary(u) for u in self.data['participants']]
|
||||
|
||||
@classmethod
|
||||
def from_response(cls, response):
|
||||
instance = DiscourseTopic.from_dict(response)
|
||||
instance.raw_response = response
|
||||
instance.posts = []
|
||||
for post in response['post_stream']['posts']:
|
||||
instance.posts.append(DiscoursePost.from_dict(post))
|
||||
|
||||
return instance
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data):
|
||||
instance = cls()
|
||||
instance.data = data
|
||||
return instance
|
||||
|
||||
def fetch_remaining_posts(self, discourse):
|
||||
""" The initial topic response is paginated, this makes another request to get additional posts
|
||||
"""
|
||||
if self.data['posts_count'] > len(self.posts):
|
||||
missing = self.data['post_stream']['stream'][len(self.posts):]
|
||||
response = discourse.posts(self.id, missing)
|
||||
for post in response['post_stream']['posts']:
|
||||
self.posts.append(DiscoursePost.from_dict(post))
|
||||
|
||||
def __getattr__(self, attr):
|
||||
return self.data[attr]
|
||||
|
||||
def __repr__(self):
|
||||
return u'<Topic {0}>'.format(self.title)
|
||||
|
||||
|
||||
class DiscourseTopicSet(object):
|
||||
def __init__(self, topics):
|
||||
self.topics = topics
|
||||
|
||||
def all(self):
|
||||
return self.topics
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self.topics)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.topics)
|
||||
|
||||
@classmethod
|
||||
def from_response(cls, response):
|
||||
topics = response.get('topic_list', {}).get('topics', [])
|
||||
topics = [DiscourseTopic.from_dict(t) for t in topics]
|
||||
return cls(topics)
|
||||
+92
-10
@@ -4,6 +4,7 @@ import logging
|
||||
import requests
|
||||
|
||||
from pydiscourse.exceptions import DiscourseError, DiscourseServerError, DiscourseClientError
|
||||
from pydiscourse.sso import sso_payload
|
||||
|
||||
|
||||
log = logging.getLogger('pydiscourse.client')
|
||||
@@ -32,9 +33,23 @@ class DiscourseClient(object):
|
||||
return self._post('/users', name=name, username=username, email=email,
|
||||
password=password, password_confirmation=confirmations, challenge=challenge, **kwargs)
|
||||
|
||||
def by_external_id(self, external_id):
|
||||
response = self._get("/users/by-external/{0}".format(external_id))
|
||||
return response['user']
|
||||
|
||||
def log_out(self, userid):
|
||||
return self._post('/admin/users/{0}/log_out'.format(userid))
|
||||
|
||||
def trust_level(self, userid, level):
|
||||
return self._put('/admin/users/{0}/trust_level'.format(userid), level=level)
|
||||
|
||||
def suspend(self, userid, duration, reason):
|
||||
return self._put('/admin/users/{0}/suspend'.format(userid), duration=duration, reason=reason)
|
||||
|
||||
def list_users(self, type, **kwargs):
|
||||
""" optional user search: filter='test@example.com' or filter='scott' """
|
||||
return self._get('/admin/users/list/{0}.json'.format(type), **kwargs)
|
||||
|
||||
def update_avatar_from_url(self, username, url, **kwargs):
|
||||
return self._post('/users/{0}/preferences/avatar'.format(username), file=url, **kwargs)
|
||||
|
||||
@@ -44,13 +59,16 @@ class DiscourseClient(object):
|
||||
|
||||
def toggle_gravatar(self, username, state=True, **kwargs):
|
||||
url = '/users/{0}/preferences/avatar/toggle'.format(username)
|
||||
|
||||
if bool(state):
|
||||
kwargs['use_uploaded_avatar'] = 'true'
|
||||
else:
|
||||
kwargs['use_uploaded_avatar'] = 'false'
|
||||
return self._put(url, **kwargs)
|
||||
|
||||
def pick_avatar(self, username, gravatar=True, generated=False, **kwargs):
|
||||
url = '/users/{0}/preferences/avatar/pick'.format(username)
|
||||
return self._put(url, **kwargs)
|
||||
|
||||
def update_email(self, username, email, **kwargs):
|
||||
return self._put('/users/{0}/preferences/email'.format(username), email=email, **kwargs)
|
||||
|
||||
@@ -60,6 +78,17 @@ class DiscourseClient(object):
|
||||
def update_username(self, username, new_username, **kwargs):
|
||||
return self._put('/users/{0}/preferences/username'.format(username), username=new_username, **kwargs)
|
||||
|
||||
def set_preference(self, username=None, **kwargs):
|
||||
if username is None:
|
||||
username = self.api_username
|
||||
return self._put(u'/users/{0}'.format(username), **kwargs)
|
||||
|
||||
def sync_sso(self, **kwargs):
|
||||
# expect sso_secret, name, username, email, external_id, avatar_url, avatar_force_update
|
||||
sso_secret = kwargs.pop('sso_secret')
|
||||
payload = sso_payload(sso_secret, **kwargs)
|
||||
return self._post('/admin/users/sync_sso?{0}'.format(payload), **kwargs)
|
||||
|
||||
def generate_api_key(self, userid, **kwargs):
|
||||
return self._post('/admin/users/{0}/generate_api_key'.format(userid), **kwargs)
|
||||
|
||||
@@ -71,11 +100,22 @@ class DiscourseClient(object):
|
||||
"""
|
||||
return self._delete('/admin/users/{0}.json'.format(userid), **kwargs)
|
||||
|
||||
def users(self, filter=None, **kwargs):
|
||||
if filter is None:
|
||||
filter = 'active'
|
||||
|
||||
return self._get('/admin/users/list/{0}.json'.format(filter), **kwargs)
|
||||
|
||||
def private_messages(self, username=None, **kwargs):
|
||||
if username is None:
|
||||
username = self.api_username
|
||||
return self._get('/topics/private-messages/{0}.json'.format(username), **kwargs)
|
||||
|
||||
def private_messages_unread(self, username=None, **kwargs):
|
||||
if username is None:
|
||||
username = self.api_username
|
||||
return self._get('/topics/private-messages-unread/{0}.json'.format(username), **kwargs)
|
||||
|
||||
def hot_topics(self, **kwargs):
|
||||
return self._get('/hot.json', **kwargs)
|
||||
|
||||
@@ -85,8 +125,8 @@ class DiscourseClient(object):
|
||||
def new_topics(self, **kwargs):
|
||||
return self._get('/new.json', **kwargs)
|
||||
|
||||
def topic(self, topic_id, **kwargs):
|
||||
return self._get('/t/{0}.json'.format(topic_id), **kwargs)
|
||||
def topic(self, slug, topic_id, **kwargs):
|
||||
return self._get('/t/{0}/{1}.json'.format(slug, topic_id), **kwargs)
|
||||
|
||||
def post(self, topic_id, post_id, **kwargs):
|
||||
return self._get('/t/{0}/{1}.json'.format(topic_id, post_id), **kwargs)
|
||||
@@ -123,6 +163,11 @@ class DiscourseClient(object):
|
||||
"""
|
||||
return self._post('/posts', raw=content, **kwargs)
|
||||
|
||||
def update_post(self, post_id, content, edit_reason='', **kwargs):
|
||||
kwargs['post[raw]'] = content
|
||||
kwargs['post[edit_reason]'] = edit_reason
|
||||
return self._put('/posts/{0}'.format(post_id), **kwargs)
|
||||
|
||||
def topics_by(self, username, **kwargs):
|
||||
url = '/topics/created-by/{0}.json'.format(username)
|
||||
return self._get(url, **kwargs)['topic_list']['topics']
|
||||
@@ -138,9 +183,42 @@ class DiscourseClient(object):
|
||||
kwargs['term'] = term
|
||||
return self._get('/search.json', **kwargs)
|
||||
|
||||
def create_category(self, name, color, text_color='FFFFFF', permissions=None, parent=None, **kwargs):
|
||||
""" permissions - dict of 'everyone', 'admins', 'moderators', 'staff' with values of
|
||||
"""
|
||||
|
||||
kwargs['name'] = name
|
||||
kwargs['color'] = color
|
||||
kwargs['text_color'] = text_color
|
||||
|
||||
if permissions is None and 'permissions' not in kwargs:
|
||||
permissions = {'everyone': '1'}
|
||||
|
||||
for key, value in permissions.items():
|
||||
kwargs['permissions[{0}]'.format(key)] = value
|
||||
|
||||
if parent:
|
||||
parent_id = None
|
||||
for category in self.categories():
|
||||
if category['name'] == parent:
|
||||
parent_id = category['id']
|
||||
continue
|
||||
|
||||
if not parent_id:
|
||||
raise DiscourseClientError(u'{0} not found'.format(parent))
|
||||
kwargs['parent_category_id'] = parent_id
|
||||
|
||||
return self._post('/categories', **kwargs)
|
||||
|
||||
def categories(self, **kwargs):
|
||||
return self._get('/categories.json', **kwargs)['category_list']['categories']
|
||||
|
||||
def category(self, name, parent=None, **kwargs):
|
||||
if parent:
|
||||
name = u'{0}/{1}'.format(parent, name)
|
||||
|
||||
return self._get(u'/category/{0}.json'.format(name), **kwargs)
|
||||
|
||||
def site_settings(self, **kwargs):
|
||||
for setting, value in kwargs.items():
|
||||
setting = setting.replace(' ', '_')
|
||||
@@ -164,16 +242,20 @@ class DiscourseClient(object):
|
||||
params['api_username'] = self.api_username
|
||||
url = self.host + path
|
||||
|
||||
response = requests.request(verb, url, allow_redirects=False, params=params, timeout=self.timeout)
|
||||
headers = {'Accept': 'application/json; charset=utf-8'}
|
||||
|
||||
response = requests.request(
|
||||
verb, url, allow_redirects=False, params=params, headers=headers,
|
||||
timeout=self.timeout)
|
||||
|
||||
log.debug('response %s: %s', response.status_code, repr(response.text))
|
||||
if not response.ok:
|
||||
if response.reason:
|
||||
msg = response.reason
|
||||
else:
|
||||
try:
|
||||
msg = u','.join(response.json()['errors'])
|
||||
except (ValueError, TypeError, KeyError):
|
||||
try:
|
||||
msg = u','.join(response.json()['errors'])
|
||||
except (ValueError, TypeError, KeyError):
|
||||
if response.reason:
|
||||
msg = response.reason
|
||||
else:
|
||||
msg = u'{0}: {1}'.format(response.status_code, response.text)
|
||||
|
||||
if 400 <= response.status_code < 500:
|
||||
|
||||
+9
-2
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import cmd
|
||||
import json
|
||||
import optparse
|
||||
@@ -30,7 +31,7 @@ class DiscourseCmd(cmd.Cmd):
|
||||
try:
|
||||
return method(*args, **kwargs)
|
||||
except DiscourseError as e:
|
||||
print e, e.response.text
|
||||
print (e, e.response.text)
|
||||
return e.response
|
||||
return wrapper
|
||||
|
||||
@@ -57,8 +58,14 @@ def main():
|
||||
op.add_option('--api-user', default='system')
|
||||
op.add_option('-v', '--verbose', action='store_true')
|
||||
|
||||
api_key = os.environ['DISCOURSE_API_KEY']
|
||||
options, args = op.parse_args()
|
||||
if not options.host.startswith('http'):
|
||||
op.error('host must include protocol, eg http://')
|
||||
|
||||
api_key = os.environ.get('DISCOURSE_API_KEY')
|
||||
if not api_key:
|
||||
op.error('please set DISCOURSE_API_KEY')
|
||||
|
||||
client = DiscourseClient(options.host, options.api_user, api_key)
|
||||
|
||||
if options.verbose:
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
Utilities to implement Single Sign On for Discourse with a Python managed authentication DB
|
||||
|
||||
https://meta.discourse.org/t/official-single-sign-on-for-discourse/13045
|
||||
|
||||
Thanks to James Potter for the heavy lifting, detailed at https://meta.discourse.org/t/sso-example-for-django/14258
|
||||
|
||||
A SSO request handler might look something like
|
||||
|
||||
@login_required
|
||||
def discourse_sso_view(request):
|
||||
payload = request.GET.get('sso')
|
||||
signature = request.GET.get('sig')
|
||||
try:
|
||||
nonce = sso_validate(payload, signature, SECRET)
|
||||
except DiscourseError as e:
|
||||
return HTTP400(e.args[0])
|
||||
|
||||
url = sso_redirect_url(nonce, SECRET, request.user.email, request.user.id, request.user.username)
|
||||
return redirect('http://discuss.example.com' + url)
|
||||
"""
|
||||
from base64 import b64encode, b64decode
|
||||
import hmac
|
||||
import hashlib
|
||||
|
||||
try: # py3
|
||||
from urllib.parse import unquote, urlencode
|
||||
except ImportError:
|
||||
from urllib import unquote, urlencode
|
||||
|
||||
|
||||
from pydiscourse.exceptions import DiscourseError
|
||||
|
||||
|
||||
def sso_validate(payload, signature, secret):
|
||||
"""
|
||||
payload: provided by Discourse HTTP call to your SSO endpoint as sso GET param
|
||||
signature: provided by Discourse HTTP call to your SSO endpoint as sig GET param
|
||||
secret: the secret key you entered into Discourse sso secret
|
||||
|
||||
return value: The nonce used by discourse to validate the redirect URL
|
||||
"""
|
||||
if None in [payload, signature]:
|
||||
raise DiscourseError('No SSO payload or signature.')
|
||||
|
||||
if not secret:
|
||||
raise DiscourseError('Invalid secret..')
|
||||
|
||||
payload = unquote(payload)
|
||||
if not payload:
|
||||
raise DiscourseError('Invalid payload..')
|
||||
|
||||
decoded = b64decode(payload.encode('utf-8')).decode('utf-8')
|
||||
if 'nonce' not in decoded:
|
||||
raise DiscourseError('Invalid payload..')
|
||||
|
||||
h = hmac.new(secret.encode('utf-8'), payload.encode('utf-8'), digestmod=hashlib.sha256)
|
||||
this_signature = h.hexdigest()
|
||||
|
||||
if this_signature != signature:
|
||||
raise DiscourseError('Payload does not match signature.')
|
||||
|
||||
nonce = decoded.split('=')[1]
|
||||
|
||||
return nonce
|
||||
|
||||
|
||||
def sso_payload(secret, **kwargs):
|
||||
return_payload = b64encode(urlencode(kwargs).encode('utf-8'))
|
||||
h = hmac.new(secret.encode('utf-8'), return_payload, digestmod=hashlib.sha256)
|
||||
query_string = urlencode({'sso': return_payload, 'sig': h.hexdigest()})
|
||||
return query_string
|
||||
|
||||
|
||||
def sso_redirect_url(nonce, secret, email, external_id, username, **kwargs):
|
||||
"""
|
||||
nonce: returned by sso_validate()
|
||||
secret: the secret key you entered into Discourse sso secret
|
||||
user_email: email address of the user who logged in
|
||||
user_id: the internal id of the logged in user
|
||||
user_username: username of the logged in user
|
||||
|
||||
return value: URL to redirect users back to discourse, now logged in as user_username
|
||||
"""
|
||||
kwargs.update({
|
||||
'nonce': nonce,
|
||||
'email': email,
|
||||
'external_id': external_id,
|
||||
'username': username
|
||||
})
|
||||
|
||||
return '/session/sso_login?%s' % sso_payload(secret, **kwargs)
|
||||
@@ -1,3 +0,0 @@
|
||||
requests
|
||||
nose
|
||||
mock
|
||||
@@ -1,40 +1,23 @@
|
||||
import codecs
|
||||
import os
|
||||
|
||||
from setuptools import setup, find_packages
|
||||
|
||||
|
||||
def read(fname):
|
||||
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
|
||||
|
||||
|
||||
# Provided as an attribute, so you can append to these instead
|
||||
# of replicating them:
|
||||
standard_exclude = ["*.py", "*.pyc", "*$py.class", "*~", ".*", "*.bak"]
|
||||
standard_exclude_directories = [
|
||||
".*", "CVS", "_darcs", "./build", "./dist", "EGG-INFO", "*.egg-info"
|
||||
]
|
||||
|
||||
|
||||
NAME = "pydiscourse"
|
||||
DESCRIPTION = "A Python library for the Discourse API"
|
||||
AUTHOR = "Marc Sibson"
|
||||
AUTHOR_EMAIL = "sibson@gmail.com"
|
||||
URL = "https://github.com/tindie/pydiscourse"
|
||||
PACKAGE = "pydiscourse"
|
||||
VERSION = __import__(PACKAGE).__version__
|
||||
README = open('README.rst').read()
|
||||
VERSION = __import__("pydiscourse").__version__
|
||||
|
||||
|
||||
setup(
|
||||
name=NAME,
|
||||
name="pydiscourse",
|
||||
version=VERSION,
|
||||
description=DESCRIPTION,
|
||||
long_description=read("README.md"),
|
||||
author=AUTHOR,
|
||||
author_email=AUTHOR_EMAIL,
|
||||
description="A Python library for the Discourse API",
|
||||
long_description=README,
|
||||
author="Marc Sibson and contributors",
|
||||
author_email="ben+pydiscourse@benlopatin.com",
|
||||
license="BSD",
|
||||
url=URL,
|
||||
url="https://github.com/bennylope/pydiscourse",
|
||||
packages=find_packages(exclude=["tests.*", "tests"]),
|
||||
install_requires=['requests>=2.0.0'],
|
||||
tests_require=['mock'],
|
||||
test_suite='tests',
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'pydiscoursecli = pydiscourse.main:main'
|
||||
@@ -47,6 +30,10 @@ setup(
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 2.7",
|
||||
"Programming Language :: Python :: 3.4",
|
||||
"Programming Language :: Python :: 3.5",
|
||||
'Programming Language :: Python :: Implementation :: PyPy',
|
||||
],
|
||||
zip_safe=False,
|
||||
)
|
||||
|
||||
@@ -82,8 +82,8 @@ class TestTopics(ClientBaseTestCase):
|
||||
|
||||
def test_topic(self, request):
|
||||
prepare_response(request)
|
||||
self.client.topic(22)
|
||||
self.assertRequestCalled(request, 'GET', '/t/22.json')
|
||||
self.client.topic('some-test-slug', 22)
|
||||
self.assertRequestCalled(request, 'GET', '/t/some-test-slug/22.json')
|
||||
|
||||
def test_topics_by(self, request):
|
||||
prepare_response(request)
|
||||
@@ -111,3 +111,8 @@ class MiscellaneousTests(ClientBaseTestCase):
|
||||
r = self.client.categories()
|
||||
self.assertRequestCalled(request, 'GET', '/categories.json')
|
||||
self.assertEqual(r, request().json()['category_list']['categories'])
|
||||
|
||||
def test_users(self, request):
|
||||
prepare_response(request)
|
||||
r = self.client.users()
|
||||
self.assertRequestCalled(request, 'GET', '/admin/users/list/active.json')
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
from base64 import b64decode
|
||||
|
||||
try: # py26
|
||||
import unittest2 as unittest
|
||||
except ImportError:
|
||||
import unittest
|
||||
|
||||
|
||||
try: # py3
|
||||
from urllib.parse import unquote
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
except ImportError:
|
||||
from urlparse import urlparse, parse_qs
|
||||
from urllib import unquote
|
||||
|
||||
|
||||
from pydiscourse import sso
|
||||
from pydiscourse.exceptions import DiscourseError
|
||||
|
||||
|
||||
class SSOTestCase(unittest.TestCase):
|
||||
def setUp(self):
|
||||
# values from https://meta.discourse.org/t/official-single-sign-on-for-discourse/13045
|
||||
self.secret = 'd836444a9e4084d5b224a60c208dce14'
|
||||
self.nonce = 'cb68251eefb5211e58c00ff1395f0c0b'
|
||||
self.payload = 'bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGI%3D%0A'
|
||||
self.signature = '2828aa29899722b35a2f191d34ef9b3ce695e0e6eeec47deb46d588d70c7cb56'
|
||||
|
||||
self.name = u'sam'
|
||||
self.username = u'samsam'
|
||||
self.external_id = u'hello123'
|
||||
self.email = u'test@test.com'
|
||||
self.redirect_url = u'/session/sso_login?sso=bm9uY2U9Y2I2ODI1MWVlZmI1MjExZTU4YzAwZmYxMzk1ZjBjMGImbmFtZT1z%0AYW0mdXNlcm5hbWU9c2Ftc2FtJmVtYWlsPXRlc3QlNDB0ZXN0LmNvbSZleHRl%0Acm5hbF9pZD1oZWxsbzEyMw%3D%3D%0A&sig=1c884222282f3feacd76802a9dd94e8bc8deba5d619b292bed75d63eb3152c0b'
|
||||
|
||||
|
||||
class Test_sso_validate(SSOTestCase):
|
||||
def test_missing_args(self):
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate(None, self.signature, self.secret)
|
||||
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate('', self.signature, self.secret)
|
||||
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate(self.payload, None, self.secret)
|
||||
|
||||
def test_invalid_signature(self):
|
||||
with self.assertRaises(DiscourseError):
|
||||
sso.sso_validate(self.payload, 'notavalidsignature', self.secret)
|
||||
|
||||
def test_valid_nonce(self):
|
||||
nonce = sso.sso_validate(self.payload, self.signature, self.secret)
|
||||
self.assertEqual(nonce, self.nonce)
|
||||
|
||||
|
||||
class Test_sso_redirect_url(SSOTestCase):
|
||||
def test_valid_redirect_url(self):
|
||||
url = sso.sso_redirect_url(self.nonce, self.secret, self.email, self.external_id, self.username, name='sam')
|
||||
|
||||
self.assertIn('/session/sso_login', url[:20])
|
||||
|
||||
# check its valid, using our own handy validator
|
||||
params = parse_qs(urlparse(url).query)
|
||||
payload = params['sso'][0]
|
||||
sso.sso_validate(payload, params['sig'][0], self.secret)
|
||||
|
||||
# check the params have all the data we expect
|
||||
payload = b64decode(payload.encode('utf-8')).decode('utf-8')
|
||||
payload = unquote(payload)
|
||||
payload = dict((p.split('=') for p in payload.split('&')))
|
||||
|
||||
self.assertEqual(payload, {
|
||||
'username': self.username,
|
||||
'nonce': self.nonce,
|
||||
'external_id': self.external_id,
|
||||
'name': self.name,
|
||||
'email': self.email
|
||||
})
|
||||
Reference in New Issue
Block a user